我在向datagridview添加新行时遇到问题。我想通过添加按钮完成它。我根据本教程http://msdn.microsoft.com/en-us/library/fbk67b6z.aspx建立了绑定,因此我的代码看起来几乎完全相同。是否可以:首先 - 向datagridviews绑定数据源添加新行,然后单击更新按钮更新数据库?我设法克隆选定的行,它将用作新行的模板。谢谢你的帮助。
答案 0 :(得分:0)
您可以使用的是DataGridView的OnRowsAdded事件。以下是此活动的链接:http://msdn.microsoft.com/en-us/library/system.windows.forms.datagridview.onrowsadded.aspx。在这种情况下,您可以遍历添加的每一行,并使用Insert语句将它们插入数据库中。我从未使用过那个活动,但它看起来就像你需要的那样。
编辑:我刚刚在你的例子中看到了这一点。
private void submitButton_Click(object sender, System.EventArgs e)
{
// Update the database with the user's changes.
dataAdapter.Update((DataTable)bindingSource1.DataSource);
}
如果您为DataGridView和提交按钮激活了EditMode,这不会有效吗?您必须有权访问SqlDataAdapter,因此将其声明为全局变量,并且您可以在提交按钮的单击事件中使用它。
答案 1 :(得分:0)
好吧,我不能做那样的事情 dataGridView1.Rows.Add(selected_row);它引发了一个例外。和我 不知道如何在我的数据库中插入一行。 - user1651521 1小时 前
对于数据绑定网格,您无法直接向数据网格添加行。您必须将新行添加到绑定表中。
因此,如果您使用与该示例相同的代码,则需要向DataTable添加新记录,DataTable是bindingsource对象的数据源。所以像这样:
private void addButton_Click(object sender, System.EventArgs e)
{
//I'm assuming your datatable is a member level variable
//otherwise you could get it through the grid
//have the datatable send you back a new row
DataRow newRow = table.NewRow();
//populate your new row with default data here
//....
//add the new row to the data table
table.Rows.Add(newRow);
}