[英]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
. 我需要检查并查看
DataGridViewComboBoxColumn
是否存在某个值。 The issue is that DataGridViewComboBoxColumn.Items.Contains()
wants an object and I am giving it a long
value. 问题是
DataGridViewComboBoxColumn.Items.Contains()
想要一个对象,我给它一个long
值。 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
}
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: 如果组合框列中的
Items
很复杂,那么您应该这样做:
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: 例如,如果项目类型为
Category
且类别具有Id
和Name
并且您将其Id
用作ValueMember
,则可以使用如下代码:
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. 这里的关键点是使用
Cast<T>
来帮助您将所有项目转换为所需的类型。
This way you can even search in items using Where()
after Cast<T>()
这样你甚至可以在
Cast<T>()
之后使用Where()
搜索项目
DataGridViewComboBoxCell cell = dataGridView1.Rows[0].Cells[0] as DataGridViewComboBoxCell;
long value = 3434232;
if (cell.Items.Contains(value)) MessageBox.Show("Yes");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.