Click here to Skip to main content
15,906,816 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,

In my ddlist I am adding duplicate items. I want all the items to be distinct in the ddlist box.

I tried

C#
if(!DropDownList1.Items.Contains(str))
{
    DropDoqnList1.Items.Add(str);
}


But it's showing me error like only 'ListItem' can pass as an argument.

Please help.
Posted

Hello ,
there are two methods for searching the text or value in dropdown.
one is

FindByText
// search in  the collection which contains  the specified text


and another one is

FindByValue
// search in the collection which contains  the specified value


syntax is
drpdown.Items.FindByText(string text);

or

drpdown.Items.FindByValue(string value);


and then put it in the condition

 if (drpcategory.Items.Contains(drpcategory.Items.FindByText("search text")))
{
  //code..
}


thanks
 
Share this answer
 
v3
Try:
C#
if(!DropDownList1.Items.Contains(new ListItem(str)))
{
ListItem li = new ListItem();
li.Text = str;
li.Value = str;
DropDoqnList1.Items.Add(li);
}
 
Share this answer
 
v2
It's so simple just write this code to reduce duplicate value.

C#
if(!DropDownList1.Items.Contains(new ListItem(data)))
        {
            DropDownList1.Items.Add(data);
        }


thanx.....:-)
 
Share this answer
 
Comments
srmohanr 10-Oct-13 5:47am    
Thanks for your help :)
Chintan Desai1988 10-Oct-13 6:07am    
you welcome dear........:-)
Member 11529058 18-Mar-15 3:42am    
where to put this statement?

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900