Click here to Skip to main content
15,886,873 members
Articles / Web Development / HTML
Article

Add some Style to your DataGrids

Rate me:
Please Sign up or sign in to vote.
4.60/5 (31 votes)
5 Jul 2004CPOL4 min read 255.3K   4.4K   109   22
Use CSS style sheets to apply re-usable styles across all of your grids.

Sample Image - cssgrid.gif

Introduction

It can be frustrating trying to apply CSS styles to .NET data grids - attempting to blindly apply styles does not usually work as expected, because of the way that the DataGrid is rendered to the browser. This article introduces some simple techniques to help get you started.

But first, why use styles at all? You could use the autoformat feature in Visual Studio .NET, but what happens when the "UI expert consultant" that your boss hired insists on extra spacing between the rows? You'll have to go to every grid on your project, and edit it. Using styles lets you control the appearance of all of your grids from a single place.

DataGrid styles

The DataGrid exposes several places where it is easy to assign a style, using the CssStyle property. They are:

  • <asp:datagrid> - this corresponds to an HTML table element. You can use this style to set some global properties for the grid, such as the background color, or the border.
  • <HeaderStyle> - this controls the header row, but the style is applied to the HTML <tr> element. Interestingly, ASP.NET renders the table header cells as <td>, not <th>. Naughty Microsoft, abusing web standards again!
  • <ItemStyle> - this controls formatting for each item. The style is applied to the HTML <tr> element for the odd rows.
  • <AlternatingItemStyle> - controls formatting for alternate (even) items. Also applied to the <tr> element.
  • <SelectedItemStyle> - applied to a highlighted row.
  • <FooterStyle> - applied to a footer row, e.g., a summary row.
  • <PagerStyle> - applied to a pager row.

I will not use all of these styles in my examples, because they are not necessary to show how to do it.

<asp:datagrid>

In my example, I have set up the DataGrid like this:

ASP.NET
<asp:datagrid id="DataGrid1" runat="server" CssClass="Grid">
    <HeaderStyle CssClass="GridHeader"></HeaderStyle>
    <ItemStyle CssClass="GridItem"></ItemStyle>
    <AlternatingItemStyle CssClass="GridAltItem"></AlternatingItemStyle>
</asp:datagrid>

I applied a CssStyle of Grid to the asp:datagrid element, and various other styles to the other grid style elements. In my external style sheet, I used the following line, which creates a solid tan border, 1 pixel thick.

HTML
.Grid { border: solid 1px Tan; }

Applying a style class to the grid as a whole has other benefits as well - we can use that class to refer to sub-elements of the grid, like this:

HTML
.Grid td
{
    border: solid 3px #FFFFFF;
    margin: 3px 3px 3px 3px;
    font-family: Arial;
    padding: 5px 5px 5px 5px;
    text-align: center;
}

The style above applies to all cells within the grid, since they are all <td> elements. It makes all the text Arial and centered, creates thick white gridlines, and inserts some padding and spacing between the cells.

<HeaderStyle>

Next, we move on to formatting the header row. This is fairly simple, using the GridHeader style that was applied to the <HeaderStyle> element.

HTML
.GridHeader
{
    font-weight: bold;
    background-color: Tan;
}

This works OK, until you create a sorted grid. Sorted grids have hyperlink tags for the header row. These hyperlinks do not take on the styles assigned so far. We can take care of that though:

HTML
.GridHeader a
{
    text-decoration: none;
    color: LightGoldenrodYellow;
    padding: 0px 15px 0px 15px;
}

The above takes care of the color and style of the hyperlink. The padding is not necessary, but I used it to illustrate some more advanced CSS, which is implemented in the following block:

HTML
.GridHeader a:hover
{
    text-decoration: underline;
    background: Tan url(images/spin.gif) no-repeat 0 100%;
}

The hover keyword is used to represent what happens when the mouse is moved over the link. In my case, I am underlining the hyperlink, and causing a small image to appear next to it. (This is why I created the 15px padding earlier; so that the image would have a place to go). The image is a spin button, which will hopefully indicate to the user what clicking the header will do.

<ItemStyle>, <AlternatingItemStyle>

Next, we want to set some attributes for the grid rows. In my case, I've decided to make the row font a little smaller, so that I can fit more data in my row.

HTML
.GridItem, .GridAltItem
{
    font-size: smaller;
}

