Monday, May 14, 2007

Add columns programmatically to a GridView and style the rows

A friend of mine asked me how to programmatically add columns to a GridView and I found this great article which I hope will help some of you too :

http://www.gridviewguy.com/ArticleDetails.aspx?articleID=29

He also asked me how to style the Grids the best possible way and to modify the style of some control in it, maybe just one cell.

As far as the general style is concerned I advise you to use a .skin file in the "Themes" folder of your ASP.NET 2.0 app. In this file the following declaration will map the GridView items to CSS classes :



<asp:GridView SkinID="" runat="server" CellPadding="4" GridLines="Both" CssClass="GridView" Width="100%" BorderColor="#ECECEC" BorderStyle="Solid">
<HeaderStyle CssClass="GridHeader" />
<FooterStyle CssClass="GridFooter" />
<SelectedRowStyle CssClass="GridSelectedRow" />
<AlternatingRowStyle CssClass="GridAlternatingRow" />
<EditRowStyle CssClass="GridEditRow" />
<RowStyle CssClass="GridRow" />
<PagerStyle CssClass="GridPager" />
<EmptyDataRowStyle CssClass="GridEmptyRow" />
</asp:GridView>


In a css file, you can then create the relevant classes like GridHeader, etc.

If you need to modify a row or some element of it when the Grid is being "written" you should do it in the RowDataBound event as follows:



Protected Sub myGridView_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles myGridView.RowDataBound()
If e.Row.RowType = DataControlRowType.DataRow Then
Dim objButton As Button
objButton = CType(e.Row.FindControl("cmdButtonInTheRow"), Button)
If IsDBNull(e.Row.DataItem("MyDataFieldValue")) Then
objButton.Enabled = False
ElseIf e.Row.DataItem("MyDataFieldValue") = "SOME_VALUE" Then
objButton.BackColor = System.Drawing.Color.FromName("White")
Else
objButton.BackColor = System.Drawing.Color.FromName("Green")
e.Row.BackColor = System.Drawing.Color.FromName("Red")
e.Row.Cells(3).BackColor = System.Drawing.Color.FromName("Yellow")
e.Row.Cells(4).ForeColor = System.Drawing.Color.FromName("Pink")
End
End If
End If
End Sub


Hope this helps!

Cheers,

No comments: