如何在绑定到XmlDataSource时以编程方式设置Dropdownlist的SelectedValue

MNI*_*NIK 23 asp.net xmldatasource drop-down-menu

我正在XmlDataSource用作datasourcea dropdownlist.

现在我想SelectedValue在页面最初加载时设置下拉列表.我已经尝试了OnDataBound event下拉,我可以看到总项目.但设置SelectedValue不起作用.在OnDataBinding事件中,我甚至不能看到可能是因为名单尚未绑定的全部项目?

如何根据值设置所选索引?

Aar*_*ide 71

这似乎对我有用.

    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;
        }
    }
Run Code Online (Sandbox Code Playgroud)

  • 这是正确的答案!Nice'n'Clean +1 (4认同)

小智 9

DropDownList1.Items.FindByValue(stringValue).Selected = true; 
Run Code Online (Sandbox Code Playgroud)

应该管用.


Ati*_*ood 8

这是工作代码

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"));
            }
        }
Run Code Online (Sandbox Code Playgroud)


The*_*eed -4

在对 DropDownList 调用 DataBind 后,您是否尝试过执行类似 ddl.SelectedIndex = 0 的操作?

  • 考虑格式化这个答案 - 除此之外它是错误的(或者不完全是OP询问的内容)。只需将其删除即可。 (2认同)