How do I Avoid duplicates from being added to a listbox?

  • Thread starter Thread starter Tim Burr
  • Start date Start date
T

Tim Burr

Hi

When using vb.net I have always used the following to prevent
duplicates from being added to a listbox:

If lstDDTab.FindStringExact(txtTabName.Text) <> -1 Then
Beep()
MsgBox("Duplicate tab names not permitted.",
MsgBoxStyle.Information + MsgBoxStyle.OKOnly, "Tab Error")
txtTabName.Focus()
Exit Sub

However FindStringExact is not supported in compact framework. What
other solution is available to me?

Thanks

Tim
 
This does not help me much. I do not understand what I am looking at. I
have only been programming in VB.Net for about 90 days. Please explain
how to apply that code to my situation.

Thanks

Tim
 
On that page, search for FindStringExact. It is a C# implementation of what
you want. You can then find one of the many online converters and translate
it. Once you have tried, you can post back with specific questions...

Alternatively, just iterate the list items checking for each one if it
matches... it is a handful of lines of code...

Cheers
Daniel
 
Ok I converted it to VB.Net and got the following:

Public Function FindStringExact(ByVal s As String, ByVal startIndex
As Integer) As Integer
Dim index As Integer = -1
Dim pString As IntPtr = MarshalEx.StringToHGlobalUni(s)
index = CInt(Win32Window.SendMessage(Me.Handle,
CInt(CB.FINDSTRINGEXACT), startIndex, pString))
MarshalEx.FreeHGlobal(pString)
Return index
End Function 'FindStringExact


There are numerous errors:

MarshalEx is not declared
CB is not declared
Win32Window is not declared
'Handle' is not a member of 'PROJ007.Form12'

Help

Thanks
 
Add a reference to the opennetcf SDF dlls. Look at the top of that file for
the using/import to see which namespaces you need.

Cheers
Daniel
 
Hi, Tim

If you just want to prevent adding duplicated stuff in ListBox, you can try
the following code.

if(lstAdded.Items.Contains(txtToAdd.Text))
{
MessageBox.Show("Duplicated");
return;
}
lstAdded.Items.Add(txtToAdd.Text);
 
Hello

I tried the following but it did not work: (Vb.Net)

If Not lstView.Items.Contains(lstFld.Text) Then
lstView.Items.Add(lstFld.Text)
End If

Does not seem to fire as the duplicates are still being copied over.
 
Is lstFld a TextBox ?

Try
MessageBox.Show( lstView.Items.Contains(lstFld.Text).ToString() )
to see what it returns.
 
Hi

I got it to work thanks to your MSG box suggestion.

I used
lstView.Items.Contains(lstFld.Text) = True Then

It was a logical expression with a true/false answer not the actual
string.

Thanks for this.

TB
 
Back
Top