How to programmatically set SelectedValue of Dropd

2020-02-01 03:08发布

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?

4条回答
欢心
2楼-- · 2020-02-01 03:48

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"));
            }
        }
查看更多
ら.Afraid
3楼-- · 2020-02-01 03:49
DropDownList1.Items.FindByValue(stringValue).Selected = true; 

should work.

查看更多
时光不老,我们不散
4楼-- · 2020-02-01 03:51

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;
        }
    }
查看更多
该账号已被封号
5楼-- · 2020-02-01 03:56

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

查看更多
登录 后发表回答