Click here to Skip to main content
15,881,709 members
Articles / Programming Languages / C#
Article

DataGrid Formatting

Rate me:
Please Sign up or sign in to vote.
4.57/5 (35 votes)
15 Aug 2004CPOL5 min read 240K   3.9K   60   23
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 NameData TypeDescription
card_nonumericCard No.
card_typecharCard Type
card_idvarcharCard Identity
card_balancedecimalCard Balance Amount
card_valid_sdtimestampCard Validity Start Date
card_valid_eddateCard Validity End Date
card_valid_timetimeCard Validity Time

Image 1

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.

Image 2

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:

Image 3

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:

Image 4

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.

C#
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.

C#
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.

Image 5

(You will get full code in the zip file.)

C#
//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)


Written By
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

 
QuestionThe code NOT WORKING. IANYWHERE is NO-where. So Silly. Pin
spins311-Jul-14 0:29
spins311-Jul-14 0:29 
GeneralMy vote of 5 Pin
Manoj Kumar Choubey28-Nov-12 19:08
professionalManoj Kumar Choubey28-Nov-12 19:08 
QuestionDataGridView Pin
ss9o9o9o17-Jul-12 2:55
ss9o9o9o17-Jul-12 2:55 
Generalwind form Pin
hungthaibinh9-Jul-08 1:16
hungthaibinh9-Jul-08 1:16 
GeneralTimeSpan formatting Pin
wick#318-Sep-06 13:28
wick#318-Sep-06 13:28 
GeneralI want to Chang Item Color in HyperLink Colmun Pin
Aamir_o4u23-May-06 1:21
Aamir_o4u23-May-06 1:21 
GeneralUsing TableStyles with Designer Pin
pradeepnatekar3-Apr-06 23:47
pradeepnatekar3-Apr-06 23:47 
GeneralSuggestions Pin
benblo23-Feb-06 13:11
benblo23-Feb-06 13:11 
GeneralRe: Suggestions Pin
sreejith ss nair9-Mar-06 6:29
sreejith ss nair9-Mar-06 6:29 
GeneralNever been able to format currencies (nor dates) Pin
Ihari17-Jan-06 5:26
Ihari17-Jan-06 5:26 
GeneralRe: Never been able to format currencies (nor dates) Pin
sreejith ss nair17-Jan-06 5:36
sreejith ss nair17-Jan-06 5:36 
GeneralFound out why it wouldn't format Pin
Ihari17-Jan-06 19:30
Ihari17-Jan-06 19:30 
GeneralFormat Info Pin
Zapss22-Oct-05 22:01
Zapss22-Oct-05 22:01 
Good Article it is very use ful for me,
how to work with formatInfo property
i will try to use but it would not work,
i want to change one column value for a parituclar langauage,
on which event i have to write the code.

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/frlrfsystemwindowsformsdatagridtextboxcolumnclassformatinfotopic.asp[^]
GeneralColumn headers text alignment Pin
asmyan13-Oct-05 17:01
asmyan13-Oct-05 17:01 
GeneralAbout digits Pin
Bahadir Cambel10-Apr-05 6:05
Bahadir Cambel10-Apr-05 6:05 
Generaldatagrid formatting Pin
StrayGrey19-Oct-04 0:06
StrayGrey19-Oct-04 0:06 
GeneralRe: datagrid formatting Pin
sreejith ss nair19-Oct-04 0:40
sreejith ss nair19-Oct-04 0:40 
GeneralRe: datagrid formatting Pin
StrayGrey19-Oct-04 7:33
StrayGrey19-Oct-04 7:33 
GeneralRe: datagrid formatting Pin
sreejith ss nair19-Oct-04 7:39
sreejith ss nair19-Oct-04 7:39 
GeneralRe: datagrid formatting Pin
sreejith ss nair19-Oct-04 7:46
sreejith ss nair19-Oct-04 7:46 
GeneralRe: datagrid formatting Pin
StrayGrey19-Oct-04 7:57
StrayGrey19-Oct-04 7:57 
GeneralRe: datagrid formatting Pin
sreejith ss nair19-Oct-04 8:10
sreejith ss nair19-Oct-04 8:10 
GeneralRe: datagrid formatting Pin
StrayGrey21-Oct-04 18:27
StrayGrey21-Oct-04 18:27 

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

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