我正在写一份数据录入表格。当我单击保存按钮时,我希望将表单中的数据保存到数据库中。我还希望从数据库中填充一个DataGridview。
我的问题是:当我从DataGridview中选择任何行时,该行将显示为选中。以主键数据为基础,填写数据录入表单的所有字段。
我可以使用哪个事件来执行此操作?有没有人能提点建议呢?
发布于 2012-08-13 21:20:12
你可以做到
private void dataGridView1_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e)
{
textBox1.Text = dataGridView1.CurrentRow[e.RowIndex].ToString();
}或者使用row enter事件获取当前行。
private void dataGridView1_RowEnter(object sender,
DataGridViewCellEventArgs e)
{
//e.RowIndex to get the index of the row
}发布于 2012-08-14 20:21:06
最简单的方法是使用绑定源和数据绑定。
因此,在表单中添加一个绑定源,并将其作为DataGridView的数据源,然后设置到数据输入字段的数据绑定(这里我只绑定到一个文本框)。
// Load your data into a data source - for the example just imagine a data table called dt
bindingSource1.DataSource = dt;
dataGridView1.DataSource = bindingSource1;
// Now we set up a databinding to a text box, to an example property LastName
textBox1.DataBindings.Add(new Binding("Text", bindingSource1, "LastName", false,
DataSourceUpdateMode.OnPropertyChanged));此绑定自动是双向的,当您从网格中选择项时,此绑定起作用。将显示您选择的每个项目的姓氏。
要使双向绑定更快(有时它可能会延迟到您进入网格),可以在textboxes事件中执行以下操作:
void textBox1_LostFocus(object sender, EventArgs e)
{
bindingSource1.ResetBindings(false);
}发布于 2012-08-13 21:22:20
https://stackoverflow.com/questions/11934979
复制相似问题