2014-07-21 110 views
0

我试图设置选定的索引或从数组填充的两个DropDownList的值。动态填充的DropDownList设置SelectedIndex同时改变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“四有”选择。我怎样才能设置不同的值?
注:我知道在这里不需要使用linq,但是在项目代码中,数据来自SQL DB。

+0

看看这里,[http://stackoverflow.com/questions/1249394/how-to-select-a-dropdown-list-item-by-value-programatically][1] 的选择价值需要是一个字符串。 [1]:http://stackoverflow.com/questions/1249394/how-to-select-a-dropdown-list-item-by-value-programatically –

+0

我编辑了自己的冠军。请参阅:“[应该在其标题中包含”标签“](http://meta.stackexchange.com/questions/19190/)”,其中的共识是“不,他们不应该”。 –

+0

我想我需要每个ListItem的深层副本。重复查询会更便宜吗? –

回答

0

Items.AddRange(array)瓶坯数组的一个浅表副本。

瓶坯深拷贝变化

DropDownList1.Items.AddRange(jobs); 

DropDownList1.DataSource = jobs;  

DropdownList1.DataBind(); 

重复其他列表。

1

创建另一个列表项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;