List Box : help preventing duplicate items

A

arkgroup

Hi,

Is there any way I can prevent adding same value to the list box?
Do I have to loop thru list every time I add item?
For instance, I can add 1/1/2006 as value and text many times
And I try to avoid this.

Thanks
 
M

MikeS

You can check if an item exists without looping.

Private Sub AddItem(ByVal s As String, ByVal lb As ListBox)
Dim li As New ListItem(s)
If lb.Items.Contains(li) = False Then
lb.Items.Add(li)
End If
End Sub
 
A

arkgroup

Mike,
I am using C# and code below did not work for some reason...
(lst is my ListBox)

private bool IsDuplicate(string value)
{

ListItem li = new ListItem(value);
if (lst.Items.Contains(li))
return true;

return false;
}
 
M

MikeS

C# ?

Oh, I see now, that came on my DVD too, nifty.

This seems to work, even though it gives cramps to type.

....Using *.*...;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
for (int i = 0; i < 10; i++)
{
for (int j = 0; j < 10; j++)
{
String s = (i + j).ToString();
if (!isDuplicate(s))
ListBox1.Items.Add(s);
}
}
}
private bool isDuplicate(String s)
{
ListItem li = new ListItem(s);
return ListBox1.Items.Contains(li);
}
}
 
A

arkgroup

Mike,

Your code did not produce any duplicates and isDuplicate always return
false.
Here what is working for me:

private bool IsDuplicate(string value)
{

ListItem li = ListBox1.Items.FindByValue(value);
return ListBox1.Items.Contains(li);

}

Thanks for your time.
 
M

MikeS

The code produces duplicates here.

If I make this comment:

//if (!isDuplicate(s))

The list fills with all kinds of dupes.

Glad you got it working anyway.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,578
Members
45,052
Latest member
LucyCarper

Latest Threads

Top