2012-08-13 269 views
2

我正在处理数据输入表单。当我点击保存按钮时,我希望表单中的数据被保存到数据库中。我也想从数据库中填写一个DataGridviewGridview行选择和编辑

我的问题是:当我从DataGridview中选择任何行时,该行将显示为选中状态。根据主关键数据填写所有数据输入表格的字段。

我可以使用哪个事件?任何人都可以提供建议吗?

+0

滑稽,我发布一个完整的答案,这问题昨天,我可以发誓它被标记为asp.net和引用'GridView'。我不会看到这个问题,如果它没有用asp.net标记... – pseudocoder 2012-08-14 14:15:58

回答

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 
} 
+0

我不想更改网格本身的记录。我需要将可编辑列设置为false。 – 2012-08-14 05:35:36

+0

查看我所做的更改。这是你在这个问题上的意思吗? – 2012-08-14 05:56:13

+0

我认为应该通过行输入事件来完成...对此事件有任何想法吗?我如何使用它?并从GridView的列中获取主键值,并基于该主键我可以从DB – 2012-08-14 06:01:42

1

最简单的方法到GridView这是通过使用绑定源和数据绑定来完成的。

因此,将绑定源添加到您的表单中,并将其设置为您的数据源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); 
}