|
code
newsgroups
|
|||||||||||||||||||||||
|
|||||||||||||||||||||||
List Box : help preventing duplicate itemsHi,
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 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 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; } MikeS wrote: Show quoteHide quote > 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 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); } } 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. MikeS wrote: Show quoteHide quote > 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); > } > } 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.
Login control - image button with text over it
how to get selectedvalue of radiobuttonlist in Javascript? looping through formview controls Accessing USER CONTROL which is inside Masterpage through Another USER Control inside normal page. Use CSS in themes Session sharing between ASP and ASP.NET StyleSheetTheme not working How to catch Internet Explorer events? Login HelpPageIconUrl is the help link Question about a user control derived from DropDownList |
|||||||||||||||||||||||