As I said .earlier in this chapter, the DataGridView control is the new replacement for all of its earlier successors exposed one at a time over the decade since the introduction of Visual Basic. No, I don't really think it was written by a summer intern or new employeeit's really pretty sophisticated. It makes a good way to expose rows from a DataTable or DataView instance. Once it's populated with schema, it's easy to customize. However, you can't pre-populate the control until you have a data source with which to populate it. Yes, by far the easiest way to bind to data is by dragging a TableAdapter to the Form, which gets Visual Studio to instantiate a DataGridView and set its properties to map the DataTable columns. Once you've done so, you can click the "tasks" button on the upper-right corner of the DataGridView to expose the "DataGridView Tasks" menu, shown in Figure 7.22. Figure 7.22. Setting options with the tasks dialog.The tasks dialog permits you to determine how the DataGridView is to behavewhether or not it supports updates or column reordering. It also permits you to set docking behavior as well as how the columns are displayed. You can also add columns that must be custom bound. Clicking on the Edit Columns... link opens the Edit Columns dialog, shown in Figure 7.23. This gives you an opportunity to set properties like ReadOnly (to prevent changes to the column) and the ability to sort the column through the DataGridView UI. Note that the Au_ID column (the primary key) ReadOnly property is automatically set to True. Figure 7.23. Editing columns configured in the DataGridView.For read/write columns that are bound to string values, you can set the MaxInputLength to prevent strings that are too long. Unfortunately, this value is not automatically set, so if the user enters a string longer than that defined in the underlying DataTable, your code will throw an exception. I suggest adding code to your application to automatically set the MaxInputLength property based on the defined column width. The DataGridView also does not expose the datatype of the underlying DataTable Column, but the DataGridView knows what it is and makes sure that any value you enter conforms to the type's formatting and range restrictions. For example, if you bind to a date, any value entered into the DataGridView column must be recognized as a valid date value. The same criterion is applied to numeric types, including range-checking integers, currency, and other numerics. Be prepared to trap the DataError event when these validation rules are violated. I discuss this issue again in Chapter 13 when we visit the update operations.
What happened to "Auto Format"? During the beta tests, the "Action" dialog (which the "Tasks" dialog replaced) included an "Auto Format" option that permitted you to choose a decorative skin for your DataGridView control. While it was a popular feature of the old DataGrid control, it's not available (yet) for the DataGridView. |