How to Fill TextBoxes from DataGridView on Button

2020-04-21 08:21发布

I want to fill data on button click event from DataGridView Control:

enter image description here

My code like this

for (int i = 0; i < dgv_EmpAttList.Columns.Count; i++)
{
  txt_EnrollNo.Text = this.dgv_EmpAttList.CurrentRow.Cells[i].Value.ToString();
  txt_FirstInTime.Text = this.dgv_EmpAttList.CurrentRow.Cells[i].Value.ToString();
  txt_LastOutTime.Text = this.dgv_EmpAttList.CurrentRow.Cells[i].Value.ToString();
  txt_TotalHours.Text = this.dgv_EmpAttList.CurrentRow.Cells[i].Value.ToString();
}

2条回答
够拽才男人
2楼-- · 2020-04-21 08:52

Why you have to use looping? Simply you can write

 txt_EnrollNo.Text = this.dgv_EmpAttList.CurrentRow.Cells[0].Value.ToString(); 
txt_FirstInTime.Text = this.dgv_EmpAttList.CurrentRow.Cells[1].Value.ToString();
txt_LastOutTime.Text = this.dgv_EmpAttList.CurrentRow.Cells[2].Value.ToString();
 txt_TotalHours.Text = this.dgv_EmpAttList.CurrentRow.Cells[3].Value.ToString(); 

EDIT:

Then on Button click send the row to update and write the code as follows

txt_EnrollNo.Text = row.Cells[0].Value.ToString(); //where row is DataGridViewRow
查看更多
别忘想泡老子
3楼-- · 2020-04-21 08:53

Looping through your columns probably won't help here.

Try assigning each textbox the cell that it is mapped to:

txt_EnrollNo.Text = this.dgv_EmpAttList.CurrentRow.Cells[1].Value.ToString();
txt_FirstInTime.Text = this.dgv_EmpAttList.CurrentRow.Cells[2].Value.ToString();
查看更多
登录 后发表回答