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]
        }
    }
VB.NET
Private Sub GridView1_RowCommand(ByVal sender As Object, ByVal e As GridViewCommandEventArgs)
      If e.CommandName = "Select" Then
            Dim idx As Integer = Convert.ToInt32(e.CommandArgument)
            Dim selrow As GridViewRow = GridView1.Rows(idx)
            Dim fstCell As String = selrow.Cells(0).Text
Dim scndCell As String = selrow.Cells(1).Text
' and so on
      End If
End Sub
 
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;
    }
VB.NET
Private Sub GridView1_RowUpdated(ByVal sender As Object, ByVal e As GridViewUpdatedEventArgs)
            ' Retrieve the row being edited.
            Dim index As Integer = GridView1.EditIndex
            Dim row As GridViewRow = GridView1.Rows(index)
 
            ' Retrieve the value of the first cell
            lblMsg.Text = "Updated record " & row.Cells(1).Text
 End Sub
 
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
    }
VB.NET
Protected Sub GridView1_RowDeleting(ByVal sender As Object, ByVal e As GridViewDeleteEventArgs)
        Dim ID As Integer = CInt(GridView1.DataKeys(e.RowIndex).Value)
        ' Query the database and get the values based on the ID
    End Sub
 
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;
        }
    }
VB.NET
Protected Sub gvDetail_RowUpdating(ByVal sender As Object, ByVal e As GridViewUpdateEventArgs)
   e.Cancel = True
End Sub
Private Sub GridView1_RowDeleting(ByVal sender As Object, ByVal e As GridViewDeleteEventArgs)
            ' Check for a condition and cancel the delete
            ' There should be atleast one row left in the GridView
            If GridView1.Rows.Count <= 1 Then
                  e.Cancel = True
            End If
End Sub
 
Tip 8: Paging and Sorting in GridView without using Datasource control
Original Code Author: Ryan Olshan
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();
   }
}
VB.NET
Private Function ConvertSortDirectionToSql(ByVal sortDireciton As SortDirection) As String
   Dim newSortDirection As String = String.Empty
 
   Select Case sortDirection
       Case SortDirection.Ascending
             newSortDirection = "ASC"
 
       Case SortDirection.Descending
             newSortDirection = "DESC"
   End Select
 
   Return newSortDirection
End Function
 
Protected Sub gridView_PageIndexChanging(ByVal sender As Object, ByVal e As GridViewPageEventArgs)
   gridView.PageIndex = e.NewPageIndex
   gridView.DataBind()
End Sub
 
Protected Sub gridView_Sorting(ByVal sender As Object, ByVal e As GridViewSortEventArgs)
   Dim dataTable As DataTable = TryCast(gridView.DataSource, DataTable)
 
   If Not dataTable Is Nothing Then
       Dim dataView As DataView = New DataView(dataTable)
       dataView.Sort = e.SortExpression & " " & ConvertSortDirectionToSql(e.SortDirection)
 
       gridView.DataSource = dataView
       gridView.DataBind()
   End If
End Sub
 
Tip 9: Delete Multiple rows in a GridView
Check this article of mine over here.
 
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();
    }
VB.NET
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs)
            Response.AddHeader("content-disposition", "attachment;filename=FileName.xls")
            Response.Charset = String.Empty
            Response.ContentType = "application/vnd.xls"
            Dim sw As System.IO.StringWriter = New System.IO.StringWriter()
            Dim hw As System.Web.UI.HtmlTextWriter = New HtmlTextWriter(sw)
            GridView1.RenderControl(hw)
            Response.Write(sw.ToString())
            Response.End()
End Sub
 
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.
posted on 2008-04-02 15:06  josephshi  阅读(622)  评论(0编辑  收藏  举报