Reputation: 471
I have a checkboxlist and i am getting duplicate list items in the checkboxlist. I want to check if the particular item is exist in the checkboxlist before add an item. what is the optimized way to do this check?
<asp:CheckBoxList runat="server" ID="chkboxlist" CellPadding="5" CellSpacing="5" />
chkboxlist.Items.Add("GEORGIA");
chkboxlist.Items.Add("OHIO");
Before adding any state to the checkbox list , i want to check the state value is already exist in the checbox list. How to do that?
Upvotes: 0
Views: 4517
Reputation: 1980
You can use FindByValue method of the Items property for check if a value exists. If value not exists the method return null.
By code
If(checkboxlist.Items.FindByValue("yourvalue") !=null)
{
// Exists
}
Upvotes: 1
Reputation: 223292
You can use LINQ's Enumerable.Any
like
string newItem = "OHIO";
if (chkboxlist.Items.Cast<ListItem>().Any(r => r.Text == newItem))
{
//Already exists
}
else
{
chkboxlist.Items.Add(newItem);
}
If you want case insensitive comparison then you can do:
if (chkboxlist.Items.Cast<ListItem>()
.Any(r => String.Equals(r.Text,newItem, StringComparison.InvariantCultureIgnoreCase)))
Upvotes: 1