DataGrid Formatting






4.57/5 (29 votes)
Applying DataGridTableStyle class In WinForm DataGrid control.
Intension behind
From .NET beta to .NET Ver 1.1, Microsoft doesn't give a too very user friendly feature for formatting DataGrid
and its data contents. But in the next release, they are going to introduce a new grid control called GridView
control.
I've seen lot of questions about DataGrid
formatting in major discussion boards that I used to visit, like Microsoft discussion boards and Code Project discussion board. It is a time consuming task to reply for all posts which more or less point to the same doubts, with small differences. So this is the actual inspiration to write this article. We can keep this as a reference for somewhat all phases of formatting which is applicable for the DataGrid
control.
Before starting, I am gladly inviting your ideas and suggestions based on DataGrid
formatting which is not in this article. This will help me to update the article content on later stages, and will help the other members in this discussion board.
"If you feel it is good then don't forget to vote and put your suggestions."
Introduction
Before getting into the real world, I need to explain a little about this article. This article won't help you if you are looking for a 3D rendering or something else which you can directly apply in your project. This will help you in different Windows projects that you are working on or going to.
Here, I am using a table called Card
which is designed by the help of Sybase database. You can use your own database to create the Card
table. My intension is to show how we will use different data types and their formatting in DataGrid
. That's it.
This is the structure of the table.
Field Name | Data Type | Description |
card_no |
numeric | Card No. |
card_type |
char | Card Type |
card_id |
varchar | Card Identity |
card_balance |
decimal | Card Balance Amount |
card_valid_sd |
timestamp | Card Validity Start Date |
card_valid_ed |
date | Card Validity End Date |
card_valid_time |
time | Card Validity Time |
Here, you may raise one doubt, that what is their in timestamp, date, and time, data types.
See the picture which is given below and notice the difference. Picture will serve you than words.
So, I have data of different types in my table. Next, I need to show it in different ways. (Refer code attached for data binding techniques.)
By default, if you are not applying any style to the DataGrid
, it will show the grid and contents like this:
Tell me what you will do in these scenario
- Here the alignment of all records is left. But it is not a good practice to align numeric records in left. It must be always right.
- What you will do if you want to align some of the field values to center align.
- Now, in the existing scenario, we can easily change the color of the selected row. But it won't change the selected cell color (up to my level best). Suppose if you want to show the selected cell in a different color scheme.
- If you see the caption header of the above grid (e.g., card_id, card_type etc.) it is same as what we defined in the table. My question is "Is this caption making any sense for the user?". Based on my experience, "No". Why because, we need to supply meaningful captions for this header like Card No., Card Type etc. Then only the user will feel this is user friendly.
- If you check the above table, there is no style difference between field captions and the content. In the current scenario, we can change the
DataGrid
caption style and font. Suppose if you want to change the caption style and font style of your field name. What will you do?
The above mentions are basic standards to show data. And it may vary based on your taste. See this:
This picture gives you an ultimate solution for the above five issues.
I will explain how it is changed from previous state to the above new state. If you bind a DataSet
's table with a DataGrid
, it will show the data in a grid like form. If you check that little bit more, you can view that DataGrid
style of presentation is somewhat a table like structure. In .NET, we have a class file called DataGridTableStyle
which represents the drawn grid only. The DataGridTableStyle
strictly represents the grid as it is painted in the control. So through this class' (DataGridTableStyle
) objects, you can control the appearance of the grid for each data table which is there in your DataSet
. (You will get the full set of source code in the attached zip file.)
Here our aim is:
- Create a
DataGridTableStyle
class instance. - Apply our required format styles.
- Specify to which table we need to apply the style using a property called
MappingName
inDataGridTableStyle
class. Simply put, you need to bind the name of the table here. - And finally, add this
DataGridTableStyle
object to yourDataGrid
'sTableStyle
property using the methodAdd()
.
Here is a little from our actual code block. And this is only simple formatting. Like this, you can do a lot. So catch the concept and apply as per your requirement.
private void radioButton1_Click(object sender, System.EventArgs e)
{
/*For fast capturing , i put this code block
little bit simple. So it look like lengthy.
This will create an instance of DataGridTableStyle class*/
DcStyle=new DataGridTableStyle();
/*this will help you to assign the forecolor,backcolor and
the font style of your feild header.*/
DcStyle.HeaderForeColor=Color.WhiteSmoke;
DcStyle.HeaderBackColor=Color.Green;
DcStyle.HeaderFont= new Font("Verdana",10,FontStyle.Bold);
/*this foreach loop will iterate through the entire
collection of your datatable's columns.*/
foreach(DataColumn dc in Dset.Tables["Card"].Columns)
{
/* like above this will help you to define formatting to
your feild values. which is bounding to DataGridTextBoxColumn
using the Mappingname and HeaderText.*/
DataGridTextBoxColumn textColumn=new DataGridTextBoxColumn();
textColumn.MappingName= dc.ColumnName;
textColumn.HeaderText = dc.Caption;
if(dc.ColumnName.ToString()=="card_no")
{
/*this will change the caption of your
datagrid Column's default value*/
/*to the below mwntioned value.*/
textColumn.HeaderText="Card No";
/*this will help you to align the content for you.*/
textColumn.Alignment=System.Windows.Forms.HorizontalAlignment.Right;
/*this will help you set the back color of selected cell*/
textColumn.TextBox.BackColor=Color.Red;
/*this will help you to adjest the width of Column's*/
textColumn.Width=75;
}
//continued ........................
/*this will help you from updating data content.*/
textColumn.ReadOnly = true;
/*finally we will add our formated column
to DataGridTableStyle instance*/
DcStyle.GridColumnStyles.Add(textColumn);
}
/*Here you need to map the name of the table
to mappingName property of datadridtablestyle instance */
DcStyle.MappingName=Dset.Tables["Card"].TableName;
/*then add your datadridtablestyle instance to
datagrid TableStyles collection using Add() method.*/
dataGrid1.TableStyles.Add(DcStyle);
/*our normal databinding*/
dataGrid1.DataSource=Dset.Tables["Card"].DefaultView;
}
You can add your different styles to your DataGrid
's TableStyle
collection. And likewise, you can remove or clear the DataGrid
's table style. This will help you to retain default style to your DataGrid
. This code is somewhat self explanatory. So I am not going to explain it in detail.
privatevoid radioButton2_CheckedChanged_1(object sender, System.EventArgs e)
{
//this block will help you to simply clear the existing
//style of datagrid and will help you to keep
//its default style.
DataGridTableStyle DefaultStyle =new DataGridTableStyle();
dataGrid1.TableStyles.Clear ();
DefaultStyle.HeaderBackColor = Color.Red;
DefaultStyle.AlternatingBackColor = Color.LightGray;
dataGrid1.TableStyles.Add(DefaultStyle);
}
My last discussion is based on data formatting. Suppose if we need to change the format of the data which is coming from the database table. You can fix this issue here.
(You will get full code in the zip file.)
//this will help you to show datarow in alternate color
DcStyle1.AlternatingBackColor=Color.Gold;
//this will help you to show data in currency form
textColumn.Format=System.String.Format("c",textColumn.TextBox);
//this will format and show the date in yyyy-MMM-dd format
textColumn.Format=System.String.Format("yyyy-MMM-dd",textColumn.TextBox);
//this will format and show the date in dd-MMM-yyyy format
textColumn.Format=System.String.Format("dd-MMM-yyyy",textColumn.TextBox);
//this will help you to show the time information excluding the date.
textColumn.Format=System.String.Format("hh:mm:ss",textColumn.TextBox);
Download and execute the source. Please come out with your idea.