HOW TO: Use Visual C# .NET to Format a Windows Forms DataGrid That Is Bound to an Array (317550)
The information in this article applies to:
- Microsoft Visual Studio .NET (2003), Enterprise Architect Edition
- Microsoft Visual Studio .NET (2003), Enterprise Developer Edition
- Microsoft Visual Studio .NET (2003), Academic Edition
- Microsoft Visual Studio .NET (2002), Professional Edition
- Microsoft Visual Studio .NET (2002), Enterprise Architect Edition
- Microsoft Visual Studio .NET (2002), Enterprise Developer Edition
- Microsoft Visual Studio .NET (2002), Academic Edition
- Microsoft Common Language Runtime (included with the .NET Framework 1.1)
- Microsoft Common Language Runtime (included with the .NET Framework) 1.0
This article was previously published under Q317550 For a Microsoft Visual Basic .NET version of this article, see 317383.
This article refers to the following Microsoft .NET Framework Class Library namespace:
IN THIS TASKSUMMARY
You can bind Visual Studio .NET controls not only to traditional data sources such as a DataTable object, but also to other types of lists, such as an array. However, when you bind a DataGrid control to an array, the array columns appear unformatted and in seemingly random order.
This step-by-step article describes how to use the DataGridTableStyles and the DataGridColumnStyles collections to specify column order and formatting for the array columns that appear in your DataGrid control.
back to the top
Requirements
The following list outlines the recommended hardware, software, network infrastructure, and service packs that you need:
- Microsoft Windows XP Professional, Microsoft Windows 2000 Professional, Microsoft Windows 2000 Server, Microsoft Windows 2000 Advanced Server, or Microsoft Windows NT 4.0 Server
- Microsoft Visual Studio .NET
This article assumes that you are familiar with the following topics:
back to the top
Set Up the Test Project- Start Visual Studio .NET.
- On the File menu, point to New, and then click Project.
- In the New Project dialog box, click Visual C# Projects under Project Types, and then click Windows Application under Templates.
- Drag one DataGrid control and two Button controls from the toolbox to the default form, Form1.cs.
- In the Properties window, change the Text property of the first Button control to Bind. Change the Text property of the second Button control to Format.
- Switch to Code view, and then add the following code to the very top of the form's code module:
using System.ComponentModel;
back to the top
Create a Class for the Array- You can only bind a DataGrid to a one-dimensional array. To display multiple columns of information, you must create a class or a structure (user-defined type) with multiple members, and then use an array of instances of this class or structure.
- At the very bottom of Form1.cs, after the final closing bracket (}) for the default namespace created for this project, add the following code to insert a TestItem class that has a constructor and four properties:
public class TestItem
{
private int m_TestID;
private string m_TestName;
private string m_TestBool;
private double m_TestAmount;
public int TestID
{
get
{
return m_TestID;
}
}
public string TestName
{
get
{
return m_TestName;
}
}
public string TestBool
{
get
{
return m_TestBool;
}
}
public double TestAmount
{
get
{
return m_TestAmount;
}
}
public TestItem(int TestID,string TestName,string TestBool ,double TestAmount)
{
this.m_TestID = TestID;
this.m_TestName = TestName;
this.m_TestBool = TestBool;
this.m_TestAmount = TestAmount;
}
}
The four properties of this class become four columns in the bound DataGrid. - At the top of the form's class code, add the following array declaration to create an empty array of 6 (0 to 5) TestItem objects:
TestItem[] TestItems = new TestItem[6];
back to the top
Add the Binding Code- In Design view, double-click Bind to add an event handler to the button.
- Add the following code to the Button1_Click event to create the six array items:
TestItems[0] = new TestItem(1, "Joe", "true", 1000);
TestItems[1] = new TestItem(2, "Mary", "false", 2000);
TestItems[2] = new TestItem(3, "Bill", "true", 3000);
TestItems[3] = new TestItem(4, "Anne", "false", 4000);
TestItems[4] = new TestItem(5, "Harry", "true", 5000);
TestItems[5] = new TestItem(6, "Susan", "true", 6000);
- Return to Design view, and then double-click the DataGrid control to add an event handler to the grid.
- Add the following code to bind the array to the DataGrid:
dataGrid1.DataSource = TestItems;
back to the top
Add the Formatting Code- To format the array data in the bound DataGrid, you must first create a new DataGridTableStyle. In Design view, double-click Format to add an event handler to the button, and then add the following code in the Button2_Click event:
DataGridTableStyle gs = new DataGridTableStyle();
- Add the following code to map the DataGridTableStyle to the array of TestItem objects:
gs.MappingName = TestItems.GetType().Name;
The MappingName property is the crucial information in each DataGridTableStyle and DataGridColumnStyle object. MappingName maps each grid column to one of the properties of the class, and maps the grid as a whole to the array. - Add the following code to display the ID and Name columns as DataGridTextBoxColumns:
DataGridTextBoxColumn cs = new DataGridTextBoxColumn();
cs.MappingName = "TestID";
cs.HeaderText = "Test ID";
cs.Alignment = HorizontalAlignment.Center;
cs.Width = 50;
gs.GridColumnStyles.Add(cs);
cs = new DataGridTextBoxColumn();
cs.MappingName = "TestName";
cs.HeaderText = "Test Name";
cs.Alignment = HorizontalAlignment.Left;
cs.Width = 75;
gs.GridColumnStyles.Add(cs);
- Add the following code to display the true/false TestBool column as a DataGridBoolColumn, which will be displayed by using check boxes:
DataGridBoolColumn cs2 = new DataGridBoolColumn();
cs2.MappingName = "TestBool";
cs2.HeaderText = "Test Bool";
cs2.Width = 75;
cs2.TrueValue = "true";
cs2.FalseValue = "false";
gs.GridColumnStyles.Add(cs2);
- Use the PropertyDescriptor object (from the System.ComponentModel class) to display the Amount column and to format its values as currency:
CurrencyManager cm = (CurrencyManager)this.BindingContext[TestItems];
PropertyDescriptor pd = cm.GetItemProperties()["TestAmount"];
cs = new DataGridTextBoxColumn(pd, "c");
cs.MappingName = "TestAmount";
cs.HeaderText = "Test Amount";
cs.Alignment = HorizontalAlignment.Right;
cs.Width = 75;
gs.GridColumnStyles.Add(cs);
- Add the following code to add the DataGridTableStyle object to the TableStyles collection of the DataGrid:
dataGrid1.TableStyles.Add(gs);
You can also configure the TableStyles and the ColumnStyles visually by using the Visual Studio Collection Editor. If you choose this method, omit the code presented in the first 5 steps of this section, and then follow these steps:
- Click the DataGrid on the form.
- In the Properties window, click the TableStyles property, and then click the ellipsis (...).
- In the DataGridTableStyle Collection Editor dialog box, add a TableStyle, and then click OK.
- In the Properties window, click the GridColumnStyles property, and then click the ellipsis.
- In the DataGridColumnStyle Collection Editor dialog box, click Add to add a column.
- In Column Properties, enter Test ID for HeaderText and testid for MappingName.
- Repeat this step for the testname, testbool, and testamount fields. However, when you add the testbool column, select DataGridBoolColumn from the drop-down list box to the right of the Add button. (The other columns are all DataGridTextBoxColumns.)
- Click OK to dismiss all dialog boxes.
- Replace the code in step 6 of the previous set of steps with the following:
dataGrid1.TableStyles.Add(dataGridTableStyle1);
NOTE: When you bind to an array, you must make sure that the MappingName property for the DataGridTableStyle is blank in the Collection Editor and then specify MappingName in your code as follows:
dataGridTableStyle1.MappingName = TestItems.GetType().Name;
back to the top
Run the Project- Run the project.
- Click the Bind button to load the array into the DataGrid. Notice that the columns appear out of order and that the data appears unformatted.
- Click the Format button to apply the DataGridTableStyle to the DataGrid. The columns now appear in the expected order and the data is formatted using the appropriate styles.
back to the top
Troubleshooting- If you do use the DataGridTableStyle, you must define a DataGridColumnStyle for every column that appears in the grid. You cannot define styles for some columns and display others by using the default settings.
- When you set the Alignment property in the DataGridColumnStyle, you affect the HeaderText property, as well as the data in the column.
- The DataGrid.TableStyles Property documentation states:
CAUTION: Always create DataGridColumnStyle objects and add them to the GridColumnStylesCollection before adding DataGridTableStyle objects to the GridTableStylesCollection. When you add an empty DataGridTableStyle to the collection, DataGridColumnStyle objects are automatically generated for you. Therefore, an exception will be thrown if you try to add new DataGridColumnStyle objects with duplicate MappingName values to the GridColumnStylesCollection.
back to the top
REFERENCES
For more information about the DataGrid control, search for "DataGrid Control" and "DataGrid Class" on MSDN.
back to the top
Modification Type: | Minor | Last Reviewed: | 5/23/2005 |
---|
Keywords: | kbCompModel kbDataBinding kbHOWTOmaster KB317550 kbAudDeveloper |
---|
|