博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
【ASP.NET】演绎GridView基本操作事件
阅读量:5100 次
发布时间:2019-06-13

本文共 26898 字,大约阅读时间需要 89 分钟。

 

对于gridview学NET的同学再熟悉不过,但是其中功能事件是否能编码熟练实现?前不久看点博文,以及资料,综合自己的一些想法,汇总如下:

 


数据库设计如下,以便更好理解:

设计:

 

实现:

 

 


 

GridView无代码分页排序

小实例:

 

 

 AllowSorting设为True,aspx代码中是AllowSorting="True";

运行结果:

 

 


GridView选中,编辑,取消,删除

 

小实例:

 

GridView.aspx

 

View Code
1  
7
8 9
10
11
12
13
14 <%--
--%>15
16
17
18
19
20
21
22
23
24
25
26
27

 

 

 

 

GridView.aspx.cs

 

View Code
//公有数据        SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["sqlcon"].ConnectionString);        SqlCommand cmd;        protected void Page_Load(object sender, EventArgs e)        {            if (!IsPostBack)            {                bind(); //正常绑定            }        }   ///         /// 主题:绑定数据,查询显示个人信息        /// 时间:2012年11月21日14:54:13        /// 描述:通过简单的方法绑定,实现数据显示        /// 作者:小伙        ///         public void bind()        {            //数据连接web.config中已配置的数据            SqlDataAdapter da = new SqlDataAdapter("select top 5 * from person", con);//使用数据适配器内置查询,自动开闭数据库            DataSet ds = new DataSet();//使用数据集,采取断开式访问数据            da.Fill(ds, "person");            GridView1.DataSource = ds;            GridView1.DataKeyNames=new string[]{
"pid"};//设置主键 GridView1.DataBind(); } //实现分页 protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e) { GridView1.PageIndex = e.NewPageIndex; this.bind(); } //删除 protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e) { string sqlstr = "delete from person where pid='" + GridView1.DataKeys[e.RowIndex].Value.ToString() + "'"; con.Open(); cmd = new SqlCommand(sqlstr, con); cmd.ExecuteNonQuery(); con.Close(); bind(); } //取消编辑 protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e) { GridView1.EditIndex = -1; bind(); } //编辑 protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e) { GridView1.EditIndex = e.NewEditIndex; bind(); }//更新 protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e) { string sqlstr = "update person set pname='" +((TextBox)(GridView1.Rows[e.RowIndex].Cells[1].Controls[0])).Text.ToString().Trim() + "',psex='" +((TextBox)(GridView1.Rows[e.RowIndex].Cells[2].Controls[0])).Text.ToString().Trim()+"',padress='" +((TextBox)(GridView1.Rows[e.RowIndex].Cells[3].Controls[0])).Text.ToString().Trim()+"',pyoubiao='" +((TextBox)(GridView1.Rows[e.RowIndex].Cells[4].Controls[0])).Text.ToString().Trim()+"',pprice='" +((TextBox)(GridView1.Rows[e.RowIndex].Cells[5].Controls[0])).Text.ToString().Trim()+"' where pid='" +GridView1.DataKeys[e.RowIndex].Value.ToString()+"'"; cmd = new SqlCommand(sqlstr, con); con.Open(); cmd.ExecuteNonQuery(); con.Close(); GridView1.EditIndex = -1; bind(); }

 

 

 

 

运行结果:

运行初始页:

 

点击编辑:

 

更新后:

 

 

 

 


GridView正反双向排序

 

小实例:

 

 

GridView.aspx

 

View Code
1  
7
8 9 <%--
10
11
12
13
--%>14
15
16
17
18
19
20
21
22
23
24
25
26
27

 

 

 

 

GridView.aspx.cs

 

View Code
//公有数据        SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["sqlcon"].ConnectionString);        SqlCommand cmd;        protected void Page_Load(object sender, EventArgs e)        {            if (!IsPostBack)            {                ViewState["SortOrder"] = "pname";                ViewState["OrderDire"] = "ASC";                Sortbind1();//排序绑定            }        }//排序绑定        public void Sortbind1()        {            string sqlstr = "select top 5 * from person";            SqlDataAdapter myda = new SqlDataAdapter(sqlstr, con);            DataSet ds = new DataSet();            con.Open();            myda.Fill(ds, "person");            DataView view = ds.Tables["person"].DefaultView;            string sort = (string)ViewState["SortOrder"] + " " + (string)ViewState["OrderDire"];            view.Sort = sort;            GridView1.DataSource = view;            GridView1.DataBind();            con.Close();        } //排序        protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)        {            string sPage = e.SortExpression;            if (ViewState["SortOrder"].ToString() == sPage)            {                if (ViewState["OrderDire"].ToString() == "Desc")                {                    ViewState["OrderDire"] = "ASC";                }                else                {                    ViewState["OrderDire"] = "Desc";                }            }            else            {                ViewState["SortOrder"] = e.SortExpression;            }            Sortbind1();        }

 

 

 

 

