<table>
<tr><td><asp:DropDownList ID='dd1' runat='server' /></td></tr>
<tr><td><asp:DropDownList ID='dd2' runat='server' /></td></tr>
<tr><td><asp:DropDownList ID='dd3' runat='server' /></td></tr>
<tr><td><asp:DropDownList ID='dd4' runat='server' /></td></tr>
</table>
在代码隐藏中,我加载这些项目,以便它们都匹配。然后我从数据库中检索数据,并为每个db记录调用一个方法来设置下拉列表的选定索引。
int i = 0;
foreach (var rec in dataRecords) {
switch (i) {
case 0:
SetDropDownValue(rec, dd1);
break;
case 1:
SetDropDownValue(rec, dd2);
break;
case 2:
SetDropDownValue(rec, dd3);
break;
case 3: ...
case 4: ...
default: ...
}
i++;
private void SetDropDownValue(DBRecord selectedRecord, DropDownList dl)
{
string importantVal = selectedRecord.Field;
var li = dl.Items.FindByValue(importanVal);
dl.SelectedIndex = dl.Items.IndexOf(li);
}
在SetDropDownValue方法中,单步执行调试器时,记录是正确的,dropdownlist是正确的。
dl。SelectedIndex=dl。项目。指数of(li);
执行时,传递给该方法的所有以前的DropDownList的选定索引也会更新。因此,当ddl2的选定索引更改时,ddl1将更改为ddl2的新选定索引。当ddl3更新时,ddl1&ddl2已更新。设置ddl4时,将更新ddl1、ddl2和ddl3所选索引。