0

我在向我的 datagridview 添加新行时遇到问题。我希望它通过添加按钮来完成。我的绑定基于本教程http://msdn.microsoft.com/en-us/library/fbk67b6z.aspx,所以我的代码看起来几乎完全相同。是否可以:首先 - 向 datagridviews 绑定数据源添加新行,然后通过单击更新按钮更新数据库?我设法获得了所选行的克隆,它将用作新行的模板。谢谢你的帮助。

4

2 回答 2

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,因此将其声明为全局变量,您就可以在提交按钮的单击事件中使用它。

于 2012-09-12T13:49:41.373 回答
0

好吧,我不能做这样的事情 dataGridView1.Rows.Add(selected_row); 它抛出一个异常。而且我不知道如何在我的数据库中插入一行。– user1651521 1 小时前

对于数据绑定的网格,您不能将行直接添加到数据网格中。您必须将新行添加到绑定表中。

因此,如果您使用与该示例相同的代码,您将向 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);
}
于 2012-09-12T15:22:41.100 回答