Best way to check if a drop down list contains a v

2019-02-01 15:43发布

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;

9条回答
叛逆
2楼-- · 2019-02-01 16:23

What about this:

ListItem match = ddlCustomerNumber.Items.FindByText(
    GetCustomerNumberCookie().ToString());
if (match == null)
    ddlCustomerNumber.SelectedIndex = 0;
//else
//    match.Selected = true; // you'll probably select that cookie value
查看更多
戒情不戒烟
3楼-- · 2019-02-01 16:23
ListItem item = ddlComputedliat1.Items.FindByText("Amt D");
if (item == null) {
    ddlComputedliat1.Items.Insert(1, lblnewamountamt.Text);
}
查看更多
Root(大扎)
4楼-- · 2019-02-01 16:33

You could try checking to see if this method returns a null:

if (ddlCustomerNumber.Items.FindByText(GetCustomerNumberCookie().ToString()) != null)
    ddlCustomerNumber.SelectedIndex = 0;
查看更多
Animai°情兽
5楼-- · 2019-02-01 16:34

There are two methods that come to mind:

You could use Contains like so:

if (ddlCustomerNumber.Items.Contains(new 
    ListItem(GetCustomerNumberCookie().ToString())))
{
    // ... code here
}

or modifying your current strategy:

if (ddlCustomerNumber.Items.FindByText(
    GetCustomerNumberCookie().ToString()) != null)
{
    // ... code here
}

EDIT: There's also a DropDownList.Items.FindByValue that works the same way as FindByText, except it searches based on values instead.

查看更多
forever°为你锁心
6楼-- · 2019-02-01 16:34

If the function return Nothing, you can try this below

if (ddlCustomerNumber.Items.FindByText(
    GetCustomerNumberCookie().ToString()) != Nothing)
{
...
}
查看更多
男人必须洒脱
7楼-- · 2019-02-01 16:37

If 0 is your default value, you can just use a simple assignment:

ddlCustomerNumber.SelectedValue = GetCustomerNumberCookie().ToString();

This automatically selects the proper list item, if the DDL contains the value of the cookie. If it doesn't contain it, this call won't change the selection, so it stays at the default selection. If the latter one is the same as value 0, then it's the perfect solution for you.

I use this mechanism quite a lot and find it very handy.

查看更多
登录 后发表回答