Listbox selection

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

Hi
What is the most compact way of selecting an item in a listbox based on the first part of its string, does it have an inbuilt method?

For instance if I have the items
Aardvark
Antelope
Beaver
Camel

and I 'pass' the string "Ant", then I want 'Antelope' selected. But if I pass 'Adf' or 'Gup', then nothing should be selected.

Any neat way of accomplishing this?
Thanks
 
Hi Beeeeeeeeeeeeves,

I fear you have to step through all items until you find a match. One way to find a match and select it is

string s = "Ant";

for(int i = 0; i < listBox1.Items.Count; i++)
{
if(((string)listBox1.Items).IndexOf(s) == 0)
{
listBox1.SetSelected(i, true);
break; // no need to check the rest
}
}

This sample assumes the ListBox is filled with strings and that only one match will be found.
 
Beeves

This will reduce number of lines

Method 1:

int pos = listBox1.FindString(s,0); //if you have partial string
//select item
if(pos >=0)
listBox1.SelectedIndex = pos;


Method 2:

listBox1.FindStringExact(s,0);// if you have whole string.
if(pos >=0)
listBox1.SelectedIndex = pos;

Shak.

Beeeeeeeeeeeeves said:
Hi
What is the most compact way of selecting an item in a listbox based on
the first part of its string, does it have an inbuilt method?
For instance if I have the items
Aardvark
Antelope
Beaver
Camel

and I 'pass' the string "Ant", then I want 'Antelope' selected. But if I
pass 'Adf' or 'Gup', then nothing should be selected.
 
Back
Top