In C#, I have variable, a
, of type string
.
How do I find item
by value of a
in combobox
(I want find item with value no display text of combobox).
In C#, I have variable, a
, of type string
.
How do I find item
by value of a
in combobox
(I want find item with value no display text of combobox).
You can find it by using the following code.
int index = comboBox1.Items.IndexOf(a);
To get the item itself, write:
comboBox1.Items[index];
You should see a method on the combo box control for FindStringExact(), which will search the displaymember and return the index of that item if found. If not found will return -1.
//to select the item if found:
mycombobox.SelectedIndex = mycombobox.FindStringExact("Combo");
//to test if the item exists:
int i = mycombobox.FindStringExact("Combo");
if(i >= 0)
{
//exists
}
I know my solution is very simple and funny, but before I train I used it. Important: DropDownStyle of combobox must be "DropDownList"!
First in combobox and then:
bool foundit = false;
String mystr = "item_1";
mycombobox.Text = mystr;
if (mycombobox.SelectedText == mystr) // Or using mycombobox.Text
foundit = true;
else foundit = false;
It works for me right and resolved my problem... But the way (solution) from @st-mnmn is better and fine.
Hi Guys the best way if searching for a text or value is
int Selected = -1;
int count = ComboBox1.Items.Count;
for (int i = 0; (i<= (count - 1)); i++)
{
ComboBox1.SelectedIndex = i;
if ((string)(ComboBox1.SelectedValue) == "SearchValue")
{
Selected = i;
break;
}
}
ComboBox1.SelectedIndex = Selected;
Sorry for VB.NET code, please convert it to c#.
I prepared the following function bcoz of .NET 3.5 Windows Application:
Public Function FindIndex_by_value(ByRef combo As ComboBox, ByVal value As String) As Integer
Dim idx As Integer
For i As Integer = 0 To combo.Items.Count - 1
Dim itm As DataRowView
itm = combo.Items(i)
Dim vl As String = itm.Item(0)
If vl = value Then
idx = i
Exit For
End If
Next
Return idx
End Function
using this function:
Dim idx As Integer = FindIndex_by_value(comboBox1, "Value_to_Search")
comboBox1.SelectedIndex = idx
Important: here 0 is index of the value column and I used the first column as value column in my DB query.