如何获取网格视图的行值

时间:2014-03-21 02:06:40

标签: c# winforms datagridview

我有WinForm应用程序,我喜欢获取已编辑单元格的行值,如下例所示。单击georce单元格将文本更改为“Matar”后,单击button1。使用“Matar”值获取“george”的行值,如下所示。在我的代码中,我只获得已编辑单元格的值。

GridView
--------
ID   Name   School_ID
---  ----   ---------
0    adam   300654     button1
1    steve  300789
2    george 455554
.    .       .
.    .       .
.    .       .
10   billy  562211

结果:

ID:2   Name:Matar   School_ID: 455554

mycode的:

private void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
    MessageBox.Show(dataGridView1[e.ColumnIndex, e.RowIndex]
              .Value
              .ToString());
}

2 个答案:

答案 0 :(得分:1)

如果您希望获得价值变化的价值,那么您可以获得这样的价值。

private void dataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
    string sValue = string.Empty;
    if (dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value != null)
        sValue = dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString();

}

从Current Row获取价值

string sValue = string.Empty;
if (dataGridView1.CurrentRow != null && dataGridView1.CurrentRow.Cells[e.ColumnIndex].Value != null)
    sValue = dataGridView1.CurrentRow.Cells[e.ColumnIndex].Value.ToString();

从当前单元格中获取值

string sValue = string.Empty;
if (dataGridView1.CurrentCell != null && dataGridView1.CurrentCell.Value != null)
    sValue = dataGridView1.CurrentCell.Value.ToString();

从特定行单元格中获取值

string sValue = string.Empty;
if (dataGridView1.Rows[RowIndex].Cells[ColumnIndex].Value != null)
    sValue = dataGridView1.Rows[RowIndex].Cells[ColumnIndex].Value.ToString();

<强>编辑:

获取完整的行单元格值

StringBuilder sb = new StringBuilder();
int RowIndex = 0; //set the row index here.
for (int iCol = 0; iCol < dataGridView1.ColumnCount; iCol++)
{
    if (dataGridView1.Rows[RowIndex].Cells[iCol].Value != null)
        sb.Append(dataGridView1.Columns[iCol].HeaderText + ":" + dataGridView1.Rows[RowIndex].Cells[iCol].Value.ToString() + ",");
    else
        sb.Append(dataGridView1.Columns[iCol].HeaderText + ":,");
}
string RowValues = sb.ToString();
//To Remove the last seperator ","
RowValues = RowValues.Substring(0, RowValues.Length - 1);

有必要检查值是否为null否则会给出异常“引用对象未设置。”

答案 1 :(得分:0)

要获得整行,您可以访问Rows集合:

dataGridView1.Rows[e.RowIndex]

var firstColumn = Convert.ToString(dataGridView1.Rows[0].Cells[0].Value);

您还可以尝试CurrentRow属性:

dataGridView1.CurrentRow

var firstColumn = Convert.ToString(dataGridView1.CurrentRow.Cells[0].Value);