我正在尝试获取单击的行的单元格值。
这是我的代码。
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();
}
Run Code Online (Sandbox Code Playgroud)
工作正常..但是当我单击行(用户ID的左侧)和用户ID列时,它不起作用...当我单击列标题时,它也给我一个错误。如何解决该错误,我还希望它也单击行和用户ID列。
使用 的SelectionChanged事件处理程序和CurrentRow属性DataGridView,它们是专门为您的目的而设计的
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();
}
Run Code Online (Sandbox Code Playgroud)
并设置SelectionMode为FullRowSelection
this.dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
Run Code Online (Sandbox Code Playgroud)
小智 5
您使用了错误的事件:试试这个
private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
if (e.RowIndex > -1)
{
var val = this.dataGridView1[e.ColumnIndex, e.RowIndex].Value.ToString();
}
}
Run Code Online (Sandbox Code Playgroud)