Lab Working with Data in a Data Table

In this lab you will manipulate the data in a DataTable.

► Exercise 1: Working with DataTable Objects

This practice will provide code examples that demonstrate adding data to a table, deleting rows in a table, and editing existing values in a data row and how to view the RowState and DataRowVersion information for records in a DataTable. After modifying records, the AcceptChanges and RejectChanges methods will be demonstrated as well.

1. Create a Windows application and name it WorkingWithDataTables.

2. Add a DataGridView to the form and change its Name property to Customers-DataGridView.

3. Add a button to the form and set the following properties:

□ Name = FillTableButton

4. Drop a SqlDataAdapter from the Toolbox onto the form to start the Data Adapter Configuration Wizard.

NOTE SqlDataAdapter Toolbox item

If the SqlDataAdapter is not in the Toolbox, right-click the Data section of the Toolbox, select Choose Items, and then select the SqlDataAdapter item on the .NET Framework Components tab. Click OK.

5. Select or create a new connection to the Northwind database and click Next.

6. Leave the default option to Use SQL Statements, and then click Next.

7. Type SELECT * FROM Customers on the Generate The SQL Statements page and click Finish.

The adapter and related Connection object are added to the form and appear in the component tray.

8. Right-click SqlDataAdapter1 in the component tray and select Generate DataSet.

9. In the Generate DataSet dialog box, replace DataSet1 with NorthwindDataSet and click OK.

An instance of the NorthwindDataSet is added to the form and appears in the component tray.

Figure 7-11 Form1 in the VS IDE after configuring the DataAdapter and generating the DataSet

10. Add the System.Data.SqlClient namespace to your form.

11. Create a Form Load event handler and add the following code to the Form1_Load event handler:

CustomersDataGridView.DataSource = NorthwindDataset1.Customers ' For this example we will turn off the ability to edit directly in a cell. CustomersDataGridView.MultiSelect = False

CustomersDataGridView.SelectionMode = DataGridViewSelectionMode.CellSelect CustomersDataGri dView.EditMode = DataGridViewEditMode.EditProg rammatically

CustomersDataGridView.DataSource = NorthwindDataset1.Customers;

// For this example we will turn off the ability to edit directly in a cell.

CustomersDataGridView.MultiSelect = false;

CustomersDataGridView.SelectionMode = DataGridViewSelectionMode.CellSelect; CustomersDataGri dView.EditMode = DataGridViewEditMode.EditProg rammatically;

12. Create a button-click event handler for the FillTableButton and add the following code:

SqlDataAdapter1.Fill(NorthwindDataset1.Customers) // C#

sqlDataAdapter1.Fill(NorthwindDataset1.Customers);

Add a button to the form and set the following properties:

Was this article helpful?

0 0

Post a comment