运行结果:

排序前:

 

排序后:

 

 

 

 


GridView和下拉菜单DropDownList结合

小实例:

GridView.aspx

 

View Code
1 
7
8 9 <%--
10
11
12
13
--%>14
15
16
17
18
19
20
21
22
24
25
26
27
28
29
30
31
32

 

 

 

GridView.aspx.cs

 

View Code
//公有数据        SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["sqlcon"].ConnectionString);        SqlCommand cmd;        protected void Page_Load(object sender, EventArgs e)        {            if (!IsPostBack)            {                Drpbind();//dropdown绑定                            }        } //DropDownList绑定数据        DropDownList ddl;        public void Drpbind()        {            string sqlstr = "select top 5 * from person";            con.Open();            SqlDataAdapter myda = new SqlDataAdapter(sqlstr, con);            DataSet ds = new DataSet();             myda.Fill(ds, "person");            GridView1.DataSource = ds;            GridView1.DataBind();            for (int i = 0; i <= GridView1.Rows.Count - 1; i++)            {                DataRowView mydrv = ds.Tables["person"].DefaultView[i];                if (Convert.ToString(mydrv["psex"]).Trim() == "男")                {                    ddl = (DropDownList)GridView1.Rows[i].FindControl("DropDownList1");                    ddl.SelectedIndex = 0;                }                else  if (Convert.ToString(mydrv["psex"]).Trim() == "女")                {                    ddl = (DropDownList)GridView1.Rows[i].FindControl("DropDownList1");                    ddl.SelectedIndex = 1;                }            }            con.Close();        } //GridView和下拉菜单DropDownList结合,前台性别列datasouce调用        public SqlDataReader ddlbind()        {                      string sqlstr = "select distinct psex from person";//distinct只显示一次性别            using (cmd = new SqlCommand(sqlstr, con))            {                con.Close();                con.Open();                return cmd.ExecuteReader();            }        }

 

 

 

运行结果:

 

 

 


GridView和CheckBox结合

 

小实例:

 

GridView.aspx

 

View Code
1 
2
8
9
10
11
12
13
14
15
16
17
18
19
20 <%--
21
22
--%>23
24
25
26
27
28
29
31 32                                33
35   36
38

 

 

 

 

GridView.aspx.cs

 

View Code
//公有数据        SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["sqlcon"].ConnectionString);        SqlCommand cmd;        protected void Page_Load(object sender, EventArgs e)        {            if (!IsPostBack)            {                bind(); //正常绑定            }        }  public void bind()        {            //数据连接web.config中已配置的数据            SqlDataAdapter da = new SqlDataAdapter("select  * from person", con);//使用数据适配器内置查询,自动开闭数据库            DataSet ds = new DataSet();//使用数据集,采取断开式访问数据            da.Fill(ds, "person");            GridView1.DataSource = ds;            GridView1.DataKeyNames=new string[]{
"pid"};//设置主键 GridView1.DataBind(); } //利用CheckBox选中信息 protected void CheckBox2_CheckedChanged(object sender, EventArgs e) { for (int i = 0; i <= GridView1.Rows.Count - 1; 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) { for (int i = 0; i <= GridView1.Rows.Count - 1; i++) { CheckBox cbox = (CheckBox)GridView1.Rows[i].FindControl("CheckBox1"); if (cbox.Checked == true) { string sqlstr = "delete from person where pid='" + GridView1.DataKeys[i].Value + "'"; cmd = new SqlCommand(sqlstr, con); con.Open(); cmd.ExecuteNonQuery(); con.Close(); } } bind(); } //取消选中信息 protected void Button2_Click(object sender, EventArgs e) { CheckBox2.Checked = false; for (int i = 0; i <= GridView1.Rows.Count - 1; i++) { CheckBox cbox = (CheckBox)GridView1.Rows[i].FindControl("CheckBox1"); cbox.Checked = false; } }

 

 

 

 

