Click here to Skip to main content
Click here to Skip to main content

DataGrid Formatting

By , 15 Aug 2004
Rate this:
Please Sign up or sign in to vote.

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

  1. 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.
  2. What you will do if you want to align some of the field values to center align.
  3. 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.
  4. 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.
  5. 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 in DataGridTableStyle class. Simply put, you need to bind the name of the table here.
  • And finally, add this DataGridTableStyle object to your DataGrid's TableStyle property using the method Add().

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.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

sreejith ss nair
Software Developer (Senior) Freelance
India India
He is a certified professional in both MCPD and MCTS. He is a mathematics graduate with masters in computer science.He was born and bred in India and happen to spend some time in Europe.

Comments and Discussions

 
GeneralMy vote of 5 Pinmembermanoj kumar choubey28-Nov-12 19:08 
QuestionDataGridView Pingroupss9o9o9o17-Jul-12 2:55 
Generalwind form Pinmemberhungthaibinh9-Jul-08 1:16 
GeneralTimeSpan formatting Pinmemberwick#318-Sep-06 13:28 
GeneralI want to Chang Item Color in HyperLink Colmun PinmemberAamir_o4u23-May-06 1:21 
GeneralUsing TableStyles with Designer Pinmemberpradeepnatekar3-Apr-06 23:47 
GeneralSuggestions Pinmemberbenblo23-Feb-06 13:11 
GeneralRe: Suggestions Pinmembersreejith ss nair9-Mar-06 6:29 
GeneralNever been able to format currencies (nor dates) PinmemberIhari17-Jan-06 5:26 
GeneralRe: Never been able to format currencies (nor dates) Pinmembersreejith ss nair17-Jan-06 5:36 
GeneralFound out why it wouldn't format PinmemberIhari17-Jan-06 19:30 
GeneralFormat Info PinmemberZapss22-Oct-05 22:01 
GeneralColumn headers text alignment Pinmemberasmyan13-Oct-05 17:01 
GeneralAbout digits PinmemberBahadir Cambel10-Apr-05 6:05 
Generaldatagrid formatting PinmemberAlfCStockton19-Oct-04 0:06 
GeneralRe: datagrid formatting Pinmembersreejith ss nair19-Oct-04 0:40 
GeneralRe: datagrid formatting PinmemberAlfCStockton19-Oct-04 7:33 
GeneralRe: datagrid formatting Pinmembersreejith ss nair19-Oct-04 7:39 
GeneralRe: datagrid formatting Pinmembersreejith ss nair19-Oct-04 7:46 
GeneralRe: datagrid formatting PinmemberAlfCStockton19-Oct-04 7:57 
GeneralRe: datagrid formatting Pinmembersreejith ss nair19-Oct-04 8:10 
GeneralRe: datagrid formatting PinmemberAlfCStockton21-Oct-04 18:27 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web03 | 2.8.140415.2 | Last Updated 16 Aug 2004
Article Copyright 2004 by sreejith ss nair
Everything else Copyright © CodeProject, 1999-2014
Terms of Use
Layout: fixed | fluid