检查下拉列表是否包含值的最佳方法? [英] Best way to check if a drop down list contains a value?
问题描述
当用户导航到一个新页面时,这个ddl的选择索引是由一个cookie决定的,但是如果ddl不包含那个cookie的值,那么我希望它被设置为0.我会用什么方法用于ddl?循环是最好的方法,还是我可以执行一个简单的 if 语句?
When the user navigates to a new page, this ddl's selected index is determined by a cookie, but if the ddl doesn't contain that cookie's value, then I'd like it to be set the 0. What method would I use for the ddl? Is a loop the best way, or is there a simply if statement I can perform?
这是我尝试过的,但它不返回布尔值.
This is what I've attempted, but it doesn't return a bool.
if ( !ddlCustomerNumber.Items.FindByText( GetCustomerNumberCookie().ToString() ) )
ddlCustomerNumber.SelectedIndex = 0;
推荐答案
想到了两种方法:
您可以像这样使用包含:
You could use Contains like so:
if (ddlCustomerNumber.Items.Contains(new
ListItem(GetCustomerNumberCookie().ToString())))
{
// ... code here
}
或修改您当前的策略:
if (ddlCustomerNumber.Items.FindByText(
GetCustomerNumberCookie().ToString()) != null)
{
// ... code here
}
还有一个 DropDownList.Items.FindByValue
与 FindByText 的工作方式相同,除了它基于值进行搜索.
There's also a DropDownList.Items.FindByValue
that works the same way as FindByText, except it searches based on values instead.
这篇关于检查下拉列表是否包含值的最佳方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!