C# 在 TextBox 中显示来自 dataGridView 的数据?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15406560/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Show Data from dataGridView in TextBox?
提问by user2160781
When i click in row on dataGridView
i like to populate Textbox with data from that row ?
How can i do that ?
当我点击一行时,dataGridView
我喜欢用该行的数据填充文本框?我怎样才能做到这一点 ?
this data in dataGridView
(ex. ID=1, Name=s
...) to show in Textbox
Up ??
这个数据dataGridView
(例如ID=1, Name=s
......)显示在Textbox
Up ??
采纳答案by Nolonar
You'll have to implement the SelectionChanged
event of your DataGridView
, then check for whichever row is selected.
您必须实现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.
}
}
回答by Uzair Aslam
Register MouseClick event of grid and use following code.
注册网格的鼠标点击事件并使用以下代码。
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();
}
And add the following line in your load event
并在您的加载事件中添加以下行
dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
回答by Sachith
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();
}
}