Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 724
MNIK Avatar asked Feb 25 '11 19:02

MNIK


People also ask

How can set the selected value of dropdown in asp net?

You can set the SelectedValue to the value you want to select. If you already have selected item then you should clear the selection otherwise you would get "Cannot have multiple items selected in a DropDownList" error. dropdownlist. ClearSelection(); dropdownlist.

How do I set the selected value in drop-down?

Using the jQuery change() method; you can set the selected value of dropdown in jquery by using id, name, class, and tag with selected html elements; see the following example for that: Example 1 :- Set selected value of dropdown in jquery by id.


3 Answers

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;
        }
    }
like image 98
Aaron Anodide Avatar answered Oct 12 '22 15:10

Aaron Anodide


DropDownList1.Items.FindByValue(stringValue).Selected = true; 

should work.

like image 38
dpchimmili Avatar answered Oct 12 '22 13:10

dpchimmili


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"));
            }
        }
like image 10
Atif Mahmood Avatar answered Oct 12 '22 13:10

Atif Mahmood