向数据框显示datagrid值时出错

时间:2016-03-31 09:39:38

标签: c# datagrid

我试图在文本框中显示点击的数据网格值。但现在我得到了这个例外:

Object reference not set to an instance of an object.

datagrid_cellclick事件上的代码就是这个......

if (e.RowIndex >= 0)
{
    DataGridViewRow row = this.dataGridView1.Rows[e.RowIndex];
    comboBox2.Text = row.Cells[4].Value.ToString();
    txtID.Text = row.Cells[0].Value.ToString();
    txtName.Text = row.Cells[1].Value.ToString();
    txtAddress.Text = row.Cells[2].Value.ToString();
    //txtPhone.Text = row.Cells[3].Value.ToString();          
    txtBalance.Text = row.Cells[5].Value.ToString();
}

2 个答案:

答案 0 :(得分:2)

此问题是由于您的DataGridViewRow对象未获得实例。 这可能是因为无法访问您的dataGridView1对象。 使用前缀this会导致您的dataGridView1对象存在于您的事件所在的同一个类中,这可能不是这种情况。 参考:https://msdn.microsoft.com/en-us/library/dk1507sz.aspx

尝试删除关键字this,如下所示:

DataGridViewRow row = dataGridView1.Rows[e.RowIndex];

答案 1 :(得分:1)

您可以尝试这样的事情:

if (e.RowIndex >= 0)
{   
   txtID.Text = dataGridView1[0, e.RowIndex].Value.ToString(); 
   txtPhone.Text = dataGridView1[1, e.RowIndex].Value.ToString();    
}

或者您可以按列名称获取Cell值,如下所示:

if (e.RowIndex >= 0)
{   
   txtID.Text = dataGridView1["Id", e.RowIndex].Value.ToString(); 
   txtPhone.Text = dataGridView1["Phone", e.RowIndex].Value.ToString();    
}
相关问题