vb.net 以编程方式根据 gridview 值选择一行
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4228278/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
programmatically select a row based on gridview values
提问by simonlabdes
What I have
我拥有的
I have a DataGridView with 3 columns (metric_key, metric_name, metric_value).
我有一个包含 3 列(metric_key、metric_name、metric_value)的 DataGridView。
There are for example, 6 ROWS in this table (6 different metrics), added programmatically (DGV is not bound in any way)
例如,此表中有 6 个 ROWS(6 个不同的指标),以编程方式添加(不以任何方式绑定 DGV)
Now, when I assign values in my grid I do:
现在,当我在网格中分配值时,我会这样做:
dataGridView1.item("Metric_value",0).value = "value of the metric in row 0, in the column named "metric_Value".
What I'd like
我想要什么
However I'm looking for a way to use the value in the metric_Key
column to do my assignment, something like:
但是我正在寻找一种方法来使用metric_Key
列中的值来完成我的分配,例如:
datagridView1.item("metric_Value","My_metric_Key")
instead of putting the row ID, or maybe:
而不是放置行 ID,或者:
datagridview1.item("metric_value",Indexof("My_metric_Key"))
Or
或者
datagridview1.item("metric_value",findValue("my_metric_key","metric_key"))
etc.
等等。
I don't want to create any other objects (dataview, etc.).
我不想创建任何其他对象(数据视图等)。
How can I do this?
我怎样才能做到这一点?
回答by YWE
There isn't a built in way to do this. But you can define an extension method on DataGridView to accomplish this.
没有内置的方法可以做到这一点。但是您可以在 DataGridView 上定义一个扩展方法来完成此操作。
<System.Runtime.CompilerServices.Extension()> _
Function FindValue(ByRef dgv As DataGridView, ByVal metric_key As Object) As DataGridViewRow
For Each row As DataGridViewRow In dgv.Rows
If row.Cells.Item("metric_value").Value = metric_key Then
Return row
End If
Next
Return Nothing
End Function
So if you wanted to get the row where the metric_value is 1, you could use
因此,如果您想获取 metric_value 为 1 的行,则可以使用
dataGridView1.FindValue(1)