Manning Windows Forms Programming (phần 13) ppt

50 223 0
Manning Windows Forms Programming (phần 13) 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

566 CHAPTER 17 DATA BINDING b Caption Displays a short string describing the table. c DataGridTableStyle class Used to customize the appearance and behavior of tables. DataGridColumnStyle class Used to customize the order, appearance and behavior of columns. The framework supports text and boolean columns by default. d Row Header The area in front of a row. The small triangle indicates the current item. e Grid Lines The color and style of lines are configurable. f Cell Refers to an individual value within the grid. g Column Header Shows the name of each column. The ListView class discussed in chapter 14 can also be used to present a table of information. The Windows Forms namespace provides explicit classes to represent the rows and columns in a list view. As you may recall, each item, or row, in the list is represented by the ListViewItem class instance, and each column by a ListView- SubItem instance and is presented based on a ColumnHeader instance. As illustrated by figure 17.2, the DataGrid class takes a somewhat different approach. The contents of the grid are contained in a single collection, such as an array, a photo album, or a database table. Classes exist to configure the style in which the provided data is displayed, including colors, column ordering, and other proper- ties. We will discuss the details of these style classes later in the chapter. b d c E F G Figure 17.2 This chapter will discuss many of the terms and classes related to data grids. DATA GRIDS 567 .NET Table 17.1 DataGrid class The DataGrid class represents a control that displays a collection of data as a grid of rows and columns. The data displayed and the style in which it is presented is fully configurable. This class is part of the System.Windows.Forms namespace, and inherits from the Control class. See .NET Table 4.1 on page 104 for a list of members inherited by this class. Public Properties AllowNavigation Gets or sets whether navigation is permitted. AlternatingBackColor Gets or sets the background color to use on every other row in the grid to create a ledger- like appearance. CaptionText Gets or sets the text to appear in the caption area. CaptionVisible Gets or sets whether the caption is visible. Other properties related to this and other grid areas are also provided. CurrentCell Gets or sets a DataGridCell structure representing the cell in the grid that has the focus. CurrentRowIndex Gets or sets the index of the selected row. DataMember Gets or sets which list in the assigned data source should be displayed in the grid. DataSource Gets or sets the source of data for the grid. Item Gets or sets the value of a cell. This property is the C# indexer for this class. ReadOnly Gets or sets whether the grid is in read-only mode. RowHeaderWidth Gets or sets the width of row headers in pixels. TableStyles Gets the collection of DataGridTableStyle objects specifying display styles for various tables that may be displayed by the grid. Public Methods BeginEdit Attempts to begin an edit on the grid. HitTest Returns location information within the grid of a specified point on the screen. This works much like the HitTest method in the MonthCalendar class. SetDataBinding Assigns the DataSource and DataMember properties to the given values at run time. Unselect Deselects a specified row. Public Events CurrentCellChanged Occurs when the current cell has changed. DataSourceChanged Occurs when a new data source is assigned. Navigate Occurs when the user navigates to a new table. Scroll Occurs when the user scrolls the data grid. 568 CHAPTER 17 DATA BINDING 17.1.1 CREATING THE MYALBUMDATA PROJECT While the DataGrid class includes numerous members for customizing the appear- ance and behavior of the control, it is possible to create a very simple grid with only a few lines of code. We will begin with such an application, and enhance it over the course of the chapter. The following table lays out the creation and initial layout of our new application. CREATE THE MYALBUMDATA PROJECT Action Result 1 Create a new project and solution in Visual Studio .NET called “MyAlbumData.” The new solution is shown in the Solution Explorer window, with the default Form1.cs [Design] window displayed. 2 Rename the Form1.cs file and related class file to our standard MainForm class and assign some initial settings for this form. 3 Drag a Label, ComboBox, DataGrid, and Button control onto the form. Arrange these controls as shown in the graphic. 4 Create a Click event handler for the Close button to shut down the application. private void btnClose_Click (object sender, System.EventArgs e) { Close(); } Settings Property Value (Name) MainForm Size 450, 300 Text MyAlbumData Settings Control Property Value Label Text &Album ComboBox (Name) cmbxAlbum Anchor Top, Left, Right DataGrid (Name) gridPhoto- Album Anchor Top, Bottom, Left, Right Button (Name) btnClose Anchor Bottom, Right Text &Close DATA GRIDS 569 With our initial window in place, we are ready to display some album data in the window. 17.1.2 D ISPLAYING DATA IN A DATA GRID Our main window in the MyAlbumData application contains a combo box and a data grid. Our ComboBox control will contain a list of the albums located in the default album directory, while our DataGrid control will display the contents of the selected album. This section will make the changes required for this behavior. Section 17.2 will look at customizing the information displayed by the grid. Fortunately, our existing MyPhotoAlbum project can do most of the work here. The changes required are detailed in the following steps. Set the version number of the MyAlbumData application to 17.1. DISPLAY ALBUM DATA IN THE MYPHOTOALBUM APPLICATION Action Result 1 In the Solution Explorer window, add the MyPhotoAlbum project to the solution and reference it from the MyAlbumData project. 2 At the top of the MainForm.cs code window, add a using statement for the new project and the System.IO namespace. using System.IO; using Manning.MyPhotoAlbum; 3 Define a private PhotoAlbum field within the MainForm class. private PhotoAlbum _album; 570 CHAPTER 17 DATA BINDING 4 Override the OnLoad method to: a. Add the version number to the title bar. b. Initialize the photo album. c. Set the album file names to appear in the ComboBox control. Note: The assignment of the DataSource property here is an example of data binding. In this case, we are binding the collec- tion of objects for the ComboBox control to an array of directory strings. protected override void OnLoad(EventArgs e) { Version ver = new Version(Application.ProductVersion); Text = String.Format( "MyAlbumData {0:#}.{1:#}", ver.Major, ver.Minor); _album = new PhotoAlbum(); cmbxAlbum.DataSource = Directory.GetFiles( PhotoAlbum.DefaultDir, "*.abm"); } 5 Handle the SelectedIndex- Changed event for the ComboBox object. private void cmbxAlbum_SelectedIndexChanged (object sender, System.EventArgs e) { 6 In this handler, retrieve the string selected in the combo box and dispose of any existing album. string albumFile = cmbxAlbum.SelectedItem.ToString(); if (_album != null) _album.Dispose(); 7 Open the selected album file. _album.Clear(); try { _album.Open(albumFile); 8 If the album opens successfully, assign the album title as the caption text for the DataGrid control. gridPhotoAlbum.CaptionText = _album.Title; } 9 If the album cannot be opened, clear the album and assign an error message as the caption text. catch (Exception) { _album.Clear(); gridPhotoAlbum.CaptionText = "Unable to open album"; } 10 Bind the contents of the resulting album to appear in the DataGrid control. gridPhotoAlbum.SetDataBinding(null, null); gridPhotoAlbum.SetDataBinding(_album, null); } Note: Since the value of the _album field does not actually change, we force the data grid to reload the album data by binding it to null and then rebinding to our PhotoAlbum instance. We will do this a bit more elegantly later in the chapter. DISPLAY ALBUM DATA IN THE MYPHOTOALBUM APPLICATION (continued) Action Result DATA GRIDS 571 This code opens the selected album and assigns the title of the album to appear in the caption area of the data grid. The collection of photographs in the album is bound to the contents of the data grid. The result is shown in figure 17.3. The caption area at the top of the control is assigned using the CaptionText prop- erty. In the figure, the title of the colors.abm album is “Lots of Colors” as is shown in the caption. The data source for the grid is assigned using the SetDataBinding method. This method has the following signature: public void SetDataBinding(object dataSource, string dataMember); The dataSource parameter is assigned to the DataSource property of the control, while the dataMember parameter is assigned to the DataMember property. In our application, the control recognizes our PhotoAlbum object as an IList interface containing a collection of Photograph objects. This is performed internally using the GetType method available on all object instances. The properties of the Photograph object are determined internally using the mem- bers of the System.Reflection namespace. These properties are then used as the col- umns in the grid, and each Photograph in the album is presented as a row in the grid. We will not discuss the System.Reflection namespace in detail here. This namespace permits .NET objects such as the DataGrid control to determine the type of object and members of that type at runtime. In this way our data grid can under- stand how the PhotoAlbum object is organized, and automatically create an appro- priate grid structure. Since the order of columns in the grid corresponds to the internal order of prop- erties in the PhotoAlbum class, your columns might be ordered differently than is shown in figure 17.3. Also note that properties which only provide a get access method are treated as read-only, while properties with both a get and set access method are modifiable. As a result the Image and IsImageValid columns in our grid are read-only, while the Photographer and Notes columns can be modified. We will look at how to update the class with these changes shortly. Figure 17.3 The DataGrid control sup- ports two types of entries by default. Boolean values, such as the IsImageValid property, appear as check boxes. All other properties display the result of their ToString prop- erty as a text entry. 572 CHAPTER 17 DATA BINDING Back to our SetDataBinding method, there are a number of different classes that can serve as a source of data, depending on the type of C# interfaces they support. A summary of data sources for the DataGrid class is given in the following table. Data sources for the data grid control Interface Usage Notes IList A homogenous collection of objects. The first item in the list determines the type. The first property in that type is displayed as the only column when bound to a data grid. This includes any simple array in C#, and all classes based on the Array object. typed IList A typed collection, such as our PhotoAlbum class. The type returned by the Item property is used as the assigned type, and all properties in this type can be displayed in a data grid. These can be bound to a data grid only at run time. Most notably, classes derived from CollectionBase, such as our PhotoAlbum class. Other classes with an indexer of a fixed type will also work here. IList and IComponent With both interfaces available, the class may appear in Visual Studio .NET in the component tray and be bound to a data grid at design time. Integrating a collection class with Visual Studio .NET is beyond the scope of this book. A control can be added to the Toolbox using the Customize entry in the Toolbox window’s popup menu. This often requires members of the System.Windows.Forms.Design namespace to properly interact with the Windows Forms Designer and Property windows. IBindingList This interface permits two-way notification of changes, both from the control to the class and from the class to the control. The DataView class in the System.Data namespace implements this interface, allowing a data grid to update its contents when the underlying database is modified. IEditableObject Classes implementing this interface are permitted to roll back, in a transaction- oriented manner, a changes made to an object. a. The term transaction indicates that a series of steps either fully completes or appears to never have hap- pened. For example, when transferring money between bank accounts, you must debit the first account and then credit the second account. By making such a transfer transactional, you ensure that the first account is never debited without guaranteeing that the second account is also credited. Aborting an operation part-way through the required steps is said to roll back, or undo, the operation. The DataRowView class is a customized view of a row that supports transactional changes to the elements of the row. IDataErrorInfo Objects can offer custom error information that controls can bind to. The DataRowView class supports this interface as well in order to provide appropriate feedback in a DataGrid control when an error occurs. DATA GRID CUSTOMIZATION 573 For our purposes, we will continue to use the typed IList interface supported by our PhotoAlbum class. Later in the chapter we will add support for the IEdit- ableObject interface in order to properly save modifications made in our data grid. The next section discusses various ways of customizing what appears in the grid. 17.2 DATA GRID CUSTOMIZATION One of the obvious drawbacks of letting .NET do all the work in laying out the con- tents of a data grid is that we have no control over the selection and order of columns to appear in the grid. In this section we will look at how to customize the contents of a data grid for a particular data source using table and column styles. This will enable us to build the application shown in figure 17.4. In our current application we display a single kind of table, namely one based on the PhotoAlbum class. In general, the data displayed in a data grid may vary depending on the actions of the user. For example, just as our ListView control in chapter 14 displayed both albums and photographs, we could create an AlbumCollection class derived from CollectionBase to contain the set of albums located in a given directory. We could then use this class to display both album files and the contents of albums in our data grid. More commonly, a data grid is filled with information from a database, which includes one or more tables. An employee database at a company might have one table containing department information, another table containing the employees assigned to each department, and another containing the projects each employee is assigned to. A single data grid could display all three types of tables based on a set of options, and it would be nice to customize the appearance of each type of table. Figure 17.4 This data grid displays only certain properties of photographs, and the size and content of each column are somewhat customized compared with the application in the previous section. 574 CHAPTER 17 DATA BINDING The TableStyles property in the DataGrid class supports this notion of con- figuring the appearance of multiple tables. This property contains a collection of Data- GridTableStyle objects, each of which describes the configuration for a table that might be displayed by the grid. The DataGridTableStyle class, in turn, provides a GridColumnStyles property that contains a collection of DataGridColumnStyle objects. We will discuss each of these classes separately. 17.2.1 C USTOMIZING TABLE STYLES The DataGridTableStyle class permits a custom style for a specific type of table to be defined. Many of the members of this class are duplicates of similar members in the DataGrid class. The members of the active table style always override the default settings for the data grid. A summary of this class appears in .NET Table 17.2. .NET Table 17.2 DataGridTableStyle class The DataGridTableStyle class represents the style in which to display a particular table that can appear in a DataGrid control. It configures not only the general properties for the table but also the individual columns that should appear in the table. This class is part of the System.Win- dows.Forms namespace, and inherits from the System.ComponentModel.Component class. Public Properties AllowSorting Gets or sets whether sorting is allowed on the grid when this DataGridTableStyle is used. AlternatingBack- Color Gets or sets the background color for alternating rows in the grid when this DataGridTableStyle is used. DataGrid Gets or sets the DataGrid control containing this style. GridColumn- Styles Gets or sets the collection of DataGridColumnStyle objects to use for the grid when this style is used. LinkColor Gets or sets the color of link text to use in the grid when this style is used. MappingName Gets or sets the name used to associate this table style with a specific data source. For a data source based on an IList interface, the name of the list is specified, as in myList.GetType().Name. For a data source based on a DataSet instance, a valid table name in the data set should be specified. ReadOnly Gets or sets whether columns can be edited in the grid when this style is used. RowHeader- Width Gets or sets the width of row headers in the grid when this style is used. Public Methods BeginEdit Requests an edit operation on a row in the grid. EndEdit Requests an end to an edit operation in the grid. ResetBackColor Resets the BackColor property to its default value. A number of other reset methods exist with a similar purpose. Public Events AllowSorting- Changed Occurs when the AllowSorting property value changes. A number of other changed events exist with a similar purpose. DATA GRID CUSTOMIZATION 575 There are two keys to understanding the DataGridTableStyle class. The first is the MappingName property. When a new source of data is assigned to a DataGrid control, the list of table styles is examined to locate a style whose MappingName set- ting matches the name of the table. If one is found, then that style is used to display the grid. If no match is found, then the default settings for the grid control are used. It is an error to assign identical mapping names to multiple styles within the same data grid. The second key to understanding this class is the GridColumnStyles property. This property is a collection of DataGridColumnStyle objects and specifies the selection and order of columns to display in the grid. If the GridColumnStyles property is null, then the default set of columns is displayed. We can use the DataGridTableStyle class to modify the appearance of our DataGrid control when a PhotoAlbum is displayed. We will make the very simple change of providing an alternating background color for the table. The steps required are presented in the following table. Set the version number of the MyAlbumData application to 17.2 This very simple change causes the application to display as is shown in figure 17.5. Of course, the AlternatingBackColor and RowHeaderWidth properties are available in the DataGrid class and can be set explicitly for this class. Assigning them in a table style uses these properties only when a matching table name is displayed, in this case a PhotoAlbum object. Note that our choice of light gray may not work very well with some user’s desktop colors. You can use an alternate color if you prefer, or a system color such as System- Colors.ControlLight . In your own applications, make sure you carefully select PROVIDE A CUSTOM TABLE STYLE WHEN A PHOTOALBUM IS DISPLAYED Action Result 1 In the MainForm.cs code window, create a table style instance in the OnLoad method. Note: A table style can also be created in the [Design] window by clicking on the … button in the TableStyles property. Here we elect to create the table style by hand. protected override void OnLoad(EventArgs e) { . . . // Table style for PhotoAlbum data source DataGridTableStyle albumStyle = new DataGridTableStyle(); 2 Configure the new style for a PhotoAlbum table with an alternating background color of LightGray. albumStyle.MappingName = "PhotoAlbum"; albumStyle.AlternatingBackColor = Color.LightGray; albumStyle.RowHeaderWidth = 15; 3 Assign the new style to the existing DataGrid control. // Assign the table style to the data grid gridPhotoAlbum.TableStyles.Add(albumStyle); } [...]... BindingManagerBase class The BindingManagerBase class represents a data source bound to one or more controls within a Windows Forms control This class enables synchronization of all controls with a property bound to the associated data source This class is part of the System .Windows. Forms namespace This class is abstract and cannot be instantiated The CurrencyManager class is used for all data sources... 591 .NET Table 17.6 Binding class The Binding class represents a simple data binding between a data source entry and a Windows Form control The Binding instances defined for a control are contained by the DataBindings property of that control This class is part of the System .Windows. Forms namespace Binding Public Constructor Create a new Binding instance This has the following signature: Binding(string... 17.5 IEditableObject interface The IEditableObject interface represents an interface for performing transactional operations on an object This interface is used by various NET classes such as the Windows Forms DataGrid control to allow an object to track and enforce transactional behavior This interface is part of the System.ComponentModel namespace BeginEdit Initiates an edit operation on an object... MyAlbumData application This is taken up in the next section 17.3.3 584 USING EDITABLE OBJECTS Typically, you do not actually use the editable object methods directly These are used internally by Windows Forms as required for the task at hand In this case, our DataGrid control automatically recognizes that our PhotoAlbum object supports this interface, and calls BeginEdit whenever a user initiates... built by Andrew Skowronski that is available at http://cdrcatalog.sourceforge.net/ This program manages offline media, such as a collection of recordable compact discs, and makes use of a number of Windows Forms classes in addition to the DataGrid control The data source used by this application is a DataSet object loaded from a local XML file SIMPLE DATA BINDING Binding data to a data grid is referred... is used for binding single property values to a specific data source This type of binding is supported by the Control class directly, and is therefore inherited by and available in all controls in Windows Forms The concepts and techniques for so-called simple data binding are fairly identical to those we have already discussed for the DataGrid control In this section we will alter our application to... tracking which data has been bound to which control, managing a bound data source, tracking specific bindings to a control, and managing the actual bindings A summary of these roles, along with the Windows Forms class and property related to these roles, is outlined in the following table: Roles required for simple data binding Role Class Accessing from Control class Tacking bound data BindingContext... typically contained within a DataGridTableStyle object, and indicates the position and style for the corresponding column when a table of the specified type is displayed This class is part of the System .Windows. Forms namespace, and inherits from the System.ComponentModel.Component class A DataGridColumnStyle object cannot be instantiated, as this is an abstract class The DataGridBoolColumn and DataGridTextBoxColumn... column style for string data This class hosts, or manages within a cell of the DataGrid control, a TextBox instance to support editing of string values within the table This class is part of the System .Windows. Forms namespace, and inherits from the DataGridColumnStyle class See NET Table 17 for a list 3 of members inherited from this class Format Gets or sets a string specifying how text should be formatted... BINDING .NET Table 17.8 CurrencyManager class The CurrencyManager class represents a binding manager that is associated with a data source supporting the IList interface This class is part of the System .Windows. Forms namespace, and inherits from the BindingManagerBase class See NET Table 17 for the 7 members inherited from the base class Refresh Forces a repopulation of all bound controls for a data source . menu. This often requires members of the System .Windows. Forms. Design namespace to properly interact with the Windows Forms Designer and Property windows. IBindingList This interface permits two-way. the style in which it is presented is fully configurable. This class is part of the System .Windows. Forms namespace, and inherits from the Control class. See .NET Table 4.1 on page 104 for a. ListView class discussed in chapter 14 can also be used to present a table of information. The Windows Forms namespace provides explicit classes to represent the rows and columns in a list view.

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

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

Tài liệu liên quan