Notice how I have applied the style to both the normal, and the alternating rows. Next, we apply styles to differentiate the alternating rows:

HTML
.GridItem
{
    background-color: LightGoldenrodYellow;
}

.GridAltItem
{
    background-color: PaleGoldenrod;
}

And that takes care of all of the basics.

Final Notes

The styles used here have been tested in IE6 and Mozilla FireFox 0.91. They will gracefully degrade on browsers that do not support some of the more advanced features, such as the hovering spin button.

The downloadable code includes multiple stylesheets. On FireFox, you can switch styles using the small icon on the lower left. In IE, you will have to edit the source to view the other styles.

References

License

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


Written By
Web Developer
United States United States
Steve is a software developer working in Minneapolis, MN.

Comments and Discussions

 
Questionthank you for sharing, its work Pin
sug1anto7-Aug-13 16:05
sug1anto7-Aug-13 16:05 
QuestionNeed Help UNICODE Pin
Nazim Iqbal5-Oct-12 13:37
Nazim Iqbal5-Oct-12 13:37 
XML
Hi


I need your help in,
I am working on a project, MYSQL and PHP based, with WAMP SERVER
I have a field storytext, (data collected in URDU) detail are:

<b>Field               Type         Collation                    Null        Default
storytext          text           utf8_unicode_ci            Yes        NULL</b>

Retrieving URDU Data from MY SQL 5.5.8 running on wamp server with PHP is OK,

And the soft ware is only for Internal use not web base!
------------------------------------------------------------------------------------------
<b>HERE IS THE PROBLEM:</b>

One section of it is designed on Visual Studio.NET 2010 in which

I have a datagrid, on clicking any row I got the TEXT in details on text box,

which show <b>URDU TEXT</b>, from data base here is the problem with <b>TEXT BOX and DATAGRID.</b>

I got this..........

<b>DESP. ITEM

پروگرام رانا مب
شر ايٹ پرائم ٹائم ميں
گ٠تگو کرتے Û ÙˆØ¦Û’ وزير٠اعظم Ú©Û’
وکيل Ú†ÙˆÛ Ø¯Ø±ÙŠ اعتزاز احسن
کا Ú©Û Ù†Ø§ تھا Ú©Û ØµØ¯Ø± Ú©Û’ Ø¹Û Ø¯Û’
Ú©Ùˆ استشني حاصل Û Û’
وزير٠اعظم Ø</b>
-------------------------------------------------------------------------------------------------------
I also use in visual studio

<b>cnString = "datasource=localhost;username=root;password=;database=spidernews;charset=utf8;"</b>

How can I solve this problem,
can you help me out !
<b>URDU NOT SHOWING,  </b>

<pre lang="vb">Here is Whole CODE of Visual Studio, I am using:
------------------------------------------------------------------------------------------------------------------------</pre>


<pre lang="text">
Imports MySql.Data.MySqlClient

