DataGridView获取行值

6

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

以下是我的代码:

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左侧)和用户ID列时,它无法正常工作...当我点击列标题时也会出现错误。如何修复该错误,我希望能够在行和用户ID列上进行点击。

输入图像描述


Cells[0] 是用户ID,对吗?Cells[1] 应该是全名? - Ben
@Ben 是的,我只是想获取用户ID,我的问题是当我点击UserID列和行(userid左侧)时没有给我任何东西,而当我点击列标题时会出现错误... - Sam Teng Wong
1
对于单击行标题,请使用RowHeaderMouseClick事件。对于单击列标题时出现的错误,请检查e.RowIndex是否不为-1。 - TnTinMn
3个回答

10
您正在使用错误的事件:请尝试使用以下事件。
    private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
    {
        if (e.RowIndex > -1)
        {
            var val = this.dataGridView1[e.ColumnIndex,  e.RowIndex].Value.ToString();
        }
    }

5
使用DataGridViewSelectionChanged事件处理程序和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;    

谢谢!我只是不明白当前行何时会变成 "null"。 - Svenmarim

0
为了避免在单击列标题时出现错误,您必须检查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事件注册事件处理程序。
dataGridView1.RowHeaderMouseClick += dataGridView1_RowHeaderMouseClick;

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