C#——winfrom——DataGridView 选中某一行的事件

时间:2021-07-15 04:14:43

先将SelectionMode属性设置一下,改为fullrowselection. 然后给一个cellclick事件 注意:点击表头时也会触发此事件,在取值时要排除

private void dataGridView2_CellClick(object sender, DataGridViewCellEventArgs e)
{
  //当点击表头部的列时,e.RowIndex==-1
  if (e.RowIndex > -1)
  {
    this.txtUsername.Text = this.dataGridView2.Rows[e.RowIndex].Cells[1].Value.ToString();
    this.txtPassword.Text = this.dataGridView2.Rows[e.RowIndex].Cells[2].Value.ToString();
    this.txtPosition.Text = this.dataGridView2.Rows[e.RowIndex].Cells[3].Value.ToString();
    this.txtStatus.Text = this.dataGridView2.Rows[e.RowIndex].Cells[6].Value.ToString();
    this.txtName.Text = this.dataGridView2.Rows[e.RowIndex].Cells[7].Value.ToString();
  }

}