运行结果:

 

 

 

 


鼠标移到GridView某一行时改变该行的背景色方法一

 

小实例:

 

GridView.aspx

 

View Code
1  
8
9
10
11
12
13
14
15
16
17
18
19
20 <%--
21
22
--%>23
24
25
26
27

 

 

 

 

GridView.aspx.cs

 

View Code
//公有数据        SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["sqlcon"].ConnectionString);        SqlCommand cmd;        protected void Page_Load(object sender, EventArgs e)        {            if (!IsPostBack)            {                bind(); //正常绑定            }        }  public void bind()        {            //数据连接web.config中已配置的数据            SqlDataAdapter da = new SqlDataAdapter("select  * from person", con);//使用数据适配器内置查询,自动开闭数据库            DataSet ds = new DataSet();//使用数据集,采取断开式访问数据            da.Fill(ds, "person");            GridView1.DataSource = ds;            GridView1.DataKeyNames=new string[]{
"pid"};//设置主键 GridView1.DataBind(); } //鼠标移动到某一行,改变改行颜色 protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e) { for (int i = 0; i < GridView1.Rows.Count+1; i++) //执行循环,保证每条数据都可以更新 { if (e.Row.RowType == DataControlRowType.DataRow) //首先判断是否是数据行 { //当鼠标停留时更改背景色 e.Row.Attributes.Add("onmouseover", "c=this.style.backgroundColor;this.style.backgroundColor='#999'"); //当鼠标移开时还原背景色 e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor=c"); } } }

 

 

 

 

运行结果:

 

 

 


鼠标移到GridView某一行时改变该行的背景色方法二

 

小实例:

 

GridView.aspx

 View Code

 

GridView.aspx.cs

 

View Code
1  //鼠标移动到某一行,改变改行颜色 2         protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e) 3         { 4             //如果是绑定数据行  5             if (e.Row.RowType == DataControlRowType.DataRow) 6             { 7                 //鼠标经过时,行背景色变  8                 e.Row.Attributes.Add("onmouseover", "this.style.backgroundColor='#999'"); 9                 //鼠标移出时,行背景色变 10                 e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor='#087'");11             }12         }

 

 

 

 

运行结果:

 

 

 


GridView实现删除时弹出确认对话框

 

小实例:

 

GridView.aspx

 

View Code
1 
8
9
10
11
12
13
14
15
16
17
18
19
20 <%--
21
--%>22
23
24
25
26
27

 

 

 

View Code

 

GridView.aspx.cs

 

View Code
1    //鼠标移动到某一行,改变改行颜色 2         protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e) 3         { 4             #region 5             //如果是绑定数据行  6             if (e.Row.RowType == DataControlRowType.DataRow) 7             { 8                 //鼠标经过时,行背景色变  9                 e.Row.Attributes.Add("onmouseover", "this.style.backgroundColor='#999'");10                 //鼠标移出时,行背景色变 11                 e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor='#087'");12             }13             #endregion14             //如果是绑定数据行 15             if (e.Row.RowType == DataControlRowType.DataRow)16             {17                 if (e.Row.RowState == DataControlRowState.Normal || e.Row.RowState == DataControlRowState.Alternate)18                 {19                     ((LinkButton)e.Row.Cells[7].Controls[0]).Attributes.Add("onclick", "javascript:return confirm('你确认要删除:\"" + e.Row.Cells[1].Text + "\"吗?')");20                 }21             } 22         }

 

 

 

 

运行结果:

 

 

 


GridView实现自动编号

 

小实例:

 

GridView.aspx

前台代码如上

GridView.aspx.cs

绑定显示数据代码如上,不再总结,以下只做主要代码:

 

View Code
1   //实现自动编号 2         protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e) 3         { 4             #region 5             //如果是绑定数据行  6             if (e.Row.RowType == DataControlRowType.DataRow) 7             { 8                 //鼠标经过时,行背景色变  9                 e.Row.Attributes.Add("onmouseover", "this.style.backgroundColor='#999'");10                 //鼠标移出时,行背景色变 11                 e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor='#087'");12             }13             #endregion14             #region15             //如果是绑定数据行 16             if (e.Row.RowType == DataControlRowType.DataRow)17             {18                 if (e.Row.RowState == DataControlRowState.Normal || e.Row.RowState == DataControlRowState.Alternate)19                 {20                     ((LinkButton)e.Row.Cells[8].Controls[0]).Attributes.Add("onclick", "javascript:return confirm('你确认要删除:\"" + e.Row.Cells[1].Text + "\"吗?')");21                 }22             }23             #endregion24             if (e.Row.RowIndex != -1)25             {26                 int id = e.Row.RowIndex + 1;27                 e.Row.Cells[0].Text = id.ToString();28             }29         }

 

 

 

 

