大话GridView—(1) 编辑、删除、查看详情、分页
GridView控件的使用绝对是任何.net开发人员都必须具备的基础知识。如何使用,怎样用好GridView的各个功能,还是有很多人对其不甚了解,今天我将对GridView控件简单的编辑、删除进行阐述,希望对大家有所帮助。
创建表:
USE [test] GO CREATE TABLE [dbo].[B] ( [ID] [int] NOT NULL, [Subject] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL, [Score] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL )ON [PRIMARY] GO
前台代码如下:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %> <!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>无标题页</title> </head> <body> <form id="form1" runat="server"> <div> </div> <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="ID" onrowcancelingedit="GridView1_RowCancelingEdit" onrowdeleting="GridView1_RowDeleting" onrowediting="GridView1_RowEditing" onrowupdating="GridView1_RowUpdating" AllowPaging="true" PageSize="5" onpageindexchanging="GridView1_PageIndexChanging"> <Columns> <asp:BoundField DataField="ID" HeaderText="编号" ReadOnly="True"/> <asp:TemplateField HeaderText="科目"> <EditItemTemplate> <asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("Subject") %>'></asp:TextBox> </EditItemTemplate> <ItemTemplate> <asp:Label ID="Label1" runat="server" Text='<%# Bind("Subject") %>'></asp:Label> </ItemTemplate> </asp:TemplateField> <asp:TemplateField HeaderText="分数"> <EditItemTemplate> <asp:TextBox ID="TextBox2" runat="server" Text='<%# Bind("Score") %>'></asp:TextBox> </EditItemTemplate> <ItemTemplate> <asp:Label ID="Label2" runat="server" Text='<%# Bind("Score") %>'></asp:Label> </ItemTemplate> </asp:TemplateField> <asp:CommandField HeaderText="编辑" ShowEditButton="True" /> <asp:CommandField HeaderText="删除" ShowDeleteButton="True" /> <asp:HyperLinkField DataNavigateUrlFields="ID" DataNavigateUrlFormatString="view.aspx?id={0}" HeaderText="查看" Text="查看" /> </Columns> </asp:GridView> </form> </body> </html>
要使可以编辑,使想要编辑的字段转化为可编辑列。
后台代码:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
using System;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.SqlClient;
publicpartialclass _Default : System.Web.UI.Page
{
private SqlConnection conn;
private SqlCommand cmd;
private SqlDataAdapter adapter;
protectedvoid Page_Load(object sender, EventArgs e)
{
#region//绑定数据到GridView1
//!IsPostBack很重要,如果不加这句的话,将不能更新,因为该语句表示加载时再执行。具体用法,下次再详解
if (!IsPostBack)
{
bind();
}
#endregion
}
protected SqlConnection getDB()
{
#region//连接数据库
string connString ="server=MyComputer\\sqlexpress;database=test;uid=sa;pwd=123456";
returnnew SqlConnection(connString);
#endregion
}
protectedvoid bind()
{
#region//获取数据
string selet_all ="select * from B";
conn = getDB();
conn.Open();
cmd =new SqlCommand();
cmd.CommandText = selet_all;
cmd.Connection = conn;
adapter =new SqlDataAdapter(cmd);
DataSet ds =new DataSet();
adapter.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
conn.Close();
#endregion
}
protectedvoid GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
#region//初始化编辑
GridView1.EditIndex = e.NewEditIndex;
bind();
#endregion
}
protectedvoid GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
#region//删除
int id = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Value);
string delete_one ="delete from B where ID='"+id+"'";
conn = getDB();
conn.Open();
cmd =new SqlCommand();
cmd.Connection = conn;
cmd.CommandText = delete_one;
cmd.ExecuteNonQuery();
conn.Close();
bind();
#endregion
}
protectedvoid GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
#region//取消编辑
GridView1.EditIndex =-1;
bind();
#endregion
}
protectedvoid GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
#region//更新
int id = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Value);
TextBox sub = GridView1.Rows[e.RowIndex].Cells[1].FindControl("TextBox1") as TextBox;
TextBox sco = GridView1.Rows[e.RowIndex].Cells[2].FindControl("TextBox2") as TextBox;
string subject = sub.Text.Trim().ToString();
string score = sco.Text.Trim().ToString();
string update_one ="update B set Subject='"+subject+"',Score='"+score+"' where ID='"+id+"'";
conn = getDB();
conn.Open();
cmd =new SqlCommand();
cmd.CommandText = update_one;
cmd.Connection = conn;
cmd.ExecuteNonQuery();
conn.Close();
GridView1.EditIndex =-1;
bind();
#endregion
}
protectedvoid GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;//绑定新业
bind();
}
}
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.SqlClient;
publicpartialclass _Default : System.Web.UI.Page
{
private SqlConnection conn;
private SqlCommand cmd;
private SqlDataAdapter adapter;
protectedvoid Page_Load(object sender, EventArgs e)
{
#region//绑定数据到GridView1
//!IsPostBack很重要,如果不加这句的话,将不能更新,因为该语句表示加载时再执行。具体用法,下次再详解
if (!IsPostBack)
{
bind();
}
#endregion
}
protected SqlConnection getDB()
{
#region//连接数据库
string connString ="server=MyComputer\\sqlexpress;database=test;uid=sa;pwd=123456";
returnnew SqlConnection(connString);
#endregion
}
protectedvoid bind()
{
#region//获取数据
string selet_all ="select * from B";
conn = getDB();
conn.Open();
cmd =new SqlCommand();
cmd.CommandText = selet_all;
cmd.Connection = conn;
adapter =new SqlDataAdapter(cmd);
DataSet ds =new DataSet();
adapter.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
conn.Close();
#endregion
}
protectedvoid GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
#region//初始化编辑
GridView1.EditIndex = e.NewEditIndex;
bind();
#endregion
}
protectedvoid GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
#region//删除
int id = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Value);
string delete_one ="delete from B where ID='"+id+"'";
conn = getDB();
conn.Open();
cmd =new SqlCommand();
cmd.Connection = conn;
cmd.CommandText = delete_one;
cmd.ExecuteNonQuery();
conn.Close();
bind();
#endregion
}
protectedvoid GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
#region//取消编辑
GridView1.EditIndex =-1;
bind();
#endregion
}
protectedvoid GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
#region//更新
int id = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Value);
TextBox sub = GridView1.Rows[e.RowIndex].Cells[1].FindControl("TextBox1") as TextBox;
TextBox sco = GridView1.Rows[e.RowIndex].Cells[2].FindControl("TextBox2") as TextBox;
string subject = sub.Text.Trim().ToString();
string score = sco.Text.Trim().ToString();
string update_one ="update B set Subject='"+subject+"',Score='"+score+"' where ID='"+id+"'";
conn = getDB();
conn.Open();
cmd =new SqlCommand();
cmd.CommandText = update_one;
cmd.Connection = conn;
cmd.ExecuteNonQuery();
conn.Close();
GridView1.EditIndex =-1;
bind();
#endregion
}
protectedvoid GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;//绑定新业
bind();
}
}
点击查看详情,转到view.aspx是通过以下代码获取ID的值:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
publicpartialclass view : System.Web.UI.Page
{
protectedvoid Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
int id=Convert.ToInt32(Request.QueryString["ID"].ToString());
Lable1.Text = id.ToString();
}
}
}
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
publicpartialclass view : System.Web.UI.Page
{
protectedvoid Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
int id=Convert.ToInt32(Request.QueryString["ID"].ToString());
Lable1.Text = id.ToString();
}
}
}
GridView功能也许没有DataList强大,但是它在 很多地方还是有很大用处的,相信每个开发人员都已经了解到了,GridView还自带分页、设置样式等。这里的代码分页如果记录过多的话,将使服务器经受很大的考验,接下来我将为大家继续码优质的分页代码和其它GridView高级进阶。谢谢!!