取到gridview所绑定的dataset/datatable,经过转换取到相应的实体类,把textbox的field属性设置为entity的属性,利用反射foreach (PropertyInfo pInfo in entity.GetType().GetProperties()) { foreach (IInputControl c in view.InputControls) { if (string.Equals(pInfo.Name,c.Field,StringComparison.OrdinalIgnoreCase)) c.Value = pInfo.GetValue(entity,null); } }
参考C# WinForm开发系列 - DataGridView
// datagridview单元格值发生变化的时候出发这个事件
private void datagridview_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
string strSelecteddgrd;
string strtype;
//选中的那行
int intInputRow = this.datagridview.CurrentCell.RowIndex;
//选中的那行单元格id记录
strSelecteddgrd = this.datagridview.Rows[intInputRow].Cells[2].Value.ToString();
//选中的那行属性类型
strtype = this.datagridview.Rows[intInputRow].Cells[3].Value.ToString();
//如果验证出错
if (!InputCheck(strSelecteddgrd, strtype))
{
//焦点返回到修改时候的单元格
datagridview.Rows[intInputRow].Cells["Param_Value"].Selected = true;
return;
}
}
再用click事件
例如:
txtName.Text = dataGridView1.SelectedCells[0].Value.ToString();
txtCardNUm.Text = dataGridView1.SelectedCells[1].Value.ToString();
txtNum.Text = dataGridView1.SelectedCells[2].Value.ToString();
txtSex.Text = dataGridView1.SelectedCells[3].Value.ToString();
txtAge.Text=dataGridView1.SelectedCells[4].Value.ToString();
txtTel.Text = dataGridView1.SelectedCells[5].Value.ToString();
{
foreach (IInputControl c in view.InputControls)
{
if (string.Equals(pInfo.Name,c.Field,StringComparison.OrdinalIgnoreCase))
c.Value = pInfo.GetValue(entity,null);
}
}
2,private void dgv_CellClick(object sender, DataGridViewCellEventArgs e)
{
//获得当前行索引
this.currentrow = this.dgv.CurrentCell.RowIndex;
this.TextBox1.Text = this.dgv.Rows[currentrow].Cells[1].Value;
}