[ Team LiB ] |
Recipe 7.14 Using a DataView to Control Edits, Deletions, or Additions in Windows FormsProblemYou need to selectively prevent users from editing, deleting, or adding data in a Windows Forms application. SolutionBind a DataView to Windows Forms controls. The sample code contains four event handlers:
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 = dv; } private void allowDeleteCheckBox_CheckedChanged(object sender, System.EventArgs e) { dv.AllowDelete = allowDeleteCheckBox.Checked; } private void allowEditCheckBox_CheckedChanged(object sender, System.EventArgs e) { dv.AllowEdit = allowEditCheckBox.Checked; } private void allowInsertCheckBox_CheckedChanged(object sender, System.EventArgs e) { dv.AllowNew = allowInsertCheckBox.Checked; } DiscussionThe DataGrid control does not have properties that control the adding, editing, or deleting the data in the control. Binding a DataGrid to a DataTable binds to the default view of the underlying DataTable. The DataView class represents a view of the DataTable that can be data bound on both Windows Forms and Web Forms. The DataView can be customized for editing, filtering, searching, and sorting. The DataView class can be used to add, edit, or delete records in the underlying DataTable. The properties described in Table 7-14 control the data modification permitted in a DataView.
If AllowNew is true, the record is not added until the EndEdit( ) method is called either explicitly or implicitly. The CancelEdit( ) method of the DataRowView can be called to discard the row before it is added. If AllowEdit is true, the changes to the row are not committed until the EndEdit( ) method is called either explicitly or implicitly. Only one row can be edited at a time. The CancelEdit( ) method of the DataRowView can be called to discard the row before it is added. If the AddNew( ) or BeginEdit( ) method of the DataRowView is called, EndEdit( ) is called implicitly on the pending row; this applies the changes to the row in the underlying DataTable. In data controls that allow editing multiple records, EndEdit( ) is called implicitly when the current row is changed. |
[ Team LiB ] |