原文:http://www.dotnetcurry.com/ShowArticle.aspx?ID=107
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>
<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#





