我们还有一个例程首先检查项目的 DropDownList,如果不存在则将其添加到列表中。与上面提到的 Danny 相同的想法,但我喜欢他将其添加为红色的额外想法。尽管想法相同,但我认为发布我们的完整例程会很有价值。它使用 foreach 遍历列表以查找值字符串。正如上面贾斯汀所说,使用 FindByText 可以提高效率。
protected bool SafeSetDropDownValue(DropDownList ddl, string value, string text, bool addItemIfNotFound)
{
// first make sure that drop down list has been data bound so that all the options are in there
ddl.DataBind();
// look for value in the list of dropdown values
// (can't use try/catch because exception doesn't happen until later)
bool found = false;
bool selected = true;
foreach (ListItem li in ddl.Items)
{
if (li.Value == value)
{
found = true;
}
}
if (found)
{
ddl.SelectedValue = value;
}
else
{
// the value wasn't in the list,
// so if addItem is true, then add the value to the list and then set the value
if (addItemIfNotFound)
{
ListItem li = new ListItem(text, value);
ddl.Items.Add(li);
ddl.SelectedValue = value;
}
else
{
// didn't find it and didn't add it
selected = false;
}
}
return selected;
}