[Last Call] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 376
  • Last Modified:

Search Listbox

Hi,
   I wanted to add an item to a listbox.  Before adding I want to see whether the listbox has the item if it has then it should not add to the listbox.  What is the code in c#/vb.net?
0
miyengar
Asked:
miyengar
1 Solution
 
COBOLdinosaurCommented:
miyengar,

I have moved this to the vb.net topic where I thing you will have a better chance of getting a solution.

COBOLdinosaur
Page Editor
0
 
GrumbleBotCommented:
You can do this in C#

bool b = listBox1.Items.Contains((string) "TestString");
if the string exists then it will return true else it would return false.

If you want to know the location of the string if it exists you could do this
int n  = listBox1.Items.IndexOf((string) "TestString");
This would return the index of the string in the listbox. it it doesn't exist then it will return -1.

for VB you would not need the cast (string) portion.

Hope this helps.

0
 
KarcOriginCommented:
Try this if you are in VB.NET

    Private Sub AddInList(ByVal pItem As String)
        If (ListBox1.Items.Contains(pItem) = False) Then
            ListBox1.Items.Add(pItem)
        End If
    End Sub

Call this function with the passed value you want to add in your listbox. It will add the item in the listbox if it is not exists in the listbox.

Cheers!
0
 
miyengarAuthor Commented:
Tried all the above methods gives me the following error.
My code is
bool b = lstlinenumber.Items.Contains((string)"txtlinenumber.Text");
--The best overloaded method match for 'System.Web.UI.WebControls.ListItemCollection.Contains(System.Web.UI.WebControls.ListItem)' has some invalid arguments
0
 
GrumbleBotCommented:
bool b = lstlinenumber.Items.Contains((string)"txtlinenumber.Text");

You would not want the quotes in your example, because the .Text is already a string value.

Try this

bool b = lstlinenumber.Items.Contains((string) txtlinenumber.Text);
0

Featured Post

[Webinar] Cloud and Mobile-First Strategy

Maybe you’ve fully adopted the cloud since the beginning. Or maybe you started with on-prem resources but are pursuing a “cloud and mobile first” strategy. Getting to that end state has its challenges. Discover how to build out a 100% cloud and mobile IT strategy in this webinar.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now