Reputation: 13
In my winform I need to check if a string value inputted by the user is within a combo box, where the values of the combo box's data is sourced from a database.
Is it possible to simply check if the user's value is already in the combo box or will I have to manually check the database to see if the data is present?
private void Button1_Click(object sender, EventArgs e)
{
if (!questionList.Items.Contains(customQ.Text.Trim()))
{
dbconnect.addQ(customQ.Text);
refreshBox();
}
}
I have tried using contain but it always returns false, even if the data isn't in the combo box, any feedback is appreciated :)
Upvotes: 0
Views: 1099
Reputation: 231
Casting the Items as strings will work for what you want. Items are handled as an ObjectCollection and their IEnumerable wont even try checking if a string is contained.
private void Button1_Click(object sender, EventArgs e)
{
if (!questionList.Items.Cast<string>().Contains(customQ.Text.Trim()))
{
dbconnect.addQ(customQ.Text);
refreshBox();
}
}
The code above worked as it should in my testing and hopefully it will work for you.
Upvotes: 0
Reputation: 323
You should be able to use the FindStringExact method to determine if a item already exists in the ComboBox.
if (questionList.FindStringExact(customQ.Text.Trim()) < 0)
{
// The item was not found to already exist
}
You can read more about the FindStringExact method within the .NET documentation:
Hope this helps.
Upvotes: 1