How to programmatically set SelectedValue of Dropdownlist when it is bound to XmlDataSource
Asked Answered
P

4

28

I'm using XmlDataSource as the datasource for a dropdownlist.

Now I want to set the SelectedValue of the drop down when the page initially loads. I have tried the OnDataBound event of the drop down in which I could see the total items. But setting the SelectedValue didn't work. InOnDataBinding event, I couldn't even see the total items probably because the list isn't bound yet?

How can I set the selected index based on a value?

Phrase answered 25/2, 2011 at 19:20 Comment(8)
Are you using declarative or programmatic databinding? More specifically, is your dropdown list already populated at the point where you want to set the SelectedValue?Rimola
No, the dropdownlist was not populated because I want to set the SelectedValue in the Page_Load.Phrase
Have you tried, after calling DataBind on your DropDownList, to do something like ddl.SelectedIndex = 0 ?Dibru
One solution is to programmatically databind the dropdown list before you set the selected value. You might also find an event in the ASP.NET page life cycle that occurs after declarative databinding happens.Rimola
That worked. I was trying binding events, but never tried to call DataBind directly on the dropdownlist. But when I did, it worked. Thank you.Phrase
Posting my comment as an answer.Dibru
I just set the SelectedIndex in page load, no need to data bind.Ruskin
Possible duplicate of Setting dropdownlist selecteditem programmaticallyFalkirk
R
79

This seems to work for me.

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            DropDownList1.DataBind(); // get the data into the list you can set it
            DropDownList1.Items.FindByValue("SOMECREDITPROBLEMS").Selected = true;
        }
    }
Ruskin answered 9/6, 2011 at 17:6 Comment(0)
G
18
DropDownList1.Items.FindByValue(stringValue).Selected = true; 

should work.

Galliot answered 1/11, 2012 at 5:31 Comment(0)
R
11

This is working code

protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            { 
                    DropDownList1.DataTextField = "user_name";
                    DropDownList1.DataValueField = "user_id";
                    DropDownList1.DataSource = getData();// get the data into the list you can set it
                    DropDownList1.DataBind();

    DropDownList1.SelectedIndex = DropDownList1.Items.IndexOf(DropDownList1.Items.FindByText("your default selected text"));
            }
        }
Raconteur answered 11/2, 2012 at 20:31 Comment(0)
D
-4

Have you tried, after calling DataBind on your DropDownList, to do something like ddl.SelectedIndex = 0 ?

Dibru answered 25/2, 2011 at 22:4 Comment(1)
Consider formatting this answer- besides it is wrong(or not entirely what the OP asked about). Just remove it.Sixtynine

© 2022 - 2024 — McMap. All rights reserved.