16 January 2011

GridView Tips and Tricks using ASP.NET 2.0

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. In this article, we will explore some of the most frequently asked questions about the GridView control. The article discusses ten tips and tricks that you can use while using the GridView control.


Tip 1: Add, Update, Delete Records in a Gridview using SqlDataSource
By default, the GridView control doesn’t have support for inserting new records. However you can use the built-in edit or delete functionality of the GridView control. Let us explore how to insert new records and Update and Delete existing records in Gridview. Just copy and paste the code in your project. We will be using the ‘Categories’ table in the ‘Northwind’ database.
GridView.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="GridView.aspx.cs" Inherits="GridView" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Grid View Add Update Delete</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        &nbsp;&nbsp;&nbsp;&nbsp;
        <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="CategoryID"
            DataSourceID="SqlDataSource1" ShowFooter="true" AllowPaging="True" AllowSorting="True" OnRowCommand="GridView1_RowCommand">
            <Columns>
           
                <asp:CommandField ShowDeleteButton="True" ShowEditButton="True"/>               
                <asp:TemplateField HeaderText="CategoryID" InsertVisible="False" SortExpression="CategoryID">
                    <EditItemTemplate>
                        <asp:Label ID="Label1" runat="server" Text='<%# Eval("CategoryID") %>'></asp:Label>
                    </EditItemTemplate>
                    <ItemTemplate>
                        <asp:Label ID="Label1" runat="server" Text='<%# Bind("CategoryID") %>'></asp:Label>
                    </ItemTemplate>                  
                </asp:TemplateField>
                <asp:TemplateField HeaderText="CategoryName" SortExpression="CategoryName">
                    <EditItemTemplate>
                        <asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("CategoryName") %>'></asp:TextBox>
                    </EditItemTemplate>
                    <ItemTemplate>
                        <asp:Label ID="Label2" runat="server" Text='<%# Bind("CategoryName") %>'></asp:Label>
                    </ItemTemplate>
                    <FooterTemplate>
                        <asp:TextBox ID="CategoryNameTextBox" Runat="server"></asp:TextBox>
                        </FooterTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Description" SortExpression="Description">
                    <EditItemTemplate>
                        <asp:TextBox ID="TextBox2" runat="server" Text='<%# Bind("Description") %>'></asp:TextBox>
                    </EditItemTemplate>
                    <ItemTemplate>
                        <asp:Label ID="Label3" runat="server" Text='<%# Bind("Description") %>'></asp:Label>
                    </ItemTemplate>
                    <FooterTemplate>
                        <asp:TextBox ID="DescriptionTextBox" Runat="server"></asp:TextBox>
                    </FooterTemplate>                 
                </asp:TemplateField>
                <asp:templatefield>                  
                        <footertemplate>
                              <asp:linkbutton id="btnNew" runat="server" commandname="New" text="New" />
                        </footertemplate>
                  </asp:templatefield>
               
            </Columns>
        </asp:GridView>
        <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="Data Source=SUPROTIM;Initial Catalog=Northwind;Integrated Security=True"
            DeleteCommand="DELETE FROM [Categories] WHERE [CategoryID] = @CategoryID" InsertCommand="INSERT INTO [Categories] ([CategoryName], [Description]) VALUES (@CategoryName, @Description)"
            ProviderName="System.Data.SqlClient" SelectCommand="SELECT [CategoryID], [CategoryName], [Description] FROM [Categories]"
            UpdateCommand="UPDATE [Categories] SET [CategoryName] = @CategoryName, [Description] = @Description WHERE [CategoryID] = @CategoryID">
            <DeleteParameters>
                <asp:Parameter Name="CategoryID" Type="Int32" />
            </DeleteParameters>
            <UpdateParameters>
                <asp:Parameter Name="CategoryName" Type="String" />
                <asp:Parameter Name="Description" Type="String" />
                <asp:Parameter Name="CategoryID" Type="Int32" />
            </UpdateParameters>
            <InsertParameters>
                <asp:Parameter Name="CategoryName" Type="String" />
                <asp:Parameter Name="Description" Type="String" />
            </InsertParameters>
        </asp:SqlDataSource>
   
    </div>
    </form>
</body>
</html>
GridView.aspx.cs
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        SqlConnection conn = new SqlConnection(
                    ConfigurationManager.ConnectionStrings["NorthwindConnectionString"].ConnectionString);
        try
        {
            if (e.CommandName.Equals("New"))
            {
                LinkButton btnNew = e.CommandSource as LinkButton;
                GridViewRow row = btnNew.NamingContainer as GridViewRow;
                if (row == null)
                {
                    return;
                }
                TextBox txtCatName = row.FindControl("CategoryNameTextBox") as TextBox;
                TextBox txtDescription = row.FindControl("DescriptionTextBox") as TextBox;               
                SqlCommand cmd = new SqlCommand(
                    "INSERT INTO [Categories] ([CategoryName], [Description]) VALUES (@CategoryName, @Description)",
                    conn);
                cmd.Parameters.AddWithValue("CategoryName", txtCatName.Text);
                cmd.Parameters.AddWithValue("Description",txtDescription.Text);
                conn.Open();
                if (cmd.ExecuteNonQuery() == 1)
                {
                    GridView1.DataBind();
                }
            }
        }
        catch (Exception ex)
        {
        }
        finally
        {
            conn.Close();
        }
    }
