将gridview更新数据保存到SQL Server?

时间:2016-02-08 21:39:56

标签: c# winforms sql-server-2008 devexpress

我可以在gridView中保存数据,但我无法对我的数据源执行此操作。 可能是缺少一行代码或者是否有我遗漏的东西?

这是我的代码:

public Marksheet(object val1)
{
        InitializeComponent();

        string connectionString = null;
        SqlConnection conn; 
        connectionString = "Server=localhost\\SQLEXPRESS;Integrated security=SSPI;database=jms";
        SqlDataAdapter sda6 = new SqlDataAdapter("SELECT * FROM grades WHERE class_code='" + val1 + "'", connectionString);
        conn = new SqlConnection(connectionString);
        DataTable dt5 = new System.Data.DataTable();
        sda6.Fill(dt5);
        gridControl1.DataSource = dt5;
}

private void gridControl1_EmbeddedNavigator_ButtonClick(object sender, NavigatorButtonClickEventArgs e)
{
         if (e.Button.ButtonType == DevExpress.XtraEditors.NavigatorButtonType.EndEdit)
         {
             if (MessageBox.Show("Do you want to commit changes to the current record?", "Confirm commit",

                 MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question) != DialogResult.No)
             {
                 gridView1.CloseEditor();
                 gridView1.UpdateCurrentRow();
             }   
         }
}

private void gridView1_CellValueChanged(object sender, CellValueChangedEventArgs e)
{
    //?? Could there be something I'm missing here? if yes, what could it be?
}

2 个答案:

答案 0 :(得分:1)

当您对网格控件进行任何更改时,更改将反映在数据源中,在您的情况下为DataTable。如果您从逻辑上思考,它似乎是正确的,因为网格控件绑定到DataTable并且不知道如何填充DataTable

现在您可以看到使用DataTable填充了DataAdapter。您需要调用DataAdapter.Update(dataTable)方法将更改推送到数据库。

如此处所述 - Posting Data to a Connected Database

答案 1 :(得分:0)

@Aseem已经提出了最佳方法,您需要实现ADO.net绑定,以使用 DataAdapter 将更改提交回后端。如果您可以通过这种方式实现,请查看以下教程:

Tutorial: ADO.NET Data

  

使用ADO.NET绑定到数据库时,将控件绑定到   DataTable包含数据库中的数据。当您通过更改数据时   网格控制(添加,删除或修改记录),更改   在DataTable中累积。它们不会自动发布到   底层数据库。因此,您需要手动调用   发布更改的具体方法。

如果您使用自定义数据表并且不愿意实施此类绑定,那么您必须处理GridView.RowUpdated Event,然后您可以回发您在当前更新行中所做的更改。

请参阅:Xtragrid Row Updated Event

示例:

Private Sub gridView1_RowUpdated(ByVal sender As System.Object, ByVal e As DevExpress.XtraGrid.Views.Base.RowObjectEventArgs) Handles gridView1.RowUpdated
    Dim val As Object
    Dim row As DataRowView = CType(e.Row, DataRowView)
    val = row(0)
End Sub

希望这有帮助..