C# 仅从 DataGridView 的特定列中获取文本
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/816618/
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
Getting text only from a specific column of DataGridView
提问by Goober
I have a DataGridView that is populated with 4 columns and multiple rows of data. I want to iterate through the DataGridView and get the cell value from a specific column only, since I need this data to pass into a method.
我有一个填充了 4 列和多行数据的 DataGridView。我想遍历 DataGridView 并仅从特定列中获取单元格值,因为我需要将此数据传递给方法。
Here is my code:
这是我的代码:
foreach (DataGridViewRow row in this.dataGridView2.Rows)
{
foreach (DataGridViewCell cell in row.Cells)
{
if (cell.Value == null || cell.Value.Equals(""))
{
continue;
}
GetQuestions(cell.Value.ToString());
}
}
This just seems to go through all the cells, however I need to be able to specify something like:
这似乎只是通过所有单元格,但是我需要能够指定如下内容:
foreach (DataGridViewRow row in this.dataGridView2.Rows)
{
foreach (DataGridViewCell cell in row.Cells[2])//Note specified column index
{
if (cell.Value == null || cell.Value.Equals(""))
{
continue;
}
GetQuestions(cell.Value.ToString());
}
}
采纳答案by Tim Robinson
Don't you just want to remove the inner foreach
loop? Or have I missed something?
你不是只想去掉内foreach
循环吗?或者我错过了什么?
foreach (DataGridViewRow row in this.dataGridView2.Rows)
{
DataGridViewCell cell = row.Cells[2]; //Note specified column index
if (cell.Value == null || cell.Value.Equals(""))
{
continue;
}
GetQuestions(cell.Value.ToString());
}
回答by SamWM
Perhaps you could check the ColumnIndex? Would still loop through all the cells though.
也许您可以检查 ColumnIndex ?尽管如此,仍然会遍历所有单元格。
if (cell.Value == null || cell.Value.Equals("") || cell.ColumnIndex != 2)
{
continue;
}
回答by Iralda Mitro
foreach (DataGridViewRow row in this.dataGridView2.Rows)
{
DataGridViewCell cell = row.Cells["foo"];//Note specified column NAME
{
if (cell != null && (cell.Value != null || !cell.Value.Equals("")))
{
GetQuestions(cell.Value.ToString());
}
}
}