GridView更新剔除选中正反排序等操作新篇二
这一篇是对之前的一篇关于GridView更新删除的文章的进一步补充和解释,并增加了排序,checkbox操作以及隐藏某一列的具体操作。希望大家能够互相学习,积极纠正我的某一些错误和写法,并提出一些更为简单严谨的解决方案。
前台代码:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="GridViewDIY.aspx.cs" Inherits="GridViewCollection.GridViewDIY" %>
<!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>GridViewDIY</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="GridView1" runat="server" DataKeyNames="id" AutoGenerateColumns="False" AllowPaging="True" PageSize="5" AllowSorting="True" OnRowCancelingEdit="GridView1_RowCancelingEdit" OnRowDataBound="GridView1_RowDataBound" OnRowDeleting="GridView1_RowDeleting" OnRowEditing="GridView1_RowEditing" OnRowUpdating="GridView1_RowUpdating" OnSorting="GridView1_Sorting">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="CheckBox1" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="id" HeaderText="id" SortExpression="id" ReadOnly="true" />
<asp:BoundField DataField="品牌" HeaderText="品牌" SortExpression="品牌" />
<asp:BoundField DataField="价格" HeaderText="价格" SortExpression="价格" />
<asp:BoundField DataField="数量" HeaderText="数量" SortExpression="数量" />
<asp:BoundField DataField="生产日期" HeaderText="生产日期" DataFormatString="{0:M-dd-yyyy}" SortExpression="生产日期" />
<asp:CommandField ShowEditButton="True" />
<asp:CommandField CausesValidation="false" ShowDeleteButton="True" />
</Columns>
</asp:GridView>
<asp:CheckBox ID="CheckBox2" runat="server" AutoPostBack="true" OnCheckedChanged="CheckBox2_CheckedChanged" />
<asp:Button ID="Button1" runat="server" Text="取消" OnClick="Button1_Click" />
<asp:Button ID="Button2" runat="server" Text="删除" OnClick="Button2_Click" />
<br />
<asp:CheckBox ID="CheckBox3" runat="server" AutoPostBack="true" OnCheckedChanged="CheckBox3_CheckedChanged" />
<label>显示隐藏的列</label>
</div>
</form>
</body>
</html>
后台代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
namespace GridViewCollection
{
public partial class GridViewDIY : System.Web.UI.Page
{
string con = ConfigurationManager.ConnectionStrings["con"].ToString();
SqlConnection sqlcon;
SqlCommand sqlcom;
SqlDataAdapter sqlda;
DataSet ds;
DataView dv;
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
ViewState["SortOrder"] = "价格";
ViewState["SortDire"] = "ASC";
bind();
}
}
public void bind()
{//为GridView绑定数据
sqlcon = new SqlConnection(con);
string sql = "select * from Shuma";
sqlcon.Open();
sqlda = new SqlDataAdapter(sql,sqlcon);
ds = new DataSet();
sqlda.Fill(ds,"Shuma");
dv = new DataView();
//dv.Table = ds.Tables["Shuma"];
dv = ds.Tables["Shuma"].DefaultView;
string sort = ViewState["SortOrder"] + " " + ViewState["SortDire"];
dv.Sort = sort;
GridView1.DataSource = dv;
GridView1.DataBind();
sqlcon.Close();
GridView1.Columns[4].Visible = false;
CheckBox3.Checked = false;
}
public void changeRow(string str)
{
sqlcon = new SqlConnection(con);
sqlcom = new SqlCommand(str,sqlcon);
sqlcon.Open();
sqlcom.ExecuteNonQuery();
sqlcon.Close();
bind();
}
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{//激活编辑
GridView1.EditIndex = e.NewEditIndex;
bind();
}
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{//执行更新
string cell1 = ((TextBox)(GridView1.Rows[e.RowIndex].Cells[1].Controls[0])).Text.ToString();
string cell2 = ((TextBox)(GridView1.Rows[e.RowIndex].Cells[2].Controls[0])).Text.ToString();
string cell3 = ((TextBox)(GridView1.Rows[e.RowIndex].Cells[3].Controls[0])).Text.ToString();
string cell4 = ((TextBox)(GridView1.Rows[e.RowIndex].Cells[4].Controls[0])).Text.ToString();
string str = "update Shuma set 品牌='"+ cell1 +"',价格='"+ cell2 +"',数量='"+ cell3 +"',生产日期='"+ cell4 +"'where id='"+ GridView1.DataKeys[e.RowIndex].Value.ToString() +"'";
changeRow(str);
GridView1.EditIndex = -1;
bind();
}
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{//执行删除
string str = "delete from Shuma where id='"+ GridView1.DataKeys[e.RowIndex].Value.ToString() +"'";
changeRow(str);
bind();
}
protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{//取消编辑
GridView1.EditIndex = -1;
bind();
}
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{//一方面设置鼠标放上去和移出的每一行的颜色变化,另一方面对于删除的按钮进行增加onclick事件,提示用户是否真的删除,增加用户交互和体验
if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Attributes.Add("onmouseover","this.style.backgroundColor='#e6f5fa'");
e.Row.Attributes.Add("onmouseout","this.style.backgroundColor='#ffffff'");
if (e.Row.RowState == DataControlRowState.Normal || e.Row.RowState == DataControlRowState.Alternate)
{
((LinkButton)e.Row.Cells[7].Controls[0]).Attributes.Add("onclick", "javascript:return confirm('你确认要删除吗?')");
}
}
}
protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
{//进行排序,点击一次和两次分别按照ASC和DESC排序
string sortPage = e.SortExpression;
if(ViewState["SortOrder"].ToString() == sortPage )
{
if (ViewState["SortDire"].ToString() == "DESC")
ViewState["SortDire"] = "ASC";
else
ViewState["SortDire"] = "DESC";
}
else
{
ViewState["SortOrder"] = e.SortExpression;
}
bind();
}
protected void CheckBox2_CheckedChanged(object sender, EventArgs e)
{//批量对第一列的checkbox进行操作,要么全部勾选中,要么全部取消勾选
for (int i = 0; i < GridView1.Rows.Count;i++ )
{
CheckBox cbox = (CheckBox)GridView1.Rows[i].FindControl("CheckBox1");
if (CheckBox2.Checked == true)
cbox.Checked = true;
else
cbox.Checked = false;
}
}
protected void Button1_Click(object sender, EventArgs e)
{//遍历第一列的checkbox,对于已经勾选的checkbox进行取消勾选
CheckBox2.Checked = false;
for (int i = 0; i < GridView1.Rows.Count;i++ )
{
CheckBox cbox = (CheckBox)GridView1.Rows[i].FindControl("CheckBox1");
cbox.Checked = false;
}
}
protected void Button2_Click(object sender, EventArgs e)
{//遍历你所有勾选了的项,并进行对应的删除操作
for (int i = 0; i < GridView1.Rows.Count;i++ )
{
CheckBox cbox = (CheckBox)GridView1.Rows[i].FindControl("CheckBox1");
if(cbox.Checked == true)
{
string str = "delete from Shuma where id='"+ GridView1.DataKeys[i].Value +"'";
changeRow(str);
}
bind();
}
}
protected void CheckBox3_CheckedChanged(object sender, EventArgs e)
{//通过对CheckBox的勾选操作来设置某一列的显示或隐藏,这里是对第5列进行操作的
GridView1.Columns[4].Visible = !GridView1.Columns[4].Visible;
}
}
}
这一篇文章是我看清清月儿和苏飞博客的总结和领悟,在这里我把能合并的示例合并在一个例子显示出来。在这里要谢谢清清月儿和苏飞博客的完美的整理和解释。
对于以上例子的解释:
1.排序(以下所说的标题就是数据库中的对应的列名,即排序的关键字)
一开始就定义ViewState["SortOrder"] = "价格"和ViewState["SortDire"] = "ASC"这两个量,在接着的GridView1_Sorting方法中判断用户是对于哪一个标题进行排序操作的,如果正好是"价格"这一标题,就运用ViewState["SortDire"]这个变量来回的正反排序(ASC或者是DESC)。如果不是"价格"这一标题,就把ViewState["SortOrder"]切换成用户选择的标题,再进行正反排序。(大家看方法中的if判断语句就明白了)
同时注意在bind()方法中要预先设置好页面初始加载的时候是以哪个标题进行排序显示的。
2.通过checkbox选中行或者取消选中行
先给GridView添加第一列checkbox,代码中是这样写的
<asp:TemplateField <ItemTemplate> <asp:CheckBox ID="CheckBox1" runat="server" /> </ItemTemplate> </asp:TemplateField>这里用的是自定义模板。然后在下面再添加一个checkbox和两个button控件。
勾选这个checkbox,就能对gridview里面的所有checkbox进行操作,进行全选或者全不选操作。
两个button,一个是取消,一个就是删除。这两个功能看对应的Button1_Click和Button2_Click就行了。。这里最重要的是
for (int i = 0; i < GridView1.Rows.Count;i++ )和
CheckBox cbox = (CheckBox)GridView1.Rows[i].FindControl("CheckBox1");
前者相当于遍历操作,后者是对于自定义模板取控件,而不能用之前的
string cell1 = ((TextBox)(GridView1.Rows[e.RowIndex].Cells[1].Controls[0])).Text.ToString();这种操作了。只要看懂这两个基本上就能理解具体的实现过程了。
3.隐藏GridView中的某一列,通过一个CheckBox来显示或者隐藏的切换。
这里一是要在bind()方法中就预先写好隐藏哪一列,像这样
GridView1.Columns[4].Visible = false;
CheckBox3.Checked = false;就说明预先隐藏的是第5列。
二则是要对应的CheckBox的CheckBox3_CheckedChanged()方法中进行隐藏和显示的切换。
以上就是我的全部理解和认识,虽然现在的GridView多用作显示的作用,很少有直接在上面改动的,一般都在Detail里改,但是对于它的利用和理解还是要掌握的,虽然有一些过时,而且在某些方面的灵活性不高,但是还是很能解决一些问题的。