Programmer
Programmer

Reputation: 479

How can I check for an item in a DataGridViewComboBoxColumn without using an object?

I need to check and see if a certain value is present in a DataGridViewComboBoxColumn. The issue is that DataGridViewComboBoxColumn.Items.Contains() wants an object and I am giving it a long value. Is there a method/way I can get a string/long value of the Items?

This is what my logic looks like right now (pseudo code).

if (DataGridViewComboBoxColumn.Items.Contains(long))
{
     //Do Stuff
}

Upvotes: 1

Views: 1964

Answers (2)

Reza Aghaei
Reza Aghaei

Reputation: 125197

There are many ways to do that, this simple and beautiful way will do the trick for you:

String:

yourDataGridViewComboBoxColumn.Items.Cast<string>().Contains("your string value")

Long:

yourDataGridViewComboBoxColumn.Items.Cast<long>().Contains(yourLongValue)

Complex Object:

If Items in your combo box column are complex, you should do it ths way:

 yourDataGridViewComboBoxColumn.Items.Cast<YourComplexType>()
    .Select(x => x.YourValueMemberField)
    .Contains(yourLongValue);

For example if items are of type Category and category has Id and Name and you used its Id as ValueMember, you can use code like this:

 int value=10;
 yourDataGridViewComboBoxColumn.Items.Cast<Category>()
    .Select(x => x.Id)
    .Contains(value);

The key point here is using Cast<T> that helps you to cast all items to desired type.

This way you can even search in items using Where() after Cast<T>()

Upvotes: 4

user3923437
user3923437

Reputation:

    DataGridViewComboBoxCell cell = dataGridView1.Rows[0].Cells[0] as DataGridViewComboBoxCell;
    long value = 3434232;
    if (cell.Items.Contains(value)) MessageBox.Show("Yes");

Upvotes: 0

Related Questions