如何从DataGridView的一列中读取数据

10

我想从DataGridView的一列中读取数据。我的DataGridView包含多列,但我只想读取其中一列的所有单元格。我使用以下代码读取了所有列:

foreach (DataGridViewColumn col in dataGridView1.Columns)
        col.Name.ToString();

但是我想读取特定列中的所有单元格。


foreach (var cell in col.Cells) 这个不行吗? - Nolonar
col不包含Cells的定义。 - Sumit Goyal
5个回答

23

试一下

string data = string.Empty;
int indexOfYourColumn = 0;
foreach (DataGridViewRow row in dataGridView1.Rows)
   data = row.Cells[indexOfYourColumn].Value;

1
@SumitGoyal:这段代码遍历每一行,并从指定的列中读取值,这正是您所要求的... - Pondidum
@yogi 非常感谢。 - Zujaj Misbah Khan

19
也许这也有所帮助。要获取单个单元格:
string data = (string)DataGridView1[iCol, iRow].Value;

然后你可以简单地循环行和列。

文档


DataGridView1 不包含 item 的定义。 - Sumit Goyal

2

试试这个

foreach (DataGridViewRow row in dataGridView1.Rows)
        {
            foreach (DataGridViewCell cell in row.Cells)
            {
                if (cell.ColumnIndex == 0) //Set your Column Index
                {
                //DO your Stuff here..
                }
            }
         }

或者另一种方法。
       foreach (DataGridViewColumn col in dataGridView1.Columns)
            {
                if (col.Name == "MyColName")
                {
               //DO your Stuff here..
                }
            }

0

获取点击单元格的值:

private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
    {
        textBox1.Text = dataGridView1[e.ColumnIndex, e.RowIndex].Value.ToString();
    }

0

FOREACH循环

string data = string.Empty;
string data = string.Empty;
int indexOfYourColumn = 0;
int indexOfYourColumn = 0;
foreach (DataGridViewRow row in dataGridView1.Rows)
foreach (DataGridViewRow row in dataGridView1.Rows)
   data = row.Cells[indexOfYourColumn].Value;

FOR循环

using System.Collections;

string data = string.Empty;
int indexOfYourColumn = 0;

IList list = dataGridView1.Rows;

for (int i = 0; i < list.Count; i++)
{
  DataGridViewRow row = (DataGridViewRow)list[i];
   data = row.Cells[indexOfYourColumn].Value;
  data = Convert.ToDecimal(row.Cells[indexOfYourColumn].Value);
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接