7.14. Using a DataView to Control Edits, Deletions, or Additions in Windows Forms
Problem
You need to selectively prevent users from editing, deleting, or adding data in a Windows Forms application.
Solution
Bind a DataView to Windows Forms controls.
The sample code contains four event handlers:
Form.LoadSets up the sample by filling a
DataTablewith the Orders table from the Northwind sample database. ADataViewis created from the table and bound to the data grid on the form.- Allow Delete
Button.Click Sets whether the
DataViewallows records to be deleted based on the value in a check box.- Allow Edit
Button.Click Sets whether the
DataViewallows records to be edited based on the value in a check box.- Allow Insert
Button.Click Sets whether the
DataViewallows records to be inserted based on the value in a check box.
The C# code is shown in Example 7-30.
Example 7-30. File: ControlDataEditWithDataViewForm.cs
// Namespaces, variables, and constants using System; using System.Configuration; using System.Data; using System.Data.SqlClient; private DataView dv; // . . . private void ControlDataEditWithDataViewForm_Load(object sender, System.EventArgs e) { // Fill the Order table. SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM Orders", ConfigurationSettings.AppSettings["Sql_ConnectString"]); DataTable dtOrders = new DataTable("Orders"); da.FillSchema(dtOrders, SchemaType.Source); da.Fill(dtOrders); // Create a view and bind it to the grid. dv = new DataView(dtOrders); dataGrid.DataSource ...Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access