Web.config
<connectionStrings>
            <addname="NorthwindConnectionString"connectionString="Data Source =.;Integrated Security = SSPI; Initial Catalog=Northwind;"/>
           
</connectionStrings>


Tip 2: Paging and Sorting a GridView without Refreshing a Page
If you have created a GridView and have bound it to a data source control, you can avoid postback during sorting and paging by setting  ‘EnableSortingAndPagingCallbacks’ property of the GridView to True.
Just remember that when you set the 'EnableSortingAndPagingCallbacks' property to true, you cannot use Template Fields in the GridView.
Tip 3: Pop-up a Confirmation box before Deleting a row in GridView
Add a template field and drop a button in it, using which the user will delete the record. In the OnClientClick event, call the confirm() function as mentioned below:
<asp:TemplateField>
      <ItemTemplate>
        <asp:Button ID="btnDel" runat="server" Text="Delete"
            CommandName="Delete" OnClientClick="return confirm('Are you sure you want to delete the record?');" />
      </ItemTemplate>
</asp:TemplateField>
Tip 4: Display details of the Row selected in the GridView
Assuming you have a button called ‘Select’ in your GridView with CommandName ‘Select’, to find out the row clicked and display the row’s details, use this code:
C#
private void GridView1_RowCommand(Object sender,
GridViewCommandEventArgs e)
    {
        if (e.CommandName == "Select")
        {
            int idx = Convert.ToInt32(e.CommandArgument);
            GridViewRow selrow = GridView1.Rows[idx];
            string fstCell  = selrow.Cells[0].Text;
string scndCell = selrow.Cells[1].Text;
// and so on
// Thanks to Mark Rae (MVP) for pointing the typo. Earlier it was Cells[1] and Cells [2]
        }
    }


Tip 5: Retrieve Details of the Row being Modified in GridView
C#
void GridView1_RowUpdated(Object sender, GridViewUpdatedEventArgs e)
    {
        // Retrieve the row being edited.
        int index = GridView1.EditIndex;
        GridViewRow row = GridView1.Rows[index];
        // Retrieve the value of the first cell
        lblMsg.Text = "Updated record " + row.Cells[1].Text;
    }
Tip 6: Retrieve Details of the Row being Deleted in GridView
The ID of the row being deleted must be in the GridView.DataKeyNames collection.
C#
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        int ID = (int)GridView1.DataKeys[e.RowIndex].Value;
        // Query the database and get the values based on the ID
    }
 

Tip 7: Cancelling Update and Delete in a GridView
RowUpdating - Occurs when a row's Update button is clicked, but before the GridView control updates the row.
RowDeleting – Occurs when a row's Delete button is clicked, but before the GridView control deletes the row.
C#
protected void gvDetail_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
        e.Cancel = true;
    }
void GridView1_RowDeleting(Object sender, GridViewDeleteEventArgs e)
    {
        // Check for a condition and cancel the delete
        // There should be atleast one row left in the GridView
        if (GridView1.Rows.Count <= 1)
        {
            e.Cancel = true;
        }
    }
Tip 8: Paging and Sorting in GridView without using Datasource control
C#
<asp:GridView ID="gridView" OnPageIndexChanging="gridView_PageIndexChanging" 
OnSorting="gridView_Sorting" runat="server" />
private string ConvertSortDirectionToSql(SortDirection sortDireciton)
{
   string newSortDirection = String.Empty;
   switch (sortDirection)
   {
      case SortDirection.Ascending:
         newSortDirection = "ASC";
         break;
      case SortDirection.Descending:
         newSortDirection = "DESC";
         break;
   }
   return newSortDirection
}
protected void gridView_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
   gridView.PageIndex = e.NewPageIndex;
   gridView.DataBind();
}
protected void gridView_Sorting(object sender, GridViewSortEventArgs e)
{
   DataTable dataTable = gridView.DataSource as DataTable;
   if (dataTable != null)
   {
      DataView dataView = new DataView(dataTable);
      dataView.Sort = e.SortExpression + " " + ConvertSortDirectionToSql(e.SortDirection);
      gridView.DataSource = dataView;
      gridView.DataBind();
   }
}
Tip 9: Delete Multiple rows in a GridView