运行结果:

 

 


GridView实现用“...”代替超长字符串

 

小实例:

 

GridView.aspx

View Code
1  
8
9
10
11
12
13
14
15
16
17
18
19
20
21 <%--
22
--%>23
24
25
26
27
28

 

GridView.aspx.cs

 

View Code
1   public void bind() 2         { 3             //数据连接web.config中已配置的数据 4             SqlDataAdapter da = new SqlDataAdapter("select  * from person", con);//使用数据适配器内置查询,自动开闭数据库 5             DataSet ds = new DataSet();//使用数据集,采取断开式访问数据 6             da.Fill(ds, "person"); 7             GridView1.DataSource = ds; 8             GridView1.DataKeyNames=new string[]{
"pid"};//设置主键 9 GridView1.DataBind();10 //省略字符11 for (int i = 0; i <= GridView1.Rows.Count - 1; i++)12 {13 DataRowView mydrv;14 string gIntro;15 if (GridView1.PageIndex == 0)16 {17 mydrv = ds.Tables["person"].DefaultView[i];18 gIntro = Convert.ToString(mydrv["padress"]);19 GridView1.Rows[i].Cells[5].Text = SubStr(gIntro, 2);20 }21 else22 {23 mydrv = ds.Tables["person"].DefaultView[i + (5 * GridView1.PageIndex)];24 gIntro = Convert.ToString(mydrv["padress"]);25 GridView1.Rows[i].Cells[5].Text = SubStr(gIntro, 2);26 }27 }28 }29 30 public string SubStr(string sString, int nLeng)31 {32 if (sString.Length <= nLeng)33 {34 return sString;35 }36 string sNewStr = sString.Substring(0, nLeng);37 sNewStr = sNewStr + "...";38 return sNewStr;39 }

 

 

 

 

运行结果:

 

 


GridView显示隐藏某一列

 

小实例:

 

GridView.aspx

 

View Code
1 
8
9
10
11
12
13
14
15
16
17
18
19
20
21 <%--
22
--%>23
24
25
26
27
28
29
30
32 33    
35 36                             37
39   40

 

 

 

 

GridView.aspx.cs

 

 

View Code
public void bind()        {            //数据连接web.config中已配置的数据            SqlDataAdapter da = new SqlDataAdapter("select  * from person", con);//使用数据适配器内置查询,自动开闭数据库            DataSet ds = new DataSet();//使用数据集,采取断开式访问数据            da.Fill(ds, "person");            GridView1.DataSource = ds;            GridView1.DataKeyNames=new string[]{
"pid"};//设置主键 GridView1.DataBind(); //省略字符 #region for (int i = 0; i <= GridView1.Rows.Count - 1; i++) { DataRowView mydrv; string gIntro; if (GridView1.PageIndex == 0) { mydrv = ds.Tables["person"].DefaultView[i]; gIntro = Convert.ToString(mydrv["padress"]); GridView1.Rows[i].Cells[5].Text = SubStr(gIntro, 2); } else { mydrv = ds.Tables["person"].DefaultView[i + (5 * GridView1.PageIndex)]; gIntro = Convert.ToString(mydrv["padress"]); GridView1.Rows[i].Cells[5].Text = SubStr(gIntro, 2); } } #endregion //隐藏列 GridView1.Columns[7].Visible = false;//一开始隐藏 CheckBox3.Checked = false;//如果不这样后面的代码会把他True } //隐藏列 protected void CheckBox3_CheckedChanged(object sender, EventArgs e) { GridView1.Columns[7].Visible = !GridView1.Columns[7].Visible; Response.Write("GridView1的第8列现在的显示隐藏状态是:" + GridView1.Columns[7].Visible.ToString()); }

 

 

 

运行结果:

 

 

 


GridView弹出新页面/弹出新窗口

 

小实例:

 

GridView.aspx

 

