我正在处理数据录入表格。当我单击保存按钮时,我希望将表单中的数据保存到数据库中。我还希望从数据库填充DataGridview
。
我的问题是:当我从DataGridview
中选择任何一行时,该行将显示为已选中。根据主键数据,将填写数据输入表格的所有字段。
我可以使用哪个事件?任何人都可以提出任何建议吗?
答案 0 :(得分:1)
最简单的方法是使用绑定源和数据绑定。
因此,在表单中添加一个绑定源,并将其作为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));
此绑定是自动双向的,当您从网格中选择项目时,它将起作用。将显示您选择的每个项目的姓氏。
要使双向绑定有点快照(有时它会延迟到你进入网格),你可以在文本框LostFocus事件中执行以下操作:
void textBox1_LostFocus(object sender, EventArgs e)
{
bindingSource1.ResetBindings(false);
}
答案 1 :(得分:0)
你可以做到
private void dataGridView1_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e)
{
textBox1.Text = dataGridView1.CurrentRow[e.RowIndex].ToString();
}
或使用行输入事件来获取当前行
private void dataGridView1_RowEnter(object sender,
DataGridViewCellEventArgs e)
{
//e.RowIndex to get the index of the row
}
答案 2 :(得分:0)
答案 3 :(得分:0)
当你选择一行时,调用SelectedIndexChanging
当选择一行时,调用SelectedIndexChanged
为了填充gridview,你必须使用RowDataBound
有关完整列表,请参阅以下msdn链接 http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridview_events.aspx