Skip to main content
A newer version of this page is available. .

How to: Post Changes to SQL Database

This example shows how to post changes to a SQL database. Before data is posted to the database, the DataViewBase.CommitEditing method is called to validate the currently edited row (if any).

using System.Data;
using System.Data.OleDb;
using System.Data.SqlClient;

// ...
public partial class Window1 : Window {
    SqlDataAdapter sqlAdapter;
    public Window1() {
        InitializeComponent();
        InitSQLDataAdapter();
        grid.ItemsSource = GetData();
    }
    private void InitSQLDataAdapter() {
        SqlConnection sqlConn = new SqlConnection(
            "Data Source=SQLServerName;Initial Catalog=Northwind;Integrated Security=True");
        sqlAdapter = new SqlDataAdapter(
            "SELECT [RegionID], [RegionDescription] FROM [Region]", sqlConn);
        sqlAdapter.UpdateCommand = new SqlCommand(
            "UPDATE Region SET RegionDescription = @RegionDescription WHERE RegionID = @RegionID",
            sqlConn);
        sqlAdapter.UpdateCommand.Parameters.Add("@RegionID", SqlDbType.Int, 4, "RegionID");
        sqlAdapter.UpdateCommand.Parameters.Add("@RegionDescription", SqlDbType.VarChar,
            50, "RegionDescription");
    }
    private DataView GetData() {
        DataSet ds = new DataSet();
        sqlAdapter.Fill(ds);
        return ds.Tables[0].DefaultView;
    }
    private void Button_Click(object sender, RoutedEventArgs e) {
        grid.View.CommitEditing();
        sqlAdapter.Update(((DataView)grid.DataSource).Table);
    }
}