Search This Blog

Thursday, January 6, 2011

GridView Tips and Tricks using ASP.NET

The GridView control is quiet a handy control and is the most commonly used control when building an ASP.NET site. The more you work with it, the more you realize how powerful it can be while presenting data.



For this article, we would be using the following template to populate the GridView.
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>GridView Tips and Tricks Part 2title>
head>
<body>
    <form id="form1" runat="server">
    <div>
    <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="CategoryID"
            DataSourceID="SqlDataSource1" ShowFooter="true" AllowPaging="True" AllowSorting="True"
            PageSize="5" OnRowDataBound="GridView1_RowDataBound">
            <Columns>                       
                <asp:TemplateField HeaderText="CategoryID" InsertVisible="False" SortExpression="CategoryID">
                    <ItemTemplate>
                        <asp:Label ID="lblCategoryID" runat="server" Text='<%# Bind("CategoryID") %>'>asp:Label>
                    ItemTemplate>                  
                asp:TemplateField>
                <asp:TemplateField HeaderText="CategoryName" SortExpression="CategoryName">
                    <EditItemTemplate>
                        <asp:TextBox ID="txtCategoryName" runat="server" Text='<%# Bind("CategoryName") %>'>asp:TextBox>
                    EditItemTemplate>
                    <ItemTemplate>
                        <asp:Label ID="lblCategoryName" runat="server" Text='<%# Bind("CategoryName") %>'>asp:Label>
                    ItemTemplate>
                asp:TemplateField>
                <asp:TemplateField HeaderText="Description" SortExpression="Description">
                    <EditItemTemplate>
                        <asp:TextBox ID="txtDesc" runat="server" Text='<%# Bind("Description") %>'>asp:TextBox>
                    EditItemTemplate>
                    <ItemTemplate>
                        <asp:Label ID="lblDesc" runat="server" Text='<%# Bind("Description") %>'>asp:Label>
                    ItemTemplate>                               
                asp:TemplateField>               
            Columns>
        asp:GridView>
        <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="Data Source=SUPROTIM;Initial Catalog=Northwind;Integrated Security=True"
            ProviderName="System.Data.SqlClient" SelectCommand="SELECT [CategoryID], [CategoryName], [Description] FROM [Categories]"
            UpdateCommand="UPDATE [Categories] SET [CategoryName] = @CategoryName, [Description] = @Description WHERE [CategoryID] = @CategoryID"/>
    div>
    form>
body>
html>
The web.config holding the connection will look similar to the following:
<configuration>
      <appSettings/>
      <connectionStrings>
            <add name="NorthwindConnectionString" connectionString="Data Source =(local);Integrated Security = SSPI; Initial Catalog=Northwind;"/>
      connectionStrings>
...
configuration>
Tip 1: Enable Disable Controls inside a GridView
There are at times when you have to disable controls on some rows, when a certain condition is satisfied. In this snippet, we will see how to disable editing for rows that have the CategoryName as ‘Confections’. Use the following code:
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            if (e.Row.DataItem != null)
            {
                Label lblControl = (Label)e.Row.Cells[2].FindControl("lblCategoryName");
                if(lblControl.Text == "Confections")
                {
                    e.Row.Cells[0].Enabled = false;
                }
            }
        }
    }

Tip 2: Adding Arrows for Sorting Columns in a GridView
When you are sorting the columns in a GridView, it would be a nice to have feature, to display arrows which depict either an ascending or descending sort as shown below. Create a folder called ‘images’ and add two small images called up.gif and down.gif:
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
    if (e.Row.RowType == DataControlRowType.Header)
    {
     foreach (TableCell cell in e.Row.Cells)
     {
      if (cell.HasControls())
      {
        LinkButton btnSort = (LinkButton)cell.Controls[0];
        Image image = new Image();
        if (btnSort.Text == GridView1.SortExpression)
        {
        if (GridView1.SortDirection == SortDirection.Ascending)
        {
        image.ImageUrl = "images/up.gif";                           
        }
        else
        {
        image.ImageUrl = "images/down.gif";    
        }
      }
     cell.Controls.Add(image);
    }              
}
Tip 3: How to Add a Row Number to the Gridview
There are a couple of ways to do this. However I will share a very handy tip that was shared by XIII in the asp.net forums.
Just add the following tags to your section of your GridView
    
        <%# Container.DataItemIndex + 1 %>
    


Tip 4: How to programmatically hide a column in the GridView
There are two conditions to be checked in the Page_Load to hide a columns in the GridView, let us say the 3rd column:
If ‘AutoGenerateColumns’ = True on the GridView
GridView1.HeaderRow.Cells[2].Visible = false;
        foreach (GridViewRow gvr in GridView1.Rows)
        {
            gvr.Cells[2].Visible = false;
        }
If ‘AutoGenerateColumns’ = False on the GridView
GridView1.Columns[2].Visible = false;

Tip 5: Displaying Empty Data in a GridView
When there are no results returned from the GridView control’s data source, the short and simple way of displaying a message to the user, is to use the GridView’s EmptyDataText property.  
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="CategoryID" DataSourceID="SqlDataSource1" EmptyDataText="No data
available" ShowFooter="true" AllowPaging="True" AllowSorting="True"
PageSize="5" OnRowDataBound="GridView1_RowDataBound">
Tip 6: Displaying an Image in case of Empty Data in a GridView
As an alternative to using the EmptyDataText property, if you need to display an image or any HTML/ASP.NET control, you can use the EmptyDataTemplate. In this snippet below, we are using the image control in the to display an image.
    <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="CategoryID" DataSourceID="SqlDataSource1" ShowFooter="true"
AllowPaging="True" AllowSorting="True" PageSize="5" OnRowDataBound="GridView1_RowDataBound">
   <EmptyDataTemplate>
   <asp:Image id="imgNoData" ImageUrl="~/images/NoDataFound.jpg"
   AlternateText="No data found" runat="server"/>  
EmptyDataTemplate>

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.