我想从datagridview的一列读取数据。我的datagridview包含许多列,但我想读取所有单元格,但只读取一列。我使用以下代码阅读所有列:
foreach (DataGridViewColumn col in dataGridView1.Columns)
col.Name.ToString();
但我想从特定列中读取所有单元格。
答案 0 :(得分:19)
试试这个
string data = string.Empty;
int indexOfYourColumn = 0;
foreach (DataGridViewRow row in dataGridView1.Rows)
data = row.Cells[indexOfYourColumn].Value;
答案 1 :(得分:16)
也许这也有帮助。获得一个单元格:
string data = (string)DataGridView1[iCol, iRow].Value;
然后你可以简单地循环行和列。
答案 2 :(得分: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..
}
}
答案 3 :(得分:0)
获取点击的单元格的值:
private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
textBox1.Text = dataGridView1[e.ColumnIndex, e.RowIndex].Value.ToString();
}
答案 4 :(得分:0)
FOREACH LOOP
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 LOOP
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);
}