1

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
}
Reza Aghaei
  • 120,393
  • 18
  • 203
  • 398
Programmer
  • 459
  • 5
  • 20

2 Answers2

4

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>()

Reza Aghaei
  • 120,393
  • 18
  • 203
  • 398
0
    DataGridViewComboBoxCell cell = dataGridView1.Rows[0].Cells[0] as DataGridViewComboBoxCell;
    long value = 3434232;
    if (cell.Items.Contains(value)) MessageBox.Show("Yes");
  • Posting code is useful, but for educational purposes it's good to also include some explanation of how it solves the issue. – neontapir Sep 10 '15 at 16:58