Netframwork 2.0 (phần 10) ppt

50 387 0
Netframwork 2.0 (phần 10) ppt

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

Thông tin tài liệu

Lesson 3: Working with the DataGridView 425 Lesson 3: Working with the DataGridView This lesson describes how to configure and work with data in a DataGridView control. The DataGridView can display many types of data but typically is used to display the contents of a DataTable in a DataSet. After this lesson, you will be able to: ■ Use the DataGridView control to display and update the tabular data contained in a data source. ■ Bind a DataGridView control to a data source. ■ Configure a DataGridView to use multiple data sources. ■ Manage columns in a DataGridView control by using the Edit Columns dialog box. ■ Format a DataGridView control by using styles. ■ Format a DataGridView control by using custom painting. ■ Configure the column and cell types of a DataGridView control. ■ Add tables and columns to a DataGridView control. ■ Delete columns in a DataGridView control. ■ Respond to clicks in a DataGridView control. ■ Validate input with a DataGridView control. ■ Change displayed data at run time in a DataGridView control. Estimated lesson time: 60 minutes Displaying a Dataset in the DataGridView Control To display a dataset in a DataGridView control or, more specifically, to display a Data- Table in a DataGridView, set the DataSource property of the DataGridView to the DataSet and set the DataMember property of the DataGridView to the name of the DataTable. For example, the following code displays the Northwind Customers table in a DataGridView: ' VB DataGridView1.DataSource = NorthwindDataSet1 DataGridView1.DataMember = "Customers" //C# DataGridView1.DataSource = northwindDataSet1; DataGridView1.DataMember = "Customers"; 426 Chapter 8 Implementing Data-Bound Controls You can also set a DataGridView control to display a dataset using the smart tag avail- able on a DataGridView control by selecting the DataSet in the Choose Data Source ComboBox available on the smart tag. The Choose Data Source command allows you to select a DataSet and DataTable to display from the DataSet list already defined in your project, or you can create a new DataSet to display by selecting Add Project Data Source on the smart tag, which will start the Data Source Configuration Wizard. Configuring DataGridView Columns There are six built-in types of columns you can use in a DataGridView, as outlined in Table 8-1. When adding columns to a DataGridView, select the type of column based on the data you plan to display in it. Table 8-1 DataGridView Column Types Column Type Description DataGridViewTextBoxColumn Use this column type to display text and numeric values. A data-bound DataGridView automatically generates this type of column when binding to strings and numeric values. DataGridViewCheckBoxColumn Use this column to display Boolean values. A DataGridView automatically generates this type of column when binding to Boolean values. DataGridViewImageColumn Use this column to display images. A DataGrid- View automatically generates this type of col- umn when binding to Image and Icon objects. You can also bind a DataGridViewImage col- umn to a byte array. DataGridViewButtonColumn Use this column to provide users with a button control. DataGridViewComboBoxColumn Use this column type to present lists of choices. This would typically be used for lookups to other tables. DataGridViewLinkColumn Use this column type to display links to other data. Lesson 3: Working with the DataGridView 427 Table 8-1 DataGridView Column Types Column Type Description Custom Column If none of the preceding column types provides the specific functionality you require, you can always create a custom column type. To create a custom column, define your class to inherit from DataGridViewColumn or any class with a base class of DataGridViewColumn. (For exam- ple, inherit from DataGridViewTextBoxColumn to extend the functionality of that type.) Adding Tables and Columns to a DataGridView To display a table in a DataGridView, you add and define the columns to the DataGrid- View that make up the schema of the table. You can add columns to a DataGridView with Designers using the Add Column dialog box or programmatically in code. First, decide which type of column to use (refer to Table 8-1, shown previously), and then use one of the following procedures to add the column to your DataGridView. Adding Columns to a DataGridView Using the Designer To add columns to a DataGridView in the Designer, perform the following procedures: 1. Select the DataGridView on your form. 2. Display the smart tag of the DataGridView. 3. Select Add Column. 4. In the Add Column dialog box, define the column by setting the appropriate val- ues in the dialog box. Adding Columns to a DataGridView Programmatically To add columns to a DataGridView in code, create an instance of the type of DataGrid- View column to create, define the column by setting the appropriate properties, and then add the column to the DataGridView.Columns collection. 428 Chapter 8 Implementing Data-Bound Controls For example, the following code sample creates a new text box column named Product- Name: ' VB Dim ProductNameColumn As New DataGridViewTextBoxColumn ProductNameColumn.Name = "ProductName" ProductNameColumn.HeaderText = "Product Name" ProductNameColumn.ValueType = System.Type.GetType("System.String") DataGridView1.Columns.Add(ProductNameColumn) // C# DataGridViewTextBoxColumn ProductNameColumn = new DataGridViewTextBoxColumn(); ProductNameColumn.Name = "ProductName"; ProductNameColumn.HeaderText = "Product Name"; ProductNameColumn.ValueType = System.Type.GetType("System.String"); DataGridView1.Columns.Add(ProductNameColumn); . Deleting Columns in the DataGridView Deleting columns in a DataGridView can be accomplished using the designers in Visual Studio, or programmatically in code. Deleting Columns in a DataGridView Using the Designer To delete columns in a DataGridView using the Designer, perform the following pro- cedures: 1. Select the DataGridView on your form. 2. Display the smart tag for the DataGridView. 3. Select Edit Columns. 4. In the Edit Columns dialog box, select the column you want to remove from the DataGridView. 5. Click the Remove button. Deleting Columns in a DataGridView Programmatically To delete columns in a DataGridView in code, call the Remove method and provide the name of the column you want to delete. For example, the following code example deletes a column named ProductName from DataGridView1: ' VB DataGridView1.Columns.Remove("ProductName") // C# DataGridView1.Columns.Remove["ProductName"]; Lesson 3: Working with the DataGridView 429 Determining the Clicked Cell in a DataGridView To determine the clicked cell, use the DataGridView.CurrentCell property. The Current- Cell provides a reference to the currently selected cell and provides properties to access the value of the data in the cell as well as the row and column index of the cell’s current location in the DataGridView. ' VB Dim CurrentCellValue As String CurrentCellValue = CustomersDataGridView.CurrentCell.Value.ToString // C# String CurrentCellValue; CurrentCellValue = CustomersDataGridView.CurrentCell.Value.ToString(); Validating Input in the DataGridView To validate input in an individual cell in a DataGridView, handle the DataGridView .CellValidating event and cancel the edit if the value fails validation. The CellValidating event is raised when a cell loses focus. Add code to the event handler for the CellValidat- ing event to verify that the values in specific columns conform to your business rules and application logic. The event arguments contain the proposed value in the cell as well as the row and column index of the cell being edited. For example, the following code validates that the ProductName column does not con- tain an empty string (use this sample for a DataGridView that is not bound to data): ' VB If DataGridView1.Columns(e.ColumnIndex).Name = "ProductName" Then If e.FormattedValue.ToString = "" Then dataGridView1.Rows(e.RowIndex).ErrorText = "Product Name is a required field" e.Cancel = True Else dataGridView1.Rows(e.RowIndex).ErrorText = "" End If End If // C# if (DataGridView1.Columns[e.ColumnIndex].Name == "ProductName") { if (e.FormattedValue.ToString() == "") { DataGridView1.Rows[e.RowIndex].ErrorText = "Product Name is a required field"; e.Cancel = true; } else { 430 Chapter 8 Implementing Data-Bound Controls DataGridView1.Rows[e.RowIndex].ErrorText = ""; } } The following code validates that the ProductName column does not contain an empty string (use this example for a DataGridView that is bound to data): ' VB If DataGridView1.Columns(e.ColumnIndex).DataPropertyName = "ProductName" Then If e.FormattedValue.ToString = "" Then dataGridView1.Rows(e.RowIndex).ErrorText = "Product Name is a required field" e.Cancel = True Else dataGridView1.Rows(e.RowIndex).ErrorText = "" End If End If // C# if (DataGridView1.Columns[e.ColumnIndex].DataPropertyName == "ProductName") { if (e.FormattedValue.ToString() == "") { DataGridView1.Rows[e.RowIndex].ErrorText = "Product Name is a required field"; e.Cancel = true; } else { DataGridView1.Rows[e.RowIndex].ErrorText = ""; } } Format a DataGridView Using Styles Format the look of a DataGridView by setting the grid’s cell styles. Although each cell can have a specific style applied to it, many cells typically share the same style. The DataGridView provides several built-in default cell styles that you can customize and use, or you can create new cell styles and apply them to your DataGridView cells. The following example demonstrates how to apply the alternating rows style. Format a DataGridView Control by Using Custom Painting To format a DataGridView using custom painting, you can handle the CellPainting event and insert your own custom painting code. When you handle the CellPainting event, the DataGridViewCellPaintingEventArgs provide access to many properties that simplify custom painting. When you handle the CellPainting event, be sure to set e.Handled to True so the grid will not call its own cell painting routine. Lesson 3: Working with the DataGridView 431 Place the following code in the CellPainting event handler to paint all cells LightSkyBlue: ' VB ' Paint the cell background color LightSkyBlue e.Graphics.FillRectangle(Brushes.LightSkyBlue, e.CellBounds) ' Draw the contents of the cell If Not (e.Value Is Nothing) Then e.Graphics.DrawString(e.Value.ToString, e.CellStyle.Font, _ Brushes.Black, e.CellBounds.X, e.CellBounds.Y) End If e.Handled = True // C# // Paint the cell background color LightSkyBlue e.Graphics.FillRectangle(Brushes.LightSkyBlue, e.CellBounds); // Draw the contents of the cell if (e.Value != null) { e.Graphics.DrawString(e.Value.ToString(), e.CellStyle.Font, Brushes.Black, e.CellBounds.X, e.CellBounds.Y); } e.Handled = true; Quick Check 1. What properties do you set on a DataGridView to display a specific DataTable? 2. How do you determine what cell is clicked in a DataGridView? Quick Check Answers 1. Set the DataSource property to the DataSet, and the DataMember property to the name of the DataTable. 2. Inspect the DataGridView.CurrentCell property. Lab: Working with the DataGridView In this lab you will work with data in a DataGridView control. � Exercise 1: Working with the DataGridView Now let’s create a Windows application and demonstrate how to manipulate the defini- tion as well as the columns and data in a DataGridView control. 1. Create a Windows application and name it DataGridViewExample. 2. Open the Data Sources window (on the Data menu, select Show Data Sources). 432 Chapter 8 Implementing Data-Bound Controls 3. Click Add New Data Source to start the Data Source Configuration Wizard. 4. Leave the default of Database and click Next. 5. Select (or create) a connection to the Northwind sample database and click Next. 6. Expand the Tables node. Select the Customers table, and then click Finish. 7. Drag the Customers node from the Data Sources window onto the form. At this point, you can actually run the application, and the form appears with the Customers table loaded into the DataGridView. 8. Drag two buttons onto the form below the DataGridView and set the following properties: Button1: ❑ Name = AddColumnButton ❑ Text = Add Column Button2: ❑ Name = DeleteColumnButton ❑ Text = Delete Column 9. Double-click the Add Column Button to create the button-click event handler and to open the form in code view. 10. Add the following code to Form1, which adds some additional code to the Form1_Load event that creates a new column on the DataTable and the code to add a new column to the DataGridView in the AddColumnButton_Click event. ' VB Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) _ Handles MyBase.Load 'TODO: This line of code loads data into the 'NorthwindDataSet.Customers' table. You can move, or remove it, As needed. Me.CustomersTableAdapter.Fill(Me.NorthwindDataSet.Customers) ' Add a new column to the Customers DataTable ' to be used to demonstrate adding and removing ' columns in a DataGridView in the methods below Dim Location As New DataColumn("Location") Location.Expression = "City + ', ' + Country" NorthwindDataSet.Customers.Columns.Add(Location) End Sub Private Sub AddColumnButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) _ Handles AddColumnButton.Click Lesson 3: Working with the DataGridView 433 Dim LocationColumn As New DataGridViewTextBoxColumn LocationColumn.Name = "LocationColumn" LocationColumn.HeaderText = "Location" LocationColumn.DataPropertyName = "Location" CustomersDataGridView.Columns.Add(LocationColumn) End Sub // C# private void Form1_Load(object sender, EventArgs e) { // TODO: This line of code loads data into the 'northwindDataSet.Customers' table. You can move, or remove it, as needed. this.customersTableAdapter.Fill(this.northwindDataSet.Customers); // Add a new column to the Customers DataTable // to be used to demonstrate adding and removing // columns in a DataGridView in the methods below DataColumn Location = new DataColumn("Location"); Location.Expression = "City + ', ' + Country"; northwindDataSet.Customers.Columns.Add(Location); } private void AddColumnButton_Click(object sender, EventArgs e) { DataGridViewTextBoxColumn LocationColumn = new DataGridViewTextBoxColumn(); LocationColumn.Name = "LocationColumn"; LocationColumn.HeaderText = "Location"; LocationColumn.DataPropertyName = "Location"; customersDataGridView.Columns.Add(LocationColumn); } 11. Double-click the Delete Column Button to create the DeleteColumnButton_Click event handler. Add the following code to the DeleteColumnButton_Click event handler: ' VB Try CustomersDataGridView.Columns.Remove("LocationColumn") Catch ex As Exception MessageBox.Show(ex.Message) End Try // C# try { customersDataGridView.Columns.Remove("LocationColumn"); } catch (Exception ex) { MessageBox.Show(ex.Message); } 12. Drag another button onto the form and set the following properties: 434 Chapter 8 Implementing Data-Bound Controls ❑ Name = GetClickedCellButton ❑ Text = Get Clicked Cell 13. Drag a label onto the form and place it next to the GetClickedCell button. 14. Double-click the GetClickedCell button and add the following code to the Get- ClickedCellButton_Click event handler: ' VB Dim CurrentCellInfo As String CurrentCellInfo = CustomersDataGridView.CurrentCell.Value.ToString & Environment.NewLine CurrentCellInfo += "Column: " & CustomersDataGridView.CurrentCell.OwningColumn.DataPropertyName & Environment.NewLine CurrentCellInfo += "Column Index: " & CustomersDataGridView.CurrentCell.ColumnIndex.ToString & Environment.NewLine CurrentCellInfo += "Row Index: " & CustomersDataGridView.CurrentCell.RowIndex.ToString Label1.Text = CurrentCellInfo // C# string CurrentCellInfo; CurrentCellInfo = customersDataGridView.CurrentCell.Value.ToString() + Environment.NewLine; CurrentCellInfo += "Column: " + customersDataGridView.CurrentCell.OwningColumn.DataPropertyName + Environment.NewLine; CurrentCellInfo += "Column Index: " + customersDataGridView.CurrentCell.ColumnIndex.ToString() + Environment.NewLine; CurrentCellInfo += "Row Index: " + customersDataGridView.CurrentCell.RowIndex.ToString(); label1.Text = CurrentCellInfo; 15. Create an event handler for the CustomersDataGridView.CellValidating event. (Select CustomersDataGridView on the form, click the Events button in the Prop- erties window, and double-click the CellValidating event.) 16. Add the following code to the CellValidating event handler: ' VB If CustomersDataGridView.Columns(e.ColumnIndex).DataPropertyName = "ContactName" Then If e.FormattedValue.ToString = "" Then CustomersDataGridView.Rows(e.RowIndex).ErrorText = _ "ContactName is a required field" e.Cancel = True Else CustomersDataGridView.Rows(e.RowIndex).ErrorText = "" End If End If // C# if (customersDataGridView.Columns[e.ColumnIndex].DataPropertyName == "ContactName") { [...]... of an XmlReader named aReader XmlValidatingReader aValReader; aValReader = new XmlValidatingReader(aReader); NOTE XmlValidatingReader: Obsolete The 70-526 exam objectives were created while the version 2.0 of the NET Framework was still under development Between the time the objectives were released and the NET Framework was released, XmlValidatingReader was made obsolete and was replaced by validating... following code: ' VB AddHandler aReader.ValidationEventHandler, Addressof myHandler // C# aReader.ValidationEventHandler += myHandler; Validating XML with XmlReader With the introduction of the NET Framework 2.0, you can also use the XmlReader Create method to create an instance of XmlReader that can validate XML The XmlReader.Create method can accept an instance of the XmlReaderSettings class which allows . Color.LightGray; 19. Run the application. 20 . Click the Add Column button, and then scroll to the end of the columns to verify that the new Location column is there. 21 . Click the Delete Column button. requirements listed in the “Introduction” at the beginning of the book. ■ Microsoft Visual Studio 20 05 Professional Edition installed on your computer. ■ An understanding of Microsoft Visual Basic. a Windows application and name it DataGridViewExample. 2. Open the Data Sources window (on the Data menu, select Show Data Sources). 4 32 Chapter 8 Implementing Data-Bound Controls 3. Click

Ngày đăng: 07/07/2014, 05:20

Từ khóa liên quan

Tài liệu cùng người dùng

  • Đang cập nhật ...

Tài liệu liên quan