所以我有一系列10个下拉列表和标签,它们具有相同的价值。除了复制和粘贴相同的代码10次之外,还有其他方法吗?
protected void drpPOMedList1_SelectedIndexChanged(object sender, EventArgs e)
{
if (drpPOMedList1.SelectedIndex == 0)
{
lblPOLimit1.Text = "PO Med not Selected";
}
else if (drpPOMedList1.SelectedIndex == 1)
{
lblPOLimit1.Text = "0 / 0";
}
else if (drpPOMedList1.SelectedIndex == 2)
{
lblPOLimit1.Text = "8 / 20";
}
}
答案 0 :(得分:1)
我试图找到文本之间的关系,但是faild。如果您没有文本关系,请使用数组或列表。
private readonly string[] arr = new string[] { "item 0", "item 1", ... }
protected void drpPOMedList1_SelectedIndexChanged(object sender, EventArgs e)
{
lblPOLimit1.Text = arr[drpPOMedList1.SelectedIndex];
}
答案 1 :(得分:1)
所有下拉列表的相同委托
protected void drpPOMedList1_SelectedIndexChanged(object sender, EventArgs e)
{
...
}
将此委托与所有下拉列表相关联
<asp:DropDownlist id="ddl1" runat="server" AutoPostBack="true" OnSelectedIndexChanged="drpPOMedList1_SelectedIndexChanged" />
<asp:DropDownlist id="ddl2" runat="server" AutoPostBack="true" OnSelectedIndexChanged="drpPOMedList1_SelectedIndexChanged" />
.......
答案 2 :(得分:0)
您可以将项目存储在数据结构(列表/数组/等)中,并根据需要进行编辑。
答案 3 :(得分:0)
我通常将这些转换表放在Dictionary对象中,并将这些Dictionary对象移出方法。这使您可以轻松地重用这些表,或在以后用其他结构(例如数据库存储)替换它们。
class SomeClass
{
static readonly Dictionary<int, string> INDEX_TEXT_TABLE = new Dictionary<int, string>
{
{ 0, "PO Med not Selected" },
{ 1, "0 / 0" },
{ 2, "8 / 20" }
};
protected void drpPOMedList1_SelectedIndexChanged(object sender, EventArgs e)
{
lblPOLimit1.Text = INDEX_TEXT_TABLE[drpPOMedList1.SelectedIndex];
}
}
顺便说一下,您可能希望研究使用语义上更有意义的SelectedValue
属性。下拉列表通常是键值对,键和值都是字符串类型。因此,使用此属性是数据和表示之间更合适的映射。这也提高了代码的清晰度。
class SomeClass
{
static readonly Dictionary<string, string> VALUE_TEXT_TABLE = new Dictionary<string, string>
{
{ "None", "PO Med not Selected" },
{ "Zero", "0 / 0" },
{ "EightTwenty", "8 / 20" }
};
protected void drpPOMedList1_SelectedIndexChanged(object sender, EventArgs e)
{
lblPOLimit1.Text = VALUE_TEXT_TABLE[drpPOMedList1.SelectedValue];
}
}