DataTableOperation in ADO.NET

This article has been excerpted from the book "A Programmer's Guide to ADO.NET in C#".

Adding and deleting data are two common operations when working with databases. You've already learned in my previous article about how to add data to a data table using DataRow. In this article, you'll see how to add, delete, and search data programmatically. To test the sample application, you'll not store data in a database. All data will be stored in memory in the form of DataTable objects.
The first step is to build a Graphical User Interface (GUI). To build this GUI, you'll create a Windows application project. After that add a DataGrid control, three-button controls, four textbox controls, three group boxes, and a couple, of label controls. Then adjust them on your form. You can also change the background color of the controls, as shown in figure 1 below. As you can see from the form, the add button will add the name and address that you enter in the Name and Address textboxes. The Remove button will remove the row number you'll enter in the Enter Row# textbox. The search button searches for a name in the DataTable and returns the corresponding records in the DataGrid.
Note: You don't have to create the same form. The only thing you need to have a DataGrid with the same number for text boxes and button controls.
Figure 1: Add, delete, and search operations in DataTable
Now you change the names of the form controls and add the DataSet variable dtSet and the DataTable variable custTable to the beginning of the form. The final control name variables look like listing 1.
Listing 1: Variable of figure 1
  1. private System.Windows.Forms.DataGrid datagrid1;  
  2. private System.Windows.Forms.Lable lable1;  
  3. private System.Windows.Forms.Lable lable2;  
  4. private System.Windows.Forms.TextBox textbox1;  
  5. private System.Windows.Forms.TextBox textBox2;  
  6. private System.Windows.Forms.Label lable3;  
  7. private System.Windows.Forms.TextBox textBox3;  
  8. private System.Windows.Forms.Button DeleteRow;  
  9. private System.Windows.Forms.Button AddRow;  
  10. private System.Data.DataTable custTable;  
  11. private System.Windows.Forms.GroupBox groupBox1;  
  12. private System.Windows.Forms.GroupBox groupBox2;  
  13. private System.Windows.Forms.GroupBox groupBox3;  
  14. private System.Windows.Forms.Lable lable4;  
  15. private System.Windows.Forms.Button SearchButton;  
  16. private System.Windows.Forms.TextBox SearchBox;  
  17. private System.Data.DataSet dtSet; 
