Programmatic Data GridView Construction

The most common way of using the grid is with data-bound columns. When you bind to data, the grid creates columns based on the schema or properties of the data items, and generates rows in the grid for each data item found in the bound collection. If the data binding was set up statically using the designer (as has been done in most of the examples in this book), the types and properties of the columns in the grid were set at design time. If the data binding is being done completely dynamically, the AutoGenerateColumns property is TRue by default, so the column types are determined on the fly based on the type of the bound data items. You may want to create and populate a grid programmatically when working with a grid that contains only unbound data. To know what code you need to write, you need to know the DataGridView object model a little better.

The first thing to realize is that like all .NET controls, a grid on a form is just an instance of a class. That class contains properties and methods that you can use to code against its contained object model. For DataGridView controls, the object model includes two collectionsColumns and Rowswhich contain the objects that compose the grid. These objects are cells, or more specifically, objects derived from instances of DataGridViewCell. The Columns collection contains instances of DataGridViewColumn objects, and the Rows collection contains instances of DataGridViewRows.

Programmatically Adding Columns to a Grid

There are a number of ways to approach programmatically adding columns and rows to the grid. The first step is to define the columns from which the grid is composed. To define a column, you have to specify a cell template on which the column is based. The cell template will be used by default for the cells in that column whenever a row is added to the grid. Cell templates are instances of a DataGridViewCell derived class. You can use the .NET built-in cell types to present columns as text boxes, buttons, check boxes, combo boxes, hyperlinks, and images. Another built-in cell type renders the column headers in the grid. For each of the cell types, there is a corresponding column type that is designed to contain that cell type. You can construct DataGridViewColumn instances that provide a cell type as a template, but in general you'll want to create an instance of a derived column type that is designed to contain the specific type of cell you want to work with. Additionally, you can define your own custom cell and column types (discussed later in this chapter).

For now, let's stick with the most common and simple cell type, a DataGridViewTextBoxCella text box cell. This also happens to be the default cell type. You can programmatically add a text box column in one of three ways:

® Use an overloaded version of the Add method on the Columns collection of the grid:

// Just specify the column name and header text m_Grid.Columns.Add("MyColumnName", "MyColumnHeaderText");

® Obtain an initialized instance of the DataGridViewTextBoxColumn class. You can achieve this by constructing an instance of the DataGridViewTextBoxCell class and passing it to the constructor forthdDataGridViewColumn, or just construct an instance of a DataGridViewTextBoxColumn using the default constructor. Once the column is constructed, add it to the Columns collection of the grid:

DataGridViewTextBoxColumn newCol = //Or this:

new DataGridViewTextBoxColumn();

DataGridViewTextBoxCell newCell = new DataGridViewTextBoxCell(); DataGridViewColumn newCol2 = new DataGridViewColumn(newCell); // Then add to the columns collection: m_Grid.Columns.Add(newCol); m_Grid.Columns.Add(newCol2);

If you add columns this way, their name and header values are null by default. To set these or other properties on the columns, you can access the properties on the column instance before or after adding it to the Columns collection. You could also index into the Columns collection to obtain a reference to a column, and then use that reference to get at any properties you need on the column.

Set the grid's ColumnCount property to some value greater than zero. This approach is mainly used to quickly create a grid that only contains text box cells or to add more text box columns to an existing grid.

// Constructs five TextBox columns and adds them to the grid m_Grid.ColumnCount = 5;

When you set the ColumnCount property like this, the behavior depends on whether there are already any columns in the grid. If there are existing columns and you specify fewer than the current number of columns, the ColumnCount property will remove as many columns from the grid as necessary to create only the number of columns you specify, starting from the rightmost column and moving to the left. This is a little destructive and scary because it lets you delete columns without explicitly saying which columns to eliminate, so I recommend to avoid using the ColumnCount property to remove columns.

However, when adding text box columns, if you specify more columns than the current number of columns, additional text box columns will be added to the right of the existing columns to bring the column count up to the number you specify. This is a compact way to add some columns for dynamic situations.

Programmatically Adding Rows to a Grid

Once you have added columns to the grid, you can programmatically add rows to the grid as well. In most cases, this involves using the Add method of the Rows collection on the grid. When you add a row this way, the row is created with each cell type based on the cell template that was specified for the column when the columns were created. Each cell will have a default value assigned based on the cell type, generally corresponding to an empty cell.

Several overloads of the Add method let you add multiple rows in a single call or pass in a row that has already been created. The DataGridView control also supports creating heterogeneous columns, meaning that the column can have cells of different types. To create heterogeneous columns, you have to construct the row first without attaching it to the grid. You then add the cells that you want to the row, and then add the row to the grid. For example, the following code adds a combo box as the first cell in the row, adds some items to the combo box, adds text boxes for the remaining four cells, and then adds the row to the grid.

private void OnAddHeterows(object sender, EventArgs e) {

m_Grid.ColumnCount = 5; // Create 5 text box columns DataGridViewRow heterow = new DataGridViewRow(); DataGridViewComboBoxCell comboCell = new DataGridViewComboBoxCell(); comboCell. Items. Add("Black");

comboCell. Items. Add("White"); comboCell.Value = "White"; heterow.Cells.Add(comboCell);

heterow.Cells.Add(new DataGridViewTextBoxCell());

m_Grid.Rows.Add(heterow); // this row has a combo in first cell

To add a row to a grid this way, the grid must already have been initialized with the default set of columns that it will hold. Additionally, the number of cells in the row that is added must match that column count. In this code sample, five text box columns are implicitly added by specifying a column count of five, then the first row is added as a heterogeneous row by constructing the cells and adding them to the row before adding the row to the grid.

You can also save yourself some code by using the grid's existing column definitions to create the default set of cells in a row using the CreateCells method, then replace just the cells that you want to be different from the default:

DataGridViewRow heterow = new DataGridViewRow();

heterow.CreateCells(m_Grid);

heterow. Cells. RemoveAt(O);

heterow.Cells.lnsert(0, new DataGridViewComboBoxCell()); m_Grid. Rows. Add (hete row);

To access the contents of the cells programmatically, you index into theRows collection on the grid to obtain a reference to the row, and then index into the Cells collection on the row to access the cell object.

Once you have a reference to the cell, you can do anything with that cell that the actual cell type supports. If you want to access specific properties or methods exposed by the cell type, you have to cast the reference to the actual cell type. To change a cell's contents, you set the Value property to an appropriate value based on the type of the cell. What constitutes an appropriate value depends on what kind of cell it is. For text box, link, button, and header cell types, the process is very similar to what was described for the Binding object in Chapter 4. Basically, the value you set on the Value property of the cell needs to be convertible to a string, and formatting will be applied in the painting process. To change the formatting ofthe output string, set the Format property of the style used forthe cell. The style is an instance of a DataGridViewCellStyle object and is exposed as another property on the cell, not surprisingly namedStyle. The cell's style contains other interesting properties that you can set (described later in the section "Formatting with Styles").

For example, if you want to set the contents of a text box cell to the current date using the short date format, you could use the following m_Grid. Rows[0j. Cells[2] .Value = Date Time.Now; m_Grid.Rows[0].Cells[2]. Style. Format = "d";

This sets the value ofthe third cell in the first row to an instance of a DateTime object, which is convertible to a string, and sets the format string to the short date predefined format string "d" (which is the short date formatMM/YYYY). When that cell gets rendered, it will convert the stored DateTime value to a string using the format string.

4 PREY

NEXT

0 0

Post a comment