当我在行中单击时,dataGridView
我喜欢用该行中的数据填充文本框?我怎样才能做到这一点 ?
dataGridView
(例如ID=1, Name=s
...)中的此数据显示在Textbox
Up ??
当我在行中单击时,dataGridView
我喜欢用该行中的数据填充文本框?我怎样才能做到这一点 ?
dataGridView
(例如ID=1, Name=s
...)中的此数据显示在Textbox
Up ??
您必须实现SelectionChanged
您的事件DataGridView
,然后检查选择了哪一行。
private void dataGridView_SelectionChanged(object sender, EventArgs e)
{
DataGridViewCell cell = null;
foreach (DataGridViewCell selectedCell in dataGridView.SelectedCells)
{
cell = selectedCell;
break;
}
if (cell != null)
{
DataGridViewRow row = cell.OwningRow;
idTextBox.Text = row.Cells["ID"].Value.ToString();
nameTextBox.Text = row.Cells["Name"].Value.ToString();
// etc.
}
}
注册网格的 MouseClick 事件并使用以下代码。
private void dataGridView1_MouseClick(object sender, MouseEventArgs e)
{
DataGridViewRow dr = dataGridView1.SelectedRows[0];
textBox1.Text = dr.Cells[0].Value.ToString();
// or simply use column name instead of index
//dr.Cells["id"].Value.ToString();
textBox2.Text = dr.Cells[1].Value.ToString();
textBox3.Text = dr.Cells[2].Value.ToString();
textBox4.Text = dr.Cells[3].Value.ToString();
}
并在您的加载事件中添加以下行
dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
//it checks if the row index of the cell is greater than or equal to zero
if (e.RowIndex >= 0)
{
//gets a collection that contains all the rows
DataGridViewRow row = this.dataGridView1.Rows[e.RowIndex];
//populate the textbox from specific value of the coordinates of column and row.
txtid.Text = row.Cells[0].Value.ToString();
txtname.Text = row.Cells[1].Value.ToString();
txtsurname.Text = row.Cells[2].Value.ToString();
txtcity.Text = row.Cells[3].Value.ToString();
txtmobile.Text = row.Cells[4].Value.ToString();
}
}