Murthy
Murthy

Reputation: 1552

How to check if a value already exist in list box before adding to it in asp.net

how can I check if the value is already present in a list-box, so that I can avoid duplicates?

I've added some values to the server-side list-box already, and when I add to list I get more duplicates.

How do I avoid duplicates?

lst_Viewers.Items.Add(reader["Name"].ToString());

Upvotes: 4

Views: 19533

Answers (3)

Shadow Wizzard
Shadow Wizzard

Reputation: 66398

Another approach can be to insert all the values into a List<string> then add the items only after the loop, using .Distinct() to get only unique values:

List<string> names = new List<string>();
while (reader.Read())
    names.Add(reader["Name"].ToString())
names.Distinct().ToList().ForEach(name => lst_Viewers.Items.Add(name));

This way you don't have to search the whole DropDown in every iteration - more elegant (in my opinion) and more efficient.

Upvotes: 1

Tim Schmelter
Tim Schmelter

Reputation: 460288

ListItem item = new ListItem(reader["Name"].ToString());
if ( ! lst_Viewers.Items.Contains(item) ){
    lst_Viewers.Items.Add(item);
}

or

var name = reader["Name"].ToString();
ListItem item = lst_Viewers.Items.FindByText(name);
if ( item  == null ){
    lst_Viewers.Items.Add(new ListItem(name));
}

Upvotes: 7

Haris Hasan
Haris Hasan

Reputation: 30127

if(!lst_Viewers.Items.Any(item => item.Value.ToString().Equals(reader["Name"].ToString())
    lst_Viewers.Items.Add(reader["Name"].ToString());

Upvotes: 1

Related Questions