View Code

运行结果:

 

 


GridView突出显示某一单元格(工资低于10000元)

 

小实例:

 

GridView.aspx

View Code
1 
8
9
10 <%--
--%>11 12
13
14
15
16
17
18
19
20
21
22
23
24
25

 

GridView.aspx.cs

View Code
public void bind()        {            //数据连接web.config中已配置的数据            SqlDataAdapter da = new SqlDataAdapter("select * from person", con);//使用数据适配器内置查询,自动开闭数据库            DataSet ds = new DataSet();//使用数据集,采取断开式访问数据            da.Fill(ds, "person");            GridView1.DataSource = ds;            GridView1.DataKeyNames=new string[]{
"pid"};//设置主键 GridView1.DataBind(); //省略字符 #region //for (int i = 0; i <= GridView1.Rows.Count - 1; i++) //{ // DataRowView mydrv; // string gIntro; // if (GridView1.PageIndex == 0) // { // mydrv = ds.Tables["person"].DefaultView[i]; // gIntro = Convert.ToString(mydrv["padress"]); // GridView1.Rows[i].Cells[3].Text = SubStr(gIntro, 2); // } // else // { // mydrv = ds.Tables["person"].DefaultView[i + (5 * GridView1.PageIndex)]; // gIntro = Convert.ToString(mydrv["padress"]); // GridView1.Rows[i].Cells[5].Text = SubStr(gIntro, 2); // } //} #endregion //隐藏列 //GridView1.Columns[3].Visible = false;//一开始隐藏 //CheckBox3.Checked = false;//如果不这样后面的代码会把他True //突出显示某一单元格(工资起价少于10000) for (int i = 0; i <= GridView1.Rows.Count - 1; i++) { DataRowView mydrv = ds.Tables["person"].DefaultView[i]; string price = Convert.ToString(mydrv["pprice"]); if (Convert.ToDouble(price) < 10000)//大家这里根据具体情况设置可能ToInt32等等 { GridView1.Rows[i].Cells[5].BackColor = System.Drawing.Color.Red; } } }

 

运行结果:

 


GridView数据导入Excel/Excel数据读入GridView

 

小实例:

 

GridView.aspx

添加:<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="GridView.aspx.cs"

Inherits="DBControls.GridView" EnableEventValidation = "false"
%>

View Code
<%--
--%>

 

GridView.aspx.cs

 

View Code
//导出数据        protected void Button3_Click(object sender, EventArgs e)        {            Export("application/ms-excel", "student.xls");        }        private void Export(string FileType, string FileName)        {            Response.Charset = "GB2312";            Response.ContentEncoding = System.Text.Encoding.UTF7;            Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(FileName, Encoding.UTF8).ToString());            Response.ContentType = FileType;            this.EnableViewState = false;            StringWriter tw = new StringWriter();            HtmlTextWriter hw = new HtmlTextWriter(tw);            GridView1.RenderControl(hw);            Response.Write(tw.ToString());            Response.End();        }        //如果没有下面方法会报错        public override void VerifyRenderingInServerForm(Control control)        {        }

 

 

 

 

运行结果:

 

导出结果:

 

 

 


 

转载于:https://www.cnblogs.com/baiboy/archive/2012/11/22/myGridView.html

你可能感兴趣的文章
Web Service初探
查看>>
HTML中的行内元素和框元素详解
查看>>
如何获取手机号码?
查看>>
设计模式概述
查看>>
【刘润五分钟商学院】-151幸存者偏见
查看>>
瑜伽扭身祈祷式动作教程
查看>>
vs2008 jquery 智能提示
查看>>
复习URLHttpConnection方式GET,POST方式链接网络解析uri
查看>>
asp.net Dock布局开发设置
查看>>
程序员谨防加班猝死之十大建议(转)
查看>>
memcached全面剖析–5. memcached的应用和兼容程序(转)
查看>>
angularJS学习
查看>>
关于ASBox
查看>>
使用Fastjson解析List对象时出现:{"$ref":"$.data[0].task.OBJECTS[0]"}的问题原因及解决方法...
查看>>
BZOJ 2882 & 后缀数组的傻逼实现
查看>>
java第一天练习
查看>>
SA 的参数
查看>>
MakeDirZ.bat
查看>>
好的网站收藏---长期更新---长期更新---长期更新---长期更新--
查看>>
SQL SUM() 函数
查看>>