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 se
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
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.
On C# this works:
if (DDLAlmacen.Items.Count > 0)
{
if (DDLAlmacen.Items.FindByValue("AlmacenDefectoAndes").Value == "AlmacenDefectoAndes")
{
DDLAlmacen.SelectedValue = "AlmacenDefectoAndes";
}
}
Update:
Translating the code above to Visual Basic doesn't work. It throws "System.NullReferenceException: Object reference not set to an instance of an object.."
So. for this to work on Visual Basic, I had to change the code like this:
If DDLAlmacen.Items.Count > 0 Then
If DDLAlmacen.Items.Contains(New ListItem("AlmacenDefectoAndes")) Then
DDLAlmacen.SelectedValue = "AlmacenDefectoAndes"
End If
End If
//you can use the ? operator instead of if
ddlCustomerNumber.SelectedValue = ddlType.Items.FindByValue(GetCustomerNumberCookie().ToString()) != null ? GetCustomerNumberCookie().ToString() : "0";
Sometimes the value needs to be trimmed of whitespace or it won't be matched, in such case this additional step can be used (source):
if(((DropDownList) myControl1).Items.Cast<ListItem>().Select(i => i.Value.Trim() == ctrl.value.Trim()).FirstOrDefault() != null){}
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.