Public Class Form1

    Dim conn As Common.DbConnection
    Dim da As Common.DbDataAdapter
    Dim ds As DataSet = New DataSet
    Dim cnString As String
    Dim sqlQRY As String
    'Dim dt As DataTable
    'Dim strBuilder As Char




    '''' SCROLLONG TEXT START
    Dim scrollingText As String = "Spider NEWS "
    Dim txtStr(scrollingText.Length - 1) As String
    Dim txtPos As Integer = -1

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

        'strBuilder.ToString ("tblnews" & char(34))


        cnString = "datasource=localhost;username=root;password=;database=spidernews;charset=utf8;"

        sqlQRY = "SET NAMES UTF8; SET CHARACTER SET UTF8;Select slugid,slug,storytext,storyduration,segmentdescription,prioritydescription,mosstatus from tblnews"
        'sqlQRY = "SET NAMES UTF8; SET CHARACTER SET latin1;Select slugid,slug,storytext,storyduration,segmentdescription,prioritydescription,mosstatus from tblnews"
        conn = New MySqlConnection(cnString)

        Try
            conn.Open()
            da = New MySqlDataAdapter(sqlQRY, conn)
            Dim cb As MySqlCommandBuilder = New MySqlCommandBuilder(da)

            da.Fill(ds, "tblnews")

            DataGridView1.DataSource = ds
            DataGridView1.DataMember = "tblnews"
            '''''


        Catch ex As Common.DbException
            MsgBox(ex.ToString)
        Finally
            conn.Close()
        End Try

        '''' SCROLLONG TEXT START
        For idx As Integer = 0 To UBound(txtStr)
            Dim workedString As String = ""
            workedString = scrollingText.Substring(idx) & " " & scrollingText.Substring(0, idx)
            txtStr(idx) = workedString
        Next
        Timer1.Interval = 5000
        Timer1.Enabled = True
        Timer1.Start()
        '''' SCROLLONG TEXT END
        Label2.Text = System.DateTime.Now

    End Sub

    Private Sub Save_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)

        da.Update(ds, "" + TextBox1.Text + "")
        MsgBox("Data sent", MsgBoxStyle.OkOnly, "Sucess")

    End Sub

    Private Sub DataGridView1_CellContentClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DataGridView1.CellContentClick

        Dim i, j As Integer
        i = DataGridView1.CurrentRow.Index
        RichTextBox1.Text = DataGridView1.Item(2, i).Value

    End Sub

    Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick

        Dim i, j As Integer
        i = DataGridView1.CurrentRow.Index

        '''' SCROLLONG TEXT START
        txtPos += 1
        Dim timerStr As String
        timerStr = txtStr(txtPos)
        RichTextBox1.Text = DataGridView1.Item(2, i).Value

        Label1.Text = timerStr
        If txtPos = UBound(txtStr) Then txtPos = -1
        '''' SCROLLONG TEXT START

    End Sub

End Class



</pre>

n
QuestionTHANK YOU Pin
Member 835054427-Oct-11 1:39
Member 835054427-Oct-11 1:39 
Generalpager arrow Pin
vsnewcomer8-Apr-10 1:06
vsnewcomer8-Apr-10 1:06 
QuestionProblem using this with "DatagridFixedHeader" Pin
smcirish22-Apr-08 8:04
smcirish22-Apr-08 8:04 
GeneralRe: Problem using this with "DatagridFixedHeader" Pin
Steven Campbell22-Apr-08 15:18
Steven Campbell22-Apr-08 15:18 
GeneralThank you Pin
jrl237@yahoo.com12-Jun-07 6:53
jrl237@yahoo.com12-Jun-07 6:53 
GeneralControlling Header borders Pin
iburge5-Apr-05 6:23
iburge5-Apr-05 6:23 
GeneralPaging specific Properties Pin
Member 194724231-Mar-05 16:51
Member 194724231-Mar-05 16:51 
GeneralRe: Paging specific Properties Pin
Steven Campbell1-Apr-05 2:14
Steven Campbell1-Apr-05 2:14 
GeneralMistake in applying my stylesheet Pin
MuggaBatscher23-Mar-05 21:26
MuggaBatscher23-Mar-05 21:26 
GeneralRe: Mistake in applying my stylesheet Pin
Steven Campbell24-Mar-05 2:36
Steven Campbell24-Mar-05 2:36 
GeneralRe: Mistake in applying my stylesheet Pin
MuggaBatscher24-Mar-05 2:59
MuggaBatscher24-Mar-05 2:59 
GeneralRe: Mistake in applying my stylesheet Pin
Steven Campbell24-Mar-05 16:51
Steven Campbell24-Mar-05 16:51 
Questionam I missing something? Pin
Anonymous14-Dec-04 5:28
Anonymous14-Dec-04 5:28 
AnswerRe: am I missing something? Pin
Anonymous8-Mar-05 13:50
Anonymous8-Mar-05 13:50 
AnswerRe: am I missing something? Pin
Anonymous2-Aug-05 20:28
Anonymous2-Aug-05 20:28 
AnswerRe: am I missing something? Pin
Anonymous28-Aug-05 17:55
Anonymous28-Aug-05 17:55 
AnswerRe: am I missing something? Pin
graham_m29-Jul-10 23:19
graham_m29-Jul-10 23:19 
GeneralSome best practices for stylesheets Pin
Dia-menz14-Jul-04 12:54
Dia-menz14-Jul-04 12:54 
GeneralRe: Some best practices for stylesheets Pin
aaava14-Aug-06 12:03
aaava14-Aug-06 12:03 
GeneralRe: Some best practices for stylesheets Pin
a.k.a.2-Jan-07 17:19
a.k.a.2-Jan-07 17:19 

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.