If you have used Hotmail or any other similar email client, you might have observed that  we have the option of selecting multiple rows (using the checkbox provided) and perform a set of operations on them. In this article, we will replicate this scenario for a gridview. A gridview allows us to delete only a single row at a time. We will extend this functionality to select multiple rows and delete all of the selected rows in a single stroke. In this article, I assume that you are aware of creating asp.net web applications and have worked with gridview.
The sample makes use of the Northwind database. We will be pulling data from the Employee table. For this sample to work, drop all the Foreign Key relationships on the Employee Table. To do so, in Sql Server Management Studio, browse to the Northwind database and open the Employee table in design view. Right click in the Table designer on the right hand side and choose ‘Relationships’. Select all the relationships like FK_Orders_Employees,  FK_EmployeeTerritories_Employees etc and delete them. This step is necessary as we will get a constraint violation exception if we do not do so.
Once we are through with the task of removing the relationships in the Employee table, let us explore the steps to create a gridview with functionality to delete multiple rows at a time.
Perform the following steps :
Step 1: Create an .aspx page and add a GridView and a SqlDataSource control to it.
Step 2: Configure the connection of SqlDataSource to point to the Northwind database.  Create queries for the Select and Delete commands. The resultant code will look similar as given below :
<asp:SqlDataSource ID="SqlDataSource1" Runat="server"
    SelectCommand="SELECT EmployeeID, LastName, City FROM Employees"
    DeleteCommand="DELETE FROM Employees WHERE [EmployeeID] = @EmployeeID"
    ConnectionString="<%$ ConnectionStrings:NorthwindConnectionString %>" >
       <DeleteParameters>
           <asp:Parameter Name="EmployeeID" />
       </DeleteParameters>
</asp:SqlDataSource>                                   
Step 3: Once the SqlDataSource has been configured, bind the gridview with this data source.
Step 4: To create a checkbox in each row, follow these steps:
1.    Create a TemplateField inside the <Columns> to add custom content to each column.
2.    Inside the TemplateField, create an ItemTemplate with a CheckBox added to it.
<asp:TemplateField>
       <ItemTemplate>
             <asp:CheckBox ID="chkRows" runat="server"/>
      </ItemTemplate>
 </asp:TemplateField>
This will add a checkbox to each row in the grid.
Step 5: Add a button control, and rename it to btnMultipleRowDelete.
The resultant markup in the design view will look similar to the code below :
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="EmployeeID" DataSourceID="SqlDataSource1">
  
   <Columns>
      <asp:TemplateField>
          <ItemTemplate>
            <asp:CheckBox ID="cbRows" runat="server"/>
          </ItemTemplate>
       </asp:TemplateField>
<asp:BoundField DataField="EmployeeID" HeaderText="EmployeeID" InsertVisible="False" ReadOnly="True" SortExpression="EmployeeID" />
<asp:BoundField DataField="LastName" HeaderText="LastName" SortExpression="LastName" />
<asp:BoundField DataField="City" HeaderText="City" SortExpression="City" />
   </Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" Runat="server"
SelectCommand="SELECT EmployeeID, LastName, City FROM Employees"
DeleteCommand="DELETE FROM Employees WHERE [EmployeeID] = @EmployeeID"
ConnectionString="<%$ ConnectionStrings:NorthwindConnectionString %>" >
   <DeleteParameters>
       <asp:Parameter Name="EmployeeID" />
   </DeleteParameters>
</asp:SqlDataSource>
<asp:Button
   ID="btnMultipleRowDelete"
   OnClick="btnMultipleRowDelete_Click"
   runat="server"
   Text="Delete Rows" />
In Code behind file (.cs) for C# and (.vb) for VB.NET, code the button click event. Our code will first loop through all the rows in the GridView. If a row is checked, the code retrieves the EmployeeID and passes the selected value to the Delete Command.
C#
protected void btnMultipleRowDelete_Click(object sender, EventArgs e)
{
        // Looping through all the rows in the GridView
        foreach (GridViewRow row in GridView1.Rows)
        {
            CheckBox checkbox = (CheckBox)row.FindControl("cbRows");
            //Check if the checkbox is checked.
//value in the HtmlInputCheckBox's Value property is set as the //value of the delete command's parameter.
            if (checkbox.Checked)
            {
                // Retreive the Employee ID
int employeeID = Convert.ToInt32(GridView1.DataKeys[row.RowIndex].Value);
// Pass the value of the selected Employye ID to the Delete //command.
SqlDataSource1.DeleteParameters["EmployeeID"].DefaultValue = employeeID.ToString();
                SqlDataSource1.Delete();
            }
        }
 }
Run the code, and select a few rows in the grid. ‘Delete Rows’ button, the selected rows get deleted. Rather than deleting rows one at a time, deleting them in a batch is a good practice.  
Tip 10: Export GridView To Excel
C#
protected void Button1_Click(object sender, EventArgs e)
    {
        Response.AddHeader("content-disposition", "attachment;filename=FileName.xls");
        Response.Charset = String.Empty;
        Response.ContentType = "application/vnd.xls";
        System.IO.StringWriter sw = new System.IO.StringWriter();
        System.Web.UI.HtmlTextWriter hw = new HtmlTextWriter(sw);
        GridView1.RenderControl(hw);
        Response.Write(sw.ToString());
        Response.End();
    }
Well that was a quick overview of some of the most frequently used features of the GridView control. I hope you liked the article and I thank you for viewing it. 

No comments:

Post a Comment