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).
C# |
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);
}
}
|
XAML |
<Grid>
<dxg:GridControl x:Name="grid" AutoPopulateColumns="True"
HorizontalAlignment="Stretch"
VerticalAlignment="Top">
<dxg:GridControl.View>
<dxg:TableView NavigationStyle="Cell"/>
</dxg:GridControl.View>
</dxg:GridControl>
<Button HorizontalAlignment="Left"
VerticalAlignment="Bottom"
Click="Button_Click">
Save Data
</Button>
</Grid>
|