动态填充下拉列表设置selecteindex会改变两个下拉列表

本文关键字:下拉列表 两个 填充 设置 selecteindex 动态 改变 | 更新日期: 2023-09-27 18:14:00

我正在尝试设置从数组填充的两个DropDownList的选定索引或值。

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            ListItem[] jobs;
            List<ListItem> data = new List<ListItem> {
                new ListItem("Hello", "World"),
                new ListItem("new", "item"),
                new ListItem("next", "item2"),
                new ListItem("four", "four")
            };
            jobs = (from x in data
                    select new ListItem(x.Text, x.Value)).ToArray();
            // jobs is any array of list items where
            // text = value or text != value, but value is unique.
            DropDownList1.Items.AddRange(jobs);
            DropDownList2.Items.AddRange(jobs);
            DropDownList1.SelectedIndex = 1;
            DropDownList2.SelectedValue = jobs[3].Value;
        }
    }

在实际页面上,两个DropDownList都选择了"four"。如何设置不同的值?
注意:我知道这里不需要使用linq,但在项目代码中数据来自SQL DB。

创建另一个ListItem jobsClone

ListItem[] jobsClone = new ListItem[jobs.Length];
for (int i = 0; i < jobs.Length; i++)
{
    jobsClone[i] = new ListItem(jobs[i].Value);
}
你可以设置你的SelectedIndex
DropDownList1.Items.AddRange(jobs);
DropDownList2.Items.AddRange(jobsClone);
DropDownList1.SelectedIndex = 1;
DropDownList2.SelectedIndex = 3;

动态填充下拉列表设置selecteindex会改变两个下拉列表

Items.AddRange(array)预拷贝数组的浅拷贝。

执行深度复制更改

DropDownList1.Items.AddRange(jobs); 

DropDownList1.DataSource = jobs;     
DropdownList1.DataBind();