在dropdownlist1上选择第1项时,在dropdownlist2上以星号“ 02”和“ 03”标记的项应被禁用,而在dropdownlist1上选择dropdownlist2的项2则以“ 01”开头的项和“ 03”应该被禁用
protected void Page_Load(object sender, EventArgs e)
{
if (DropDownList1.SelectedItem.Value == "01")
{
DropDownList2.Items.Cast<ListItem>()
.Where(x => (x.Value.Substring(0, 2) == "02") || (x.Value.Substring(0, 2) == "03"))
.ToList()
.ForEach(x => x.Enabled = false);
}
else
{
DropDownList2.Items.Cast<ListItem>()
.Where(x => (x.Value.Substring(0, 2) == "02") || (x.Value.Substring(0, 2) == "03"))
.ToList()
.ForEach(x => x.Enabled = true);
if (DropDownList1.SelectedItem.Value == "02")
{
DropDownList2.Items.Cast<ListItem>()
.Where(x => (x.Value.Substring(0, 2) == "01") || (x.Value.Substring(0, 2) == "03"))
.ToList()
.ForEach(x => x.Enabled = false);
}
else
{
DropDownList2.Items.Cast<ListItem>()
.Where(x => (x.Value.Substring(0, 2) == "01") || (x.Value.Substring(0, 2) == "03"))
.ToList()
.ForEach(x => x.Enabled = true);
}
}
}
protected void DropDownList1_ItemChanged(object sender, EventArgs e)
{
if (DropDownList1.SelectedItem.Value == "01")
{
DropDownList2.Items.Cast<ListItem>()
.Where(x => (x.Value.Substring(0, 2) == "02") || (x.Value.Substring(0, 2) == "03"))
.ToList()
.ForEach(x => x.Enabled = false);
}
else
{
DropDownList2.Items.Cast<ListItem>()
.Where(x => (x.Value.Substring(0, 2) == "02") || (x.Value.Substring(0, 2) == "03"))
.ToList()
.ForEach(x => x.Enabled = true);
if (DropDownList1.SelectedItem.Value == "02")
{
DropDownList2.Items.Cast<ListItem>()
.Where(x => (x.Value.Substring(0, 2) == "01") || (x.Value.Substring(0, 2) == "03"))
.ToList()
.ForEach(x => x.Enabled = false);
}
else
{
DropDownList2.Items.Cast<ListItem>()
.Where(x => (x.Value.Substring(0, 2) == "01") || (x.Value.Substring(0, 2) == "03"))
.ToList()
.ForEach(x => x.Enabled = true);
}
}
}
页面加载按预期工作,正确显示了dropdownlist2上的项目,但是一旦我将dropdownlist1上的项目更改为item2并再次更改为item1,dropdownlist2根本不显示任何内容,但是dropdownlist1上的item2正常运行一般。
答案 0 :(得分:1)
就像格雷格所说,您应该学习调试。
您在第二个列表框中获得了一个项目列表:
01, 02, 03
步骤1-在列表框1中选择01
:停用02
和03
ListBox2.Items = { 01 }
步骤2-在列表框1中选择03
:激活02
和03
,停用01
和03
ListBox2.Items = { 02 }
步骤3-在列表框1中选择01
:停用02
和03
ListBox2.Items = { }
结果:您忘了在一开始就激活所有内容。
每次为每个元素设置Enabled
。这样一来,您无需在更改状态之前就可以担心状态。而且它更短。.
protected void DropDownList1_ItemChanged(object sender, EventArgs e)
{
DropDownList2.Items.Cast<ListItem>()
.ToList()
.ForEach(x => x.Enabled = (DropDownList1.SelectedItem.Value == x.Value.Substring(0, 2)));
}