Recently, I am working on a software for the rain exposure resource library and used the latest control datagridview in vs2005. So I will refer to some documents. It was found that the datagridview has very little information on csdn, so I don't know if anyone is interested.
Introduction to new data grid released on: 5/24/2005 | updated on: 5/24/2005
Matthew MacDonald
The new dview is a new control in. NET 2.0 and is designed for the standard DataGrid Control with poor functionality in. Net 1.x. Matthew MacDonald has discussed many improvements in this article, including: datagridview supports a large number of custom and meticulous format settings, flexible size adjustment and selection, better performance, and richer event models.
The first two versions of. NET Framework (. NET 1.0 and. NET 1.1) left a significant gap in data binding. Although developers have a flexible configurable model that can link almost all controls to almost all data sources, there is no effective way to display the complete information table. The only tool that can achieve this goal is the DataGrid Control, which is very suitable for simple demonstration, but not suitable for actual code.
Filling this gap is one of the main goals of. NET 2.0, and Microsoft has used the brand new grid control datagridview to achieve this goal. Datagridview has two guiding principles. First, the goal is to support common tasks (such as master/Detailed List, verification, and data format settings) without writing a lot of code. More importantly, scalability is always taken into account during the design process, so you can integrate the required special functions without using low-level complex programming.
Content on this page
|
Basic Data Binding |
|
Beautify the datagridview |
|
Use datagridview to select a cell |
|
Datagridview object |
|
Datagridview Style |
|
Custom cell format |
|
Button Column |
|
Image Column |
|
Edit the datagridview |
|
Handling error |
|
Verification Input |
|
Use List column constraints to select |
|
Summary |
Basic Data Binding
The best way to get familiar with the datagridview is to try it without configuring any attributes. Like the DataGrid, you can use the datasource attribute to bind a able object (or an object derived from the datatable ).
Dim ds As DataSet = GetDataSet()DataGridView1.DataSource = ds.Tables("Customers")
Unlike the DataGrid, The datagridview can only display one table at a time. If the entire dataset is bound, no data is displayed unless you have set the datamember attribute with the table name to be displayed.
DataGridView1.DataSource = dsDataGridView1.DataMember = "Customers"
The basic datagridview display follows the following simple rules:
• |
Create a column for each field in the data source. |
• |
Use the field name to create a column title. The column title is fixed, which means that the column title does not scroll out of the view when you move down the list. |
• |
Supports Windows XP visual styles. You will notice that the column title has a new plane appearance and will be highlighted when you move the mouse over it. |
The datagridview datagrialso includes several default actions that you may not immediately notice:
• |
Allow local editing. You can double-click a cell or press f2 to modify the current value. The only exception is to set datacolumn. readonly to true (for example, the orderid field in the current example ). |
• |
Supports automatic sorting. You can click the column title once or twice to sort the values in ascending or descending order based on the values in the field. By default, data types are sorted in alphabetical or numerical order. The alphabetic order is case sensitive. |
• |
Different types of options are allowed. You can click and drag to highlight a cell, multiple cells, or multiple rows. Click the square in the upper-left corner of the datagridview to select the entire table. |
• |
Supports automatic resizing. You can double-click the column separator between titles to enable the left column to expand or contract automatically according to the content of the cell. |
Back to Top
Beautify the datagridview
The default appearance of the datagridview is only slightly improved than that of the DataGrid, but you can use several quick adjustment functions to significantly improve it.
One problem is that Columns cannot be automatically expanded to fit the data they contain. You can solve this problem by using the datagridview. autosizecolumns () method and a value in the datagridviewautosizecolumncriteria enumeration. You can adjust the column width based on the title text, the currently displayed row, or the width of all rows in the table.
'Adjust the column width' Based on the title or the width of the 'maximum text segment in a row of this column. Datagridview1.autosizecolumns (_ datagridviewautosizecolumncriteria. headerandrows)
Remember, this method must be called after data is bound, otherwise it will not produce any effect. You may also need to use it after the user edits the data (it may be in response to events such as the datagridview. cellvaluechanged event ).
If the column width is not added, you can change the Row Height. By default, the text in a column spans multiple rows. If you use the datagridview. autosizerows () method, the height is adjusted based on the content. Before using this method, you may want to increase the column width, especially when a field contains a large amount of text. For example, the following code snippet adds the column width of the description column to four times the width of the original column, and then adjusts the Row Height to accommodate its content.
DataGridView.Columns("Description").Width *= 4DataGridView.AutoSizeRows( _DataGridViewAutoSizeRowsMode.HeaderAndColumnsAllRows)
Figure 1Compare the methods for automatically adjusting the size of the dview.
Another reasonable change is to clear the title text displayed in each column. For example, the title "Order Date" looks more professional than the field name "orderdate. This change is easy to make. You only need to retrieve the corresponding datagridviewcolumn from the datagridview. columns set and modify its headertext attribute:
DataGridView.Columns("OrderID").HeaderText = "Order ID"
Back to Top
Use datagridview to select a cell
By default, the datagridview can be selected freely. You can highlight cells or cell groups. You can highlight all cells at a time (by clicking the square in the upper right corner of the grid ), you can also highlight one or more rows (by clicking in the row title column ). Based on the selection mode, you can even select one or more columns by selecting the column title. You can use a value in the datagridviewselectionmode enumeration to set the datagridview. selectionmode attribute to control this behavior, as described below:
• |
Cellselect: You can select cells, but cannot select the entire row or title. If datagridview. multiselect is true, you can select multiple cells. |
• |
Fullcolumnselect: Only the entire column can be selected when you click the column title. If datagridview. multiselect is true, you can select multiple columns. When this mode is used, clicking the column title does not sort the grid. |
• |
Fullrowselect: Only the entire row can be selected when you click the row title. If datagridview. multiselect is true, you can select multiple rows. |
• |
Columnheaderselect: You can use the cellselect or fullcolumnselect mode. When this mode is used, clicking the column title does not sort the grid. |
• |
Rowheaderselect: You can use the cellselect or fullrowselect mode. This is the default mode. |
You can use the following three attributes to conveniently retrieve selected cells: selectedcells, selectedrows, and selectedcolumns. No matter which selection mode is used, selectedcells always returns a set of datagridviewcell objects. On the other hand, if the row title is used to select the entire row, selectedrows returns only information. If the entire column is selected using the column title, selectedcolumns returns only information.
For example, the following code snippet checks the entire selected row. If a row is found, the corresponding value in the customerid column is displayed in the message box:
For Each SelectedRow As DataGridViewRow In _DataGridView1.SelectedRowsMessageBox.Show( _SelectedRow.Cells("CustomerID").Value)Next
Using the currentcell or currentcelladdress attribute to retrieve references to the current cell is also simple. When using the datagridview, you will notice that the current cell is surrounded by a rectangle, which looks like a box drawn with a black dotted line. This is the current location of the user.
The currentcelladdress attribute is read-only, but you can use currentcell to programmatically change the current location. After you complete this operation, the dview will be rolled to make the current position visible.
'Move to the fourth cell of row 11th. Datagridview. currentcell = _ datagridview. Rows (10). cells (3)
Back to Top
Datagridview object
So far, you have learned how to interact with the currently selected group of rows, cells, and columns. The datagridview provides two key sets for processing the entire dataset. These two sets are columns (the collection of the datagridviewcolumn object) and rows (the collection of the datagridviewrow object, each object references a collection of datagridviewcell objects ).Figure 2The object model is displayed.
In general, you will use the datagridviewcolumn object to configure the Column Display attributes, format settings, and title text, and use the datagridviewrow and datagridviewcell objects to retrieve the actual data from the bound records. When you modify data in the datagridviewcell, the processing method is the same as that of user editing: The corresponding datagridview change event is triggered and the underlying datatable is modified.
Now that you know the datagridview object model, you can easily create code to traverse the table. To select a row, column, or cell, you only need to find the corresponding datagridviewrow, datagridviewcolumn, or datagridviewcell object, and set the isselected attribute to true.
In the following example, all rows whose orderid field value is less than 100 are selected programmatically:
For Each Row As DataGridViewRow In DataGridView1.RowsIf Row.Cells("OrderID").Value < 100 ThenRow.Selected = TrueEnd IfNext
It is worth mentioning that there are several different classes derived from the datagridviewcolumn. These classes can control how values are displayed and edited in cells .. Net includes five pre-created dview columns: datagridviewbuttoncolumn, datagridviewcheckboxcolumn, datagridviewcomboboxcolumn, datagridviewimagecolumn, and datagridviewtextboxcolumn.
Back to Top
Datagridview Style
One of the challenges facing the design of the datagridview is to create a format setting system, which must be flexible enough to apply different levels of format settings, while maintaining high efficiency for very large tables. From the flexibility perspective, the best way is to allow developers to configure each cell separately. However, from the perspective of efficiency, this method may be harmful. A table containing thousands of rows has tens of thousands of cells. Maintaining different formats of each cell will definitely waste a lot of memory.
To solve this problem, the datagridview uses the datagridviewcellstyle object to implement a multi-layer model. The datagridviewcellstyle object represents the cell style and contains details such as color, Font, alignment, line feed, and data format. You can create a datagridviewcellstyle to specify the default format of the entire table. In addition, you can specify the default format of columns, rows, and cells. The more detailed the format settings, the more you create the datagridviewcellstyle object, the smaller the scalability of this solution. However, if you use column-based and row-based format settings, and occasionally set the format of each cell, compared with the DataGrid, The datagridview dview does not require much memory.
When you set the format of the datagridview application, the following priority is followed (from the highest to the lowest ):
1. DataGridViewCell.Style 2. DataGridViewRow.DefaultCellStyle 3. DataGridView.AlternatingRowsDefaultCellStyle 4. DataGridView.RowsDefaultCellStyle 5. DataGridViewColumn.DefaultCellStyle6. DataGridView.DefaultCellStyle
It is important to note that style objects are not applied in the "All/all" mode. The datagridview will check each attribute. For example, assume that your cell uses the datagridviewcell. Style attribute to apply the Custom font, but does not set the custom foreground color. As a result, the font setting overwrites the font information of any other style objects. However, if the foreground color of the next style object in the hierarchy is not empty, the foreground color is inherited from this object (in this case, it is a datagridviewrow. defaultcellstyle ).
Datagridviewcellstyle defines two format settings: Data and appearance. Data format settings describe how to modify a data binding value. This format usually includes converting numeric or date values to text using the format setting string. To set the data format, you only need to use the datagridviewcellstyle. Format attribute to set the format definition or custom format string.
For example, the following code snippet sets the format of all numbers in the unitcost field to display them as currency values, retain two decimal places, and add the corresponding currency symbols defined in the region settings:
DataGridView1.Columns("UnitCost"). _DefaultCellStyle.Format = "C"
The appearance format settings include surface details such as colors and formats. For example, the following code is right-aligned with the unitcost field, applies the bold text, and changes the background of the cell to Yellow:
DataGridView1.Columns("UnitCost"). _DefaultCellStyle.Font = _New Font(DataGridView.Font, FontStyle.Bold)DataGridView1.Columns("UnitCost"). _DefaultCellStyle.Alignment = _DataGridViewContentAlignment.MiddleRightDataGridView1.Columns("UnitCost"). _DefaultCellStyle.BackColor = Color.LightYellow
Other formatting-related attributes include forecolor, selectionforecolor, selectionbackcolor, and wrapmode (controls whether the text can span multiple lines or be truncated directly when space permits) and nullvalue (will replace the null value ).
The datagridview datagrialso includes a designer for configuring column styles during design. You only need to select the "datagridview properties" link from the "properties" window, or select "AutoFormat" from various pre-created style settings ).
Back to Top
Custom cell format
The first way to set the cell format is to set the more advanced attributes of the datagridview, datagridviewcolumn, and datagridviewrow. However, sometimes you need to set a style for a specific cell. For example, you may need to mark the data in the column when the data in the column is greater than or less than a certain value. For example, highlight the expiration date in the Project Plan list or highlight the negative rate of return in the sales analysis. In both cases, you need to set the format of individual cells.
After learning about the datagridview object model, you may want to traverse the cell set in a specific column to find the value to be highlighted. This method is feasible, but not the best one. The key issue is that if the user edits the data or the code changes the bound data source, the highlighted cells are not updated accordingly.
Fortunately, the datagridview provides the cellformatting event for this purpose. Cellformatting is only triggered before the cell value is displayed. This event allows you to update the cell style based on the content of cells. The following example checks specific customers and marks cells accordingly:
Private sub datagridviewinclucellformatting (_ byval sender as system. Object, _ byval e as system. Windows. Forms. _ datagridviewcellformattingeventargs) _ handles datagridview1.cellformatting 'check whether the column is correct. If datagridview1.columns (E. columnindex). Name = _ "mermerid" then "check whether the value is correct. If E. value = "alfki" thene. cellstyle. forecolor = color. rede. cellstyle. backcolor = color. yellowend ifend sub
Style is not the only detail that affects the appearance of the grid. You can also hide columns, move columns between different positions, and "freeze" columns so that these columns are still visible when you scroll to the right. These functions are provided through the attributes of the datagridviewcolumn class, as described below:
• |
Displayindex: Sets the position of the column displayed in the datagridview. For example, columns whose displayindex value is 0 are automatically displayed in the leftmost column. If multiple columns have the same displayindex, the columns first appear in the set. Therefore, if you use displayindex to move a column to the left, you may also need to set displayindex for the leftmost column to move it to the right. Initially, displayindex matches the index of the datagridviewcolumn object in the datagridview. columns set. |
• |
Frozen: If it is true, the column is always visible and fixed on the left side of the table, even if you scroll to the right side to view other columns. |
• |
Headertext: Set the text to be displayed in the column title. |
• |
ResizableAndMinimumwidth: Set resizable to false to prevent you from adjusting the column width, or set minimumwidth to the allowed minimum number of pixels. |
• |
Visible: To hide a column, set this attribute to false. |
Back to Top
Button Column
A column provided by the datagridview is the datagridviewbuttoncolumn, which displays a button next to each item. You can respond to the click event of this button and use it to start other operations or display a new form.
The following example uses the button text "details..." to create a simple button column:
'Create button columns. Dim details as new maid () details. Name = "details" 'disable Data Binding and display static text. '(However, you can use the attributes in the table by setting the datapropertyname' attribute .) Details. displaytextasformattedvalue = falsedetails. Text = "details..." 'clear the title. Details. headertext = "" 'to add this column. Maid. insert (_ maid. Count, details)
Figure 3Displays the grid containing the new column. The following code responds to the button-Click Event in any row and displays the corresponding record information:
Private Sub DataGridView1_CellClick( _ByVal sender As System.Object, _ByVal e As System.Windows.Forms. _DataGridViewCellEventArgs) _Handles DataGridView1.CellClickIf DataGridView1.Columns(e.ColumnIndex).Name = _"Details" ThenMessageBox.Show("You picked " & _DataGridView1.Rows(e.RowIndex). _Cells("CustomerID").Value)End IfEnd Sub
A realistic solution is to create and display a new window at this time, and pass the information about the selected record to this new window for query and display the complete information.
Back to Top
Image Column
Another column provided by the datagridview is the datagridviewimagecolumn, which displays an image in the cell border. You can set the datagridviewimagecolumn. layout attribute to configure the display mode of the image in the cell: whether to expand the cell to an appropriate size or to directly crop an image that is too large.
You can use datagridviewimagecolumn in two ways. First, you can manually create and add the column in the same way as datagridviewbuttoncolumn. This column is useful if you need to display the image information not provided by dataset itself. For example, you may need to get the file name (such as productpic002.gif), read the corresponding file from the network drive, and then display the file in the grid. To complete this operation, you need to respond to the datagridview event (such as cellformatting) to read the image of the corresponding row, obtain image data, and insert it using the value attribute in the column.
If dataset contains binary image data that does not require any manual operations, the process becomes simpler. For example, the pub_info table in the SQL Server pubs database contains the company logo. When binding to this table, you do not need to perform any additional steps. The datagridview automatically identifies the image you are using and creates the required datagridviewimagecolumn. (For an example of this technology, see the download content in this article .)
Back to Top
Edit the datagridview
As we all know, the user input function of the DataGrid is not flexible, and you have almost no way to customize cell verification methods and error reporting methods. On the other hand, datagridview allows you to control the behavior of a datagridview by responding to a large number of different events triggered during all stages of the editing process.
By default, When you double-click a cell or press the F2 key, the datagridview cell enters the editing mode. You can also set the datagridview. editcellonenter attribute to true to configure the datagridview, so that when the user moves to the cell, the Cell will immediately switch to the editing mode. You can also use the beginedit (), canceledit (), commitedit (), and endedit () Methods of the datagridview. to start and stop cell editing programmatically. When you edit a cell, a pencil-like Editing Icon is displayed in the row title.
You can press ESC to cancel editing. If the editcellonenter attribute is set to true, the cell is still in edit mode, but all changes will be abandoned. To submit changes, you only need to move to a new cell or switch the focus to another control. If your code can move the position of the current cell, the code will also submit changes.
To prevent cells from being edited, you can set the readonly attribute of the datagridviewcell, datagridviewcolumn, datagridviewrow, or datagridview (depending on whether you want to prevent changes to the cell, modify all cells in the column, and change all cells in the row )., to avoid changing all cells in the table ). The datagridview datagrialso provides the cellbeginedit event to cancel the attempt editing.
Back to Top
Handling error
By default, datagridviewtextboxcolumn allows you to enter any characters, including those that may not be allowed in the current cell. For example, you can type a non-numeric character in a numeric field or specify a value that conflicts with the foreignkeyconstraint or uniqueconstraint defined in dataset. Datagridview uses different methods to solve these problems:
• |
If you can convert the edited value to the required data type (for example, if you type text in the Number Column), you cannot submit changes or navigate to other rows. You must cancel the change or edit the value. |
• |
If the edited value conflicts with the constraint in dataset, the change will be canceled immediately after you navigate to another row or press enter to submit the change. |
These processing methods are applicable in most cases. However, if necessary, you can also participate in error handling by responding to the datagridview. dataerror event, which is triggered when the datagridview detects an error from the data source.
Back to Top
Verification Input
Verification is a slightly different task from error handling. Through error handling, you can handle issues reported by dataset. Through verification, you can capture errors defined by yourself. For example, the data allowed in dataset is meaningless in the application.
When you navigate to a new cell to submit changes, the datagridview control triggers cellvalidating and cellvalidated events. These events are followed by rowvalidating and rowvalidated events. You can respond to these events, check whether the value entered by the user is correct, and perform any post-processing required. If the value is invalid, you can usually respond in two ways: cancel the change and cell navigation (by setting the cancel attribute of the eventargs object to true ), or set some error text to remind the user. You can place the error text in other controls, or use the errortext attribute of the corresponding datagridviewrow and datagridviewcell to display the error text in the DataGrid:
• |
When datagridviewcell. errortext is set, the exclamation point icon is displayed in the cell. Hover the mouse over this icon to display an error message. |
• |
When datagridviewrow. errortext is set, the exclamation point icon is displayed in the row title on the left of the row. Hover the mouse over this icon to display an error message. |
Generally, you can combine these two attributes and set error messages in rows and cells. The following example checks too long text input in the companyName field. If a problematic value is found, the error symbol (red exclamation point) is added to the cell and the tooltip text describing the problem is displayed.
Private Sub DataGridView1_CellValidating( _ByVal sender As System.Object, _ByVal e As System.Windows.Forms. _DataGridViewCellValidatingEventArgs) _Handles DataGridView1.CellValidatingIf DataGridView1.Columns(e.ColumnIndex).Name = _"CompanyName" ThenIf CType(e.FormattedValue, String).Length > _50 ThenDataGridView1.Rows( _e.RowIndex).Cells(e.ColumnIndex). _ErrorText = _"The company name is too long."End IfEnd IfEnd Sub
Back to Top
Use List column constraints to select
Use verification to capture any errors. However, this method is not necessarily the best, because it allows the user to enter invalid content, and then tries to correct the invalid input after the facts appear. A better solution is to prevent users from entering any invalid content at the beginning.
A common example is to restrict a column to the range of a pre-defined value list. In this example, the easiest way for a user is to select the correct value from the list instead of entering the value manually. The biggest advantage is that you can use datagridviewcomboboxcolumn to easily implement this design.
You can use the items set to manually add an item list for the datagridviewcomboboxcolumn, just like using ListBox. In addition, you can bind the datagridviewcomboboxcolumn to another data source. In this case, you can use the datasource attribute to specify the data source, use the displaymember attribute to indicate the value to be displayed in the column, and use the valuember attribute to specify the value to be used by the underlying column value.
To demonstrate this situation, let's take a look at the next example about the products table. Each record in this table is linked to the record in the categories table through its categoryid field. To change the product category, you must remember the correct ID and enter it in the categoryid field. A better solution is to use the datagridviewcomboboxcolumn bound to the categories table. This column uses categoryname as the display value, but uses categoryid as the real underlying value. This column will still be bound to the products table through the datapropertyname attribute, which means that when you select a new category from the list, the categoryid field of the product record will be changed automatically.
The following code is required to configure the table:
'Delete the automatically generated categoryid column. Datagridview1.columns. Remove ("categoryid") 'creates a list column for categoryid. Dim list as new datagridviewcomboboxcolumn () List. displayindex = 0list. headertext = "category" 'This column is bound to the 'products. categoryid field. List. datapropertyname = "categoryid" 'This list retrieves data from the categories table. List. datasource = Ds. Tables ("categories") List. displaymember = "categoryname" list. valuemember = "categoryid" 'add this column. Datagridview1.columns. Add (list)
Back to Top
Summary
This article outlines one of the most anticipated. Net controls: dview. Unlike the DataGrid, The datagridview can be used in different situations-whether to process data binding, user editing, or static text display only. In short, this article gives you a closer look at the integrated data solution provided by. NET Framework, and one of the most striking reasons for Windows form developers to upgrade to. NET 2.0.
Download 501macdonald. Zip
For more information about Visual Studio. NET developer and pinnacle Hing, visit their Web site http://www.pinpub.com /.
Note: This is not a web site of Microsoft Corporation. Microsoft is not liable for its content.
This article is reproduced from Visual Studio. NET developer in July. Unless otherwise stated, all rights reserved are 2005 pinnacle Hing, Inc .. All rights reserved. Visual Studio. NET developer is an independent publication of pinnacle Hing, Inc. No part of this article shall be used or reproduced in any form without the prior consent of pinnacle Publishing, Inc. (except for short references in comments ). To contact pinnacle Hing, inc., call 1-800-788-1900.
Go to the original English page
Link from msdn to: http://www.microsoft.com/china/msdn/library/langtool/vsdotnet/vs05a9.mspx