C# DataGridView获取行值

C# DataGridView获取行值,c#,datagridview,C#,Datagridview,我正在尝试获取我单击的行的单元格值 这是我的密码 private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e) { txtFullName.Text = dataGridView1.Rows[e.RowIndex].Cells[0].Value.ToString(); txtUsername.Text = dataGridView1.Rows[

我正在尝试获取我单击的行的单元格值

这是我的密码

private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
    {
        txtFullName.Text = dataGridView1.Rows[e.RowIndex].Cells[0].Value.ToString();
        txtUsername.Text = dataGridView1.Rows[e.RowIndex].Cells[2].Value.ToString();
        txtPassword.Text = dataGridView1.Rows[e.RowIndex].Cells[3].Value.ToString();
    }
很好。。但当我单击行(UserID的左侧)和UserID列时,它不起作用。。。当我单击列标题时,它也会给我一个错误。我如何修复这个错误,我希望它也能单击行和userid列


为避免单击列标题时出现错误,您必须检查
e.RowIndex
是否为0或更多:

void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
    if (e.RowIndex == -1) { return; }
    txtFullName.Text = dataGridView1.Rows[e.RowIndex].Cells[0].Value.ToString();
    txtUsername.Text = dataGridView1.Rows[e.RowIndex].Cells[2].Value.ToString();
    txtPassword.Text = dataGridView1.Rows[e.RowIndex].Cells[3].Value.ToString();
}
要在单击行标题时设置事件,必须将事件处理程序注册到
RowHeaderMouseClick
event

dataGridView1.RowHeaderMouseClick += dataGridView1_RowHeaderMouseClick;

使用
DataGridView
SelectionChanged
eventhandler和
CurrentRow
属性,它们完全是为您的目的而设计的

void DataGridView1_SelectionChanged(object sender, EventArgs e)
{
    DataGridView temp = (DataGridView)sender;
    if (temp.CurrentRow == null)
        return; //Or clear your TextBoxes
    txtFullName.Text = dataGridView1.CurrentRow.Cells[0].Value.ToString();
    txtUsername.Text = dataGridView1.CurrentRow.Cells[2].Value.ToString();
    txtPassword.Text = dataGridView1.CurrentRow.Cells[3].Value.ToString();
}
并将
SelectionMode
设置为
FullRowSelection

this.dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;    

您使用了错误的事件:请尝试此选项

    private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
    {
        if (e.RowIndex > -1)
        {
            var val = this.dataGridView1[e.ColumnIndex,  e.RowIndex].Value.ToString();
        }
    }

单元格[0]
是用户ID。。。不是吗<代码>单元格[1]应该是全名吗?@Ben是的。。我只是想得到用户ID。。。我的问题是当我点击UserID列时,第行(UserID的左侧)并没有给我任何信息。。。当我点击clomun标题时,它会给我一个错误…要点击行标题,请使用RowHeaderMouseClick事件。对于单击列标题时出现的错误,请检查e.RowIndex是否为-1。谢谢!我只是不明白当前行何时将为“null”