ASP.NET GridView用法(二) 模板,脚注,排序,编辑,删除,多选,分页,添加
2017-12-03 11:18
891 查看
这个例子是一个 图书管理的gridview. 项目地址:https://gitee.com/qiuyuhan/gridviewbookinfo
数据库:
如果要用脚注,基本每一项都需要改用模板的形式。
WebForm1.aspx
Web.Config
bookinfo.cs
运行效果:
数据库:
如果要用脚注,基本每一项都需要改用模板的形式。
WebForm1.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="gridview书籍管理.WebForm1" %> <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <title></title> </head> <body> <form id="form1" runat="server"> <div> <asp:GridView runat="server" ID="gridview1" AllowPaging="True" AutoGenerateColumns="False" OnPageIndexChanging="gridview1_PageIndexChanging" ShowFooter="True" OnRowEditing="gridview1_RowEditing" OnRowCancelingEdit="gridview1_RowCancelingEdit" OnRowDataBound="gridview1_RowDataBound" OnRowUpdating="gridview1_RowUpdating" OnRowDeleting="gridview1_RowDeleting" AllowSorting="True" OnSorting="gridview1_Sorting" > <Columns> <asp:TemplateField HeaderText="书籍Id" SortExpression="Id" > <ItemTemplate> <asp:Label runat="server" ID="lbid" Text='<%# Eval("Id") %>' /> </ItemTemplate> </asp:TemplateField> <asp:TemplateField HeaderText="书籍名称" SortExpression="Title"> <ItemTemplate> <asp:Label runat="server" ID="lbtitle" Text='<%# Eval("Title") %>' /> </ItemTemplate> <EditItemTemplate> <asp:TextBox runat="server" ID="txtEditTitle" Text='<%# Eval("Title") %>' ></asp:TextBox> </EditItemTemplate> <FooterTemplate> <asp:TextBox runat="server" ID="txtTitle"></asp:TextBox> </FooterTemplate> </asp:TemplateField> <asp:TemplateField HeaderText="简介" SortExpression="Descript"> <ItemTemplate> <asp:Label runat="server" ID="lbdes" Text='<%# Eval("Descript") %>'></asp:Label> </ItemTemplate> <EditItemTemplate> <asp:TextBox runat="server" ID="txtEditDes" Text='<%# Eval("Descript") %>' ></asp:TextBox> </EditItemTemplate> <FooterTemplate> <asp:TextBox runat="server" ID="txtDes"></asp:TextBox> </FooterTemplate> </asp:TemplateField> <asp:TemplateField HeaderText="图书分类" SortExpression="Booktype"> <ItemTemplate> <asp:Label runat="server" ID="lbtype" Text='<%# Eval("Booktype") %>' /> </ItemTemplate> <EditItemTemplate> <asp:DropDownList runat="server" ID="ddEditType"> <asp:ListItem Text="计算机" Value="计算机"></asp:ListItem> <asp:ListItem Text="其它" Value="其它"></asp:ListItem> </asp:DropDownList> </EditItemTemplate> <FooterTemplate> <asp:DropDownList runat="server" ID="ddType"> <asp:ListItem Text="计算机" Value="计算机"></asp:ListItem> <asp:ListItem Text="其它" Value="其它"></asp:ListItem> </asp:DropDownList> </FooterTemplate> </asp:TemplateField> <asp:TemplateField HeaderText="单价" SortExpression="Price"> <ItemTemplate> <asp:Label runat="server" Text='<%# Eval("Price") %>' ID="labPrice"></asp:Label> </ItemTemplate> <EditItemTemplate> <asp:TextBox runat="server" ID="txtEditPrice" Text='<%# Eval("Price") %>' ></asp:TextBox> </EditItemTemplate> <FooterTemplate> <asp:TextBox runat="server" ID="txtPrice"></asp:TextBox> </FooterTemplate> </asp:TemplateField> <asp:TemplateField HeaderText="选择"> <ItemTemplate> <asp:CheckBox runat="server" ID="chkbox"/> </ItemTemplate> <FooterTemplate> <asp:Button runat="server" ID="btnadd" Text="添加" OnClick="btnadd_Click"/> </FooterTemplate> </asp:TemplateField> <asp:CommandField runat="server" ShowEditButton="True" HeaderText="操作" /> <asp:CommandField runat="server" ShowDeleteButton="True" /> </Columns> </asp:GridView> </div> <div> <asp:CheckBox runat="server" ID="chkAll" Text="全选" AutoPostBack="true" OnCheckedChanged="chkAll_CheckedChanged"/> <asp:Button runat="server" ID="btndelall" Text="删除" OnClick="btndelall_Click" /> </div> <div> <asp:Button runat="server" ID="btnpricesum" Text="价格求和" OnClick="btnpricesum_Click"/> <asp:Label runat="server" ID="labsum" Text="0.00"></asp:Label> </div> </form> </body> </html>WebForm1.aspx.cs
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using BLL; using Model; using System.Data; namespace gridview书籍管理 { public partial class WebForm1 : System.Web.UI.Page { private int currentid; protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { //排序表达式 实际上就是 字段名(ViewState作为全局变量) ViewState["sortexpression"] = "Id"; //排序顺序 ViewState["sortorder"] = "ASC"; //绑定数据 Bind(); } } public void Bind() { // this.gridview1.DataSource = BLL.UserBLL.selectAllbooks(); //设置datakey this.gridview1.DataKeyNames = new string[] { "Id" }; //使用dataview进行排序 DataView view = BLL.UserBLL.selectAllbooks().DefaultView; //设置排序 view.Sort = ViewState["sortexpression"] + " " + ViewState["sortorder"]; //设置dataview this.gridview1.DataSource = view; //绑定 this.gridview1.DataBind(); } /// 分页时 protected void gridview1_PageIndexChanging(object sender, GridViewPageEventArgs e) { ///分页 this.gridview1.PageIndex = e.NewPageIndex; //把编辑行恢复原状 this.gridview1.EditIndex = -1; //重新绑定 Bind(); } //行编辑时 protected void gridview1_RowEditing(object sender, GridViewEditEventArgs e) { //设置编辑行 this.gridview1.EditIndex = e.NewEditIndex; //保存当前正在编辑的行的id currentid = Convert.ToInt32(this.gridview1.DataKeys[e.NewEditIndex].Value); //重新绑定 Bind(); } //退出编辑 protected void gridview1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e) { //编辑行恢复 this.gridview1.EditIndex = -1; Bind(); } //行数据绑定 protected void gridview1_RowDataBound(object sender, GridViewRowEventArgs e) { if (this.gridview1.EditIndex == e.Row.RowIndex) //当前绑定数据行是编辑行 { int currentindex = e.Row.RowIndex; DropDownList ddl =(DropDownList) (e.Row.FindControl("ddEditType")); if (ddl != null) { bookinfo bi= UserBLL.selectbook(currentid); if (bi.Booktype == "其它") { ddl.SelectedIndex = 1; } else { ddl.SelectedIndex = 0; } } } } //行更新时 protected void gridview1_RowUpdating(object sender, GridViewUpdateEventArgs e) { int index= e.RowIndex; TextBox txtTitle= this.gridview1.Rows[index].FindControl("txtEditTitle") as TextBox; TextBox txtDes = this.gridview1.Rows[index].FindControl("txtEditDes") as TextBox; DropDownList ddl = this.gridview1.Rows[index].FindControl("ddEditType") as DropDownList; TextBox txtPrice = this.gridview1.Rows[index].FindControl("txtEditPrice") as TextBox; ///// bookinfo bi = new bookinfo(); bi.Title = txtTitle.Text; bi.Decsript = txtDes.Text; bi.Booktype = ddl.SelectedValue; bi.Price = Convert.ToDouble(txtPrice.Text.Trim()); ///获取id bi.Id = Convert.ToInt32(this.gridview1.DataKeys[index].Value); BLL.UserBLL.updateBook(bi); ////关闭编辑行 this.gridview1.EditIndex = -1; //重新绑定数据 Bind(); } //行删除时 protected void gridview1_RowDeleting(object sender, GridViewDeleteEventArgs e) { int index=e.RowIndex; int id=Convert.ToInt32( this.gridview1.DataKeys[index].Value); BLL.UserBLL.deleteByid(id); //重新绑定 Bind(); } //脚注里面的添加数据按钮点击事件 protected void btnadd_Click(object sender, EventArgs e) { //行对象.FindControl("ID") // FooterRow.FindControl() TextBox txttitle=this.gridview1.FooterRow.FindControl("txtTitle") as TextBox; TextBox txtDes = this.gridview1.FooterRow.FindControl("txtDes") as TextBox; DropDownList ddl = this.gridview1.FooterRow.FindControl("ddType") as DropDownList; TextBox txtPrice = this.gridview1.FooterRow.FindControl("txtPrice") as TextBox; //// bookinfo bi = new bookinfo(); bi.Title = txttitle.Text; bi.Decsript = txtDes.Text; bi.Booktype = ddl.SelectedValue; bi.Price = Convert.ToDouble(txtPrice.Text.Trim()); // BLL.UserBLL.addBook(bi); Bind(); } //全选 protected void chkAll_CheckedChanged(object sender, EventArgs e) { if (this.chkAll.Checked == true) { for (int i = 0; i < this.gridview1.Rows.Count; i++) { CheckBox chb = this.gridview1.Rows[i].FindControl("chkbox") as CheckBox; chb.Checked = true; } } else { for (int i = 0; i < this.gridview1.Rows.Count; i++) { CheckBox chb = this.gridview1.Rows[i].FindControl("chkbox") as CheckBox; chb.Checked = false; } } } //选择删除按钮 protected void btndelall_Click(object sender, EventArgs e) { for (int i = 0; i < this.gridview1.Rows.Count; i++) { CheckBox chb = this.gridview1.Rows[i].FindControl("chkbox") as CheckBox; if (chb.Checked == true) { int id = Convert.ToInt32(this.gridview1.DataKeys[i].Value); BLL.UserBLL.deleteByid(id); } } Bind(); } //求和 protected void btnpricesum_Click(object sender, EventArgs e) { double sum = 0; for (int i = 0; i < this.gridview1.Rows.Count; i++) { CheckBox chb = this.gridview1.Rows[i].FindControl("chkbox") as CheckBox; if (chb.Checked == true) { Label lab=this.gridview1.Rows[i].FindControl("labPrice") as Label; sum += Convert.ToDouble(lab.Text.Trim()); } } this.labsum.Text = sum.ToString(); } //排序时 protected void gridview1_Sorting(object sender, GridViewSortEventArgs e) { //产生点击事件的排序字符串 string expression = e.SortExpression; if (ViewState["sortexpression"].ToString() == expression) //如果上次点击的是这个,就直接设置ASC,DESC { if (ViewState["sortorder"].ToString() == "ASC") { ViewState["sortorder"] = "DESC"; } else { ViewState["sortorder"] = "ASC"; } } else { //如果上次没有点击这个 就直接排序 ViewState["sortexpression"] = expression; } /////////////这里只是设置一些全局变量 实际排序操作 在 DataView的Sort排序字符串里面设置 Bind();//重新绑定 } } }
Web.Config
<?xml version="1.0" encoding="utf-8"?> <!-- 有关如何配置 ASP.NET 应用程序的详细信息,请访问 https://go.microsoft.com/fwlink/?LinkId=169433 --> <configuration> <system.web> <compilation debug="true" targetFramework="4.5.2"/> <httpRuntime targetFramework="4.5.2"/> </system.web> <system.codedom> <compilers> <compiler language="c#;cs;csharp" extension=".cs" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.3.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:6 /nowarn:1659;1699;1701"/> <compiler language="vb;vbs;visualbasic;vbscript" extension=".vb" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.3.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:14 /nowarn:41008 /define:_MYTYPE=\"Web\" /optionInfer+"/> </compilers> </system.codedom> <connectionStrings> <add name="MYSQL" connectionString="Data Source=.;Initial Catalog=gridview;Integrated Security=True"/> </connectionStrings> </configuration>SQLHELPER.cs
using System; using System.Collections.Generic; using System.Text; //添加引用 System.Configuration using System.Configuration; using System.Data; using System.Data.Sql; using System.Data.SqlClient; namespace DAL { public class SQLHELPER { //获取Web.config里面的连接字符串 public static String configuration = ConfigurationManager.ConnectionStrings["MYSQL"].ConnectionString; /// <summary> /// 返回首行首列 /// </summary> /// <param name="sqltext">sql语句</param> /// <returns>(object)</returns> public static object ExecuteScalar(string sqltext) { using (SqlConnection conn = new SqlConnection(configuration)) { conn.Open(); SqlCommand cmd = new SqlCommand(sqltext, conn); return cmd.ExecuteScalar(); } } /// <summary> /// 返回受影响行数 /// </summary> /// <param name="sqltext"></param> /// <returns></returns> public static object ExecuteNonQuery(string sqltext) { using (SqlConnection conn = new SqlConnection(configuration)) { conn.Open(); SqlCommand cmd = new SqlCommand(sqltext, conn); return cmd.ExecuteNonQuery(); } } /// <summary> /// 返回DataSet结果集 /// </summary> /// <param name="sqltext">SQL语句</param> /// <returns>DataSet</returns> public static DataSet ExecuteDataSet(string sqltext) { using (SqlConnection conn = new SqlConnection(configuration)) { conn.Open(); SqlDataAdapter adapter = new SqlDataAdapter(sqltext, conn); DataSet dataset = new DataSet(); adapter.Fill(dataset); return dataset; } } } }UserServer.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Data; using Model; namespace DAL { public class UserServer { public static DataSet selectAllBooks() { string sql = " select * from bookinfo order by id desc"; return SQLHELPER.ExecuteDataSet(sql); } public static object addBook(bookinfo bi) { return SQLHELPER.ExecuteNonQuery(" insert into bookinfo (title,descript,booktype,price)values('" + bi.Title + "','" + bi.Decsript + "','" + bi.Booktype + "',' "+ bi.Price+"')"); } //根据id查找book public static DataSet selectBook(int id) { return SQLHELPER.ExecuteDataSet(" select [title],[descript],[booktype],[price] from bookinfo where id='" + id + "'"); } //更新书籍信息 public static object updateBook(bookinfo bi) { return SQLHELPER.ExecuteNonQuery(" update bookinfo set title='" + bi.Title + "',descript='" + bi.Decsript + "',booktype='" + bi.Booktype+ "',price='" + bi.Price+"' where id='" + bi.Id+"'"); } //删除书籍 public static object deleteByid(int id) { return SQLHELPER.ExecuteNonQuery(" delete from bookinfo where id='" + id + "'"); } } }UserBLL.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Data; using DAL; using Model; namespace BLL { public class UserBLL { public static DataTable selectAllbooks() { return UserServer.selectAllBooks().Tables[0]; } public static int addBook(bookinfo bi) { return Convert.ToInt32(UserServer.addBook(bi)); } ///根据id查找book public static bookinfo selectbook(int id) { DataTable dt= UserServer.selectBook(id).Tables[0]; bookinfo bi = new bookinfo(); bi.Id = id; bi.Title = dt.Rows[0][0].ToString(); bi.Decsript= dt.Rows[0][1].ToString(); bi.Booktype = dt.Rows[0][2].ToString(); return bi; // bi.Price = dt.Rows[0][3] } //更新书籍信息 public static int updateBook(bookinfo bi) { return Convert.ToInt32(DAL.UserServer.updateBook(bi)); } //删除书籍 public static int deleteByid(int id) { return Convert.ToInt32(DAL.UserServer.deleteByid(id)); } } }
bookinfo.cs
using System; using System.Collections.Generic; using System.Text; namespace Model { /// <summary> /// 图书信息实体类 /// </summary> public class bookinfo { private int id; private string title; private string decsript; private string booktype; private double price; public int Id { get => id; set => id = value; } public string Title { get => title; set => title = value; } public string Decsript { get => decsript; set => decsript = value; } public string Booktype { get => booktype; set => booktype = value; } public double Price { get => price; set => price = value; } } }
运行效果:
相关文章推荐
- GridView 实现自定义分页、排序、查询、添加、编辑、多选删除 之代码规范
- GridView 实现自定义分页、排序、查询、添加、编辑、多选删除、导出、突出显示等常见应用实现
- GridView 实现自定义分页、排序、查询、添加、编辑、多选删除、导出、突出显示等常见应用实现(cs)
- GridView 实现自定义分页、排序、查询、添加、编辑、多选删除 之代码规范
- GridView 实现自定义分页、排序、查询、添加、编辑、多选删除 之代码规范
- GridView 实现自定义分页、排序、查询、添加、编辑、多选删除
- GridView 实现自定义分页、排序、查询、添加、编辑、多选删除 之代码规范
- GridView 实现自定义分页、排序、查询、添加、编辑、多选删除
- GridView 实现自定义分页、排序、查询、添加、编辑、多选删除、导出、突出显示等常见应用实现
- gridview 实现自定义分页、排序、查询、添加、编辑、多选删除 之代码规范
- [Asp.Net]GridView无代码分页排序,选中,编辑,取消,删除,正反双向排序,下拉菜单DropDownList结合
- asp.net中gridview的查询、分页、编辑更新、删除的实例代码
- ASP.NET 中 对GridView(网格视图)的查、分页、编辑更新、删除操作
- Asp.Net[C#] 使用GridView 分页,编辑,删除,导出XML完整页面
- asp.net中gridview的查询、分页、编辑更新、删除的实例代码
- Asp.Net[C#] 使用GridView 分页,编辑,删除,导出XML完整页面
- Asp.Net:GridView 编辑、删除、自定义分页以后备用
- Asp.Net[C#] 使用GridView 分页,编辑,删除,导出XML完整页面
- [转载]ASP.NET中为GridView添加删除提示框
- [ASP.NET]GridView自定义编辑,更新,取消,删除