Now you create the Customers table with three columns: id, Name, and Address. I've already discussed how to add columns to a DataTable using DataColumn and bind it to a DataGrid in the previous articles. The CreateCustomersTable method creates the Customers table. After creating the Customers table you add the DataTable to the DataSet using the DataSet.Tables. Add method. The CreateCustomersTable method looks like listing 2.
Listing 2: The CreateCustomersTable method
  1. // This method creates customers Table  
  2. private void CreateCustomersTable() {  
  3.       // create a new DataTable.  
  4.       custTable = new DataTable("Customers");  
  5.       DataColumn dtColumn;  
  7.       // createe id column  
  8.       dtColumn = new DataColumn();  
  9.       dtColumn.DataType = System.Type.GetType("System.Int32");  
  10.       dtColumn.ColumnName = "id";  
  11.       dtColumn.AutoIncrement = true;  
  12.       dtColumn.AutoIncrementSeed = 100;  
  13.       dtColumn.AutoIncrementStep = 1;  
  14.       dtColumn.Caption = "Cust ID";  
  15.       dtColumn.ReadOnly = true;  
  16.       dtColumn.Unique = true;  
  17.       // Add id column to the DataColumnCollection.  
  18.       custTable.Columns.Add(dtColumn);  
  20.       // Create Name column.  
  21.       dtColumn = new DataColumn();  
  22.       dtColumn.DataType = System.Type.GetType("System.String");  
  23.       dtColumn.ColumnName = "Name";  
  24.       dtColumn.Caption = "cust Name";  
  25.       dtColumn.AutoIncrement = false;  
  26.       dtColumn.ReadOnly = false;  
  27.       dtColumn.Unique = false;  
  29.       // Add Name column to the Table.  
  30.       custTable.Columns.Add(dtColumn);  
  32.       // Create Address Column.  
  33.       dtColumn = new DataColumn();  
  34.       dtColumn.DataType = System.Type.GetType("System.String");  
  35.       dtColumn.ColumnName = "Address";  
  36.       dtColumn.Caption = " Address";  
  37.       dtColumn.ReadOnly = false;  
  38.       dtColumn.Unique = false;  
  40.       // Add Address column to the table.  
  41.       custTable.Columns.Add(dtColumn);  
  43.       // Make the Id column the primary key column.  
  44.       DataColumn[] PrimaryKeyColumns = new DataColumn[1];  
  45.       PrimaryKeyColumns[0] = custTable.Columns["id"];  
  46.       custTable.PrimaryKey = PrimaryKeyColumns;  
  48.       // Instantiate the DataSet variable.  
  49.       dtSet = new DataSet("Customers");  
  51.       // Add the custTable to the DataSet.  
  52.       dtSet.Tables.Add(custTable);  
  54.       RefreshData();  
At the end of the CreateCustomersTable method, you call the RefreshData method, which refreshes the DataGrid contents and fills them with the current data of the DataTable by setting Data Grid's DataSource property to DatSet's DefaultViewManager. The RefreshData method looks like the following:
  1. private void RefreshData() {  
  2.       dataGrid1.DataSource = dtSet.DefaultViewManager;  
As you can see from figure 1, the Add Row button adds a new row to the Customers DataTable with the Name and Address columns reading from Name and address text boxes. The Delete Row button deletes the row member inserted in the Enter Row # text box. The search button searches and returns rows that contain the name entered in the Enter Name text box of the searches group box.
OK, now it's time to write code for the button event handlers. You can write button event handlers by double-clicking on the buttons or using the Properties windows. First, you write the event handler for the Add Row button with the handler name AddRow_click for this button. After that write event handlers for the Remove and search buttons; the event handler names for these buttons are DeleteRow_Click and SearchButton_Click respectively.
Now you can write code on these handlers. First, you're writing code for the Add Row button. Actually, there is nothing new about the code written for the Add Row button handler. You add a new row to the DataTable using DataRow and call the Add and AcceptChanges methods of the Data Table. The following code snippet listed in listing 2 shows the Add Row button click event handler.
As you can see from the code, I added Name as TextBox1's text and Address as TextBox2's text.
You call NewRow of DataTable to add a new row to DataTable, set its field values, and call the DataTable.Rows.Add method to add it. In the end, you call the RefreshData method to fill the DataGrid with the records.
Listing 2: The Add Row_Click method
  1. private void AddRow_Click(object sender, System.EventArgs e) {  
  2.     // Add rows to the cust table using its NewRow method  
  3.     // I add three customers with their addresses, name and id  
  4.     DataRow myDataRow = custTable.NewRow();  
  5.     myDataRow["Name"] = textBox1.Text.ToString();  
  6.     myDataRow["Address"] = textBox2.Text.ToString();  
  7.     custTable.Rows.Add(myDataRow);  
  8.     custTable.AcceptChanges();  
  9.     RefreshData();  
If you add six rows to the DataTable using the Add Row button the result looks like figure 2.
Figure 2: Adding rows to the DataTable
The Delete Row button deletes the row number you entered in the text box. You can delete a row from a DataTable by calling DataRow's Delete method. On the Delete Row button event handler, you call DataTable's Delete method. Before calling Delete, you need to know what row you want to delete from a DataTable. You get that from TextBox3 and return that row using DataTable.Rows (index). Once you have a DataRow, you call its Delete method and AcceptChanges method to make final changes to the DataTable. In listing 3, you first call the Delete method of DataRow and call AcceptChanges to accept the changes.
Listing 3: The Delete Row_Click method
  1. // Deletes a row from the datatable  
  2. private void DeleteRow_Click(object sender, System.EventArgs e) {  
  3.     int idx = Convert.ToInt32(textBox3.Text.ToString());  
  4.     DataRow row = custTable.Rows[idx - 1];  
  5.     row.Delete();  
  6.     row.AcceptChanges();  
To test this code, you delete the second row by entering 2 in the Remove Row # text box and click the Delete Row button. The result looks at figure 3.
Figure 3: Deleting rows from the DataTable
The DataTable class also provides the Select method to select certain rows in a DataTable based on a filter. A filter is a conditional statement. All SQL conditional operators are valid in the Filter string. For Example, to filter rows where id is greater than 22, the filter string will be "ID>22"; for selecting records of the name Row, the filter string will be "Name = 'Rox'". The SearchButton_Click method searches for the criteria and deletes all the rows from the DataTable that don't match the criteria to display only that match the criteria. Listing 4 shows the SearchButton_Click method.
Listing 4: The SearchButton_Click method
  1. // search button searches for the criteria  
  2. private void SearchButton_Click(object sender, System.EventArgs e) {  
  3.     string str = "Name < >'" + textBox4.Text + " ' ";  
  4.     DataRow[] rows = custTable.Select(str);  
  5.     // if no record found  
  6.     if (rows.Length == 0) {  
  7.         MessageBox.Show("No records found!");  
  8.         return;  
  9.     }  
  11.     for (int i = 0; i < rows.Length; i++) {  
  12.         rows[i].Delete();  
  13.         rows[i].AcceptChanges();  
  14.     }  
  16.     RefreshData();  
Now using the search button and text boxes, your search for records with the name Amy by entering "Amy" in the Search text box and clicking the search button. The result looks like figure 4.
Figure 4: Result of clicking the search after entering "AMY"


Hope this article would have helped you in understanding the DataTableOperation in ADO.NET. See my other articles on the website on ADO.NET.

Similar Articles
Founded in 2003, Mindcracker is the authority in custom software development and innovation. We put best practices into action. We deliver solutions based on consumer and industry analysis.