【ASP.NET】演绎GridView基本操作事件

 

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

 


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

设计:

 

实现:

 

 


 

GridView无代码分页排序

小实例:

 

 

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

运行结果:

 

 




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

 

小实例:

 

GridView.aspx

 

View Code
 1  <asp:GridView ID="GridView1" runat="server" Height="138px" Width="1117px" 
 2         AllowPaging="True" AllowSorting="True" AutoGenerateColumns="False" 
 3         onpageindexchanging="GridView1_PageIndexChanging" 
 4         onrowcancelingedit="GridView1_RowCancelingEdit" 
 5         onrowdeleting="GridView1_RowDeleting" onrowediting="GridView1_RowEditing" 
 6         onrowupdating="GridView1_RowUpdating">
 7         <Columns>
 8 
 9             <asp:TemplateField HeaderText="身份证号" SortExpression="pid">
10                 <ItemTemplate>
11                     <asp:Label ID="Label1" runat="server" Text='<%# Bind("pid") %>'></asp:Label>
12                 </ItemTemplate>
13             </asp:TemplateField>
14            <%-- <asp:BoundField DataField="pid" HeaderText="身份证号" SortExpression="pid" />--%>
15             <asp:BoundField DataField="pname" HeaderText="姓名" SortExpression="pname" />
16             <asp:BoundField DataField="psex" HeaderText="性别" SortExpression="psex" />
17             <asp:BoundField DataField="padress" HeaderText="地址" SortExpression="padress" />
18             <asp:BoundField DataField="pyoubiao" HeaderText="邮编"  SortExpression="pyoubiao" />
19             <asp:BoundField DataField="pprice" HeaderText="工资起价" SortExpression="pprice" />
20              <asp:CommandField HeaderText="选择" ShowSelectButton="True" />
21             <asp:CommandField HeaderText="编辑" ShowEditButton="True" />
22             <asp:CommandField HeaderText="删除" ShowDeleteButton="True" />
23         </Columns>
24         <EmptyDataRowStyle BackColor="Red" />
25         <HeaderStyle BackColor="#0000CC" Font-Bold="True" ForeColor="White" />
26         <PagerStyle BackColor="#864"  HorizontalAlign="Center" ForeColor="White"/>
27     </asp:GridView>

 

 

 

 

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(); //正常绑定
            }
        }


   /// <summary>
        /// 主题:绑定数据,查询显示个人信息
        /// 时间:2012年11月21日14:54:13
        /// 描述:通过简单的方法绑定,实现数据显示
        /// 作者:小伙
        /// </summary>
        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  <asp:GridView ID="GridView1" runat="server" Height="138px" Width="1117px" 
 2         AllowPaging="True" AllowSorting="True" AutoGenerateColumns="False" 
 3         onpageindexchanging="GridView1_PageIndexChanging" 
 4         onrowcancelingedit="GridView1_RowCancelingEdit" 
 5         onrowdeleting="GridView1_RowDeleting" onrowediting="GridView1_RowEditing" 
 6         onrowupdating="GridView1_RowUpdating" onsorting="GridView1_Sorting">
 7         <Columns>
 8 
 9             <%--<asp:TemplateField HeaderText="身份证号" SortExpression="pid">
10                 <ItemTemplate>
11                     <asp:Label ID="Label1" runat="server" Text='<%# Bind("pid") %>'></asp:Label>
12                 </ItemTemplate>
13             </asp:TemplateField>--%>
14             <asp:BoundField DataField="pid" HeaderText="身份证号" SortExpression="pid" />
15             <asp:BoundField DataField="pname" HeaderText="姓名" SortExpression="pname" />
16             <asp:BoundField DataField="psex" HeaderText="性别" SortExpression="psex" />
17             <asp:BoundField DataField="padress" HeaderText="地址" SortExpression="padress" />
18             <asp:BoundField DataField="pyoubiao" HeaderText="邮编"  SortExpression="pyoubiao" />
19             <asp:BoundField DataField="pprice" HeaderText="工资起价" SortExpression="pprice" />
20              <asp:CommandField HeaderText="选择" ShowSelectButton="True" />
21             <asp:CommandField HeaderText="编辑" ShowEditButton="True" />
22             <asp:CommandField HeaderText="删除" ShowDeleteButton="True" />
23         </Columns>
24         <EmptyDataRowStyle BackColor="Red" />
25         <HeaderStyle BackColor="#0000CC" Font-Bold="True" ForeColor="White" />
26         <PagerStyle BackColor="#864"  HorizontalAlign="Center" ForeColor="White"/>
27     </asp:GridView>

 

 

 

 

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 <asp:GridView ID="GridView1" runat="server" Height="138px" Width="1117px" 
 2         AllowPaging="True" AllowSorting="True" AutoGenerateColumns="False" 
 3         onpageindexchanging="GridView1_PageIndexChanging" 
 4         onrowcancelingedit="GridView1_RowCancelingEdit" 
 5         onrowdeleting="GridView1_RowDeleting" onrowediting="GridView1_RowEditing" 
 6         onrowupdating="GridView1_RowUpdating" onsorting="GridView1_Sorting">
 7         <Columns>
 8 
 9             <%--<asp:TemplateField HeaderText="身份证号" SortExpression="pid">
10                 <ItemTemplate>
11                     <asp:Label ID="Label1" runat="server" Text='<%# Bind("pid") %>'></asp:Label>
12                 </ItemTemplate>
13             </asp:TemplateField>--%>
14             <asp:BoundField DataField="pid" HeaderText="身份证号" SortExpression="pid" />
15             <asp:BoundField DataField="pname" HeaderText="姓名" SortExpression="pname" />
16             <asp:TemplateField HeaderText="性别" SortExpression="psex" >
17                 <ItemTemplate>
18                     <asp:DropDownList ID="DropDownList1" runat="server" DataSource='<%# ddlbind()%>' DataValueField="psex" DataTextField="psex"/>
19                 </ItemTemplate>
20             </asp:TemplateField>
21             <asp:BoundField DataField="padress" HeaderText="地址" SortExpression="padress" />
22             <asp:BoundField DataField="pyoubiao" HeaderText="邮编" 
23                 SortExpression="pyoubiao" />
24             <asp:BoundField DataField="pprice" HeaderText="工资起价" SortExpression="pprice" />
25              <asp:CommandField HeaderText="选择" ShowSelectButton="True" />
26             <asp:CommandField HeaderText="编辑" ShowEditButton="True" />
27             <asp:CommandField HeaderText="删除" ShowDeleteButton="True" />
28         </Columns>
29         <EmptyDataRowStyle BackColor="Red" />
30         <HeaderStyle BackColor="#0000CC" Font-Bold="True" ForeColor="White" />
31         <PagerStyle BackColor="#864"  HorizontalAlign="Center" ForeColor="White"/>
32     </asp:GridView>

 

 

 

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 <form id="form1" runat="server">
 2     <asp:GridView ID="GridView1" runat="server" Height="138px" Width="1117px" 
 3         AllowPaging="True" AllowSorting="True" AutoGenerateColumns="False" 
 4         onpageindexchanging="GridView1_PageIndexChanging" 
 5         onrowcancelingedit="GridView1_RowCancelingEdit" 
 6         onrowdeleting="GridView1_RowDeleting" onrowediting="GridView1_RowEditing" 
 7         onrowupdating="GridView1_RowUpdating" PageSize="4">
 8         <Columns>
 9              <asp:TemplateField>
10                 <ItemTemplate>
11                     <asp:CheckBox ID="CheckBox1" runat="server" />
12                  </ItemTemplate>
13               </asp:TemplateField>
14            <asp:BoundField DataField="pid" HeaderText="身份证号" SortExpression="pid" />
15             <asp:BoundField DataField="pname" HeaderText="姓名" SortExpression="pname" />
16             <asp:BoundField DataField="psex" HeaderText="性别" SortExpression="psex" />
17             <asp:BoundField DataField="padress" HeaderText="地址" SortExpression="padress" />
18             <asp:BoundField DataField="pyoubiao" HeaderText="邮编"  SortExpression="pyoubiao" />
19             <asp:BoundField DataField="pprice" HeaderText="工资起价" SortExpression="pprice" />
20             <%-- <asp:CommandField HeaderText="选择" ShowSelectButton="True" />
21             <asp:CommandField HeaderText="编辑" ShowEditButton="True" />
22             <asp:CommandField HeaderText="删除" ShowDeleteButton="True" />--%>
23         </Columns>
24         <EmptyDataRowStyle BackColor="Red" />
25         <HeaderStyle BackColor="#0000CC" Font-Bold="True" ForeColor="White" />
26         <PagerStyle BackColor="#864"  HorizontalAlign="Center" ForeColor="White"/>
27     </asp:GridView>
28     <br />
29     <asp:CheckBox ID="CheckBox2" runat="server" ForeColor="Red" Text="全选" 
30         AutoPostBack="True" oncheckedchanged="CheckBox2_CheckedChanged" />
31     
32     &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
33     <asp:Button ID="Button1" runat="server" Font-Bold="true" ForeColor="red"  
34         Text="删除" onclick="Button1_Click" />
35 &nbsp;&nbsp;
36     <asp:Button ID="Button2" runat="server" Font-Bold="true" ForeColor="red" 
37         Text="取消" onclick="Button2_Click" />
38     </form>

 

 

 

 

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  <asp:GridView ID="GridView1" runat="server" Height="138px" Width="1117px" 
 2         AllowPaging="True" AllowSorting="True" AutoGenerateColumns="False" 
 3         onpageindexchanging="GridView1_PageIndexChanging" 
 4         onrowcancelingedit="GridView1_RowCancelingEdit" 
 5         onrowdeleting="GridView1_RowDeleting" onrowediting="GridView1_RowEditing" 
 6         onrowupdating="GridView1_RowUpdating" PageSize="4" 
 7         onrowdatabound="GridView1_RowDataBound">
 8         <Columns>
 9              <asp:TemplateField>
10                 <ItemTemplate>
11                     <asp:CheckBox ID="CheckBox1" runat="server" />
12                  </ItemTemplate>
13               </asp:TemplateField>
14            <asp:BoundField DataField="pid" HeaderText="身份证号" SortExpression="pid" />
15             <asp:BoundField DataField="pname" HeaderText="姓名" SortExpression="pname" />
16             <asp:BoundField DataField="psex" HeaderText="性别" SortExpression="psex" />
17             <asp:BoundField DataField="padress" HeaderText="地址" SortExpression="padress" />
18             <asp:BoundField DataField="pyoubiao" HeaderText="邮编"  SortExpression="pyoubiao" />
19             <asp:BoundField DataField="pprice" HeaderText="工资起价" SortExpression="pprice" />
20             <%-- <asp:CommandField HeaderText="选择" ShowSelectButton="True" />
21             <asp:CommandField HeaderText="编辑" ShowEditButton="True" />
22             <asp:CommandField HeaderText="删除" ShowDeleteButton="True" />--%>
23         </Columns>
24         <EmptyDataRowStyle BackColor="Red" />
25         <HeaderStyle BackColor="#0000CC" Font-Bold="True" ForeColor="White" />
26         <PagerStyle BackColor="#864"  HorizontalAlign="Center" ForeColor="White"/>
27     </asp:GridView>

 

 

 

 

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 <asp:GridView ID="GridView1" runat="server" Height="138px" Width="1117px" 
 2         AllowPaging="True" AllowSorting="True" AutoGenerateColumns="False" 
 3         onpageindexchanging="GridView1_PageIndexChanging" 
 4         onrowcancelingedit="GridView1_RowCancelingEdit" 
 5         onrowdeleting="GridView1_RowDeleting" onrowediting="GridView1_RowEditing" 
 6         onrowupdating="GridView1_RowUpdating" PageSize="4" 
 7         onrowdatabound="GridView1_RowDataBound">
 8         <Columns>
 9              <asp:TemplateField>
10                 <ItemTemplate>
11                     <asp:CheckBox ID="CheckBox1" runat="server" />
12                  </ItemTemplate>
13               </asp:TemplateField>
14            <asp:BoundField DataField="pid" HeaderText="身份证号" SortExpression="pid" />
15             <asp:BoundField DataField="pname" HeaderText="姓名" SortExpression="pname" />
16             <asp:BoundField DataField="psex" HeaderText="性别" SortExpression="psex" />
17             <asp:BoundField DataField="padress" HeaderText="地址" SortExpression="padress" />
18             <asp:BoundField DataField="pyoubiao" HeaderText="邮编"  SortExpression="pyoubiao" />
19             <asp:BoundField DataField="pprice" HeaderText="工资起价" SortExpression="pprice" />
20             <%-- <asp:CommandField HeaderText="选择" ShowSelectButton="True" />
21             <asp:CommandField HeaderText="编辑" ShowEditButton="True" />--%>
22             <asp:CommandField HeaderText="删除" ShowDeleteButton="True" />
23         </Columns>
24         <EmptyDataRowStyle BackColor="Red" />
25         <HeaderStyle BackColor="#0000CC" Font-Bold="True" ForeColor="White" />
26         <PagerStyle BackColor="#864"  HorizontalAlign="Center" ForeColor="White"/>
27     </asp:GridView>

 

 

 

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             #endregion
14             //如果是绑定数据行 
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             #endregion
14             #region
15             //如果是绑定数据行 
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             #endregion
24             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  <asp:GridView ID="GridView1" runat="server" Height="138px" Width="1117px" 
 2         AllowPaging="True" AllowSorting="True" AutoGenerateColumns="False" 
 3         onpageindexchanging="GridView1_PageIndexChanging" 
 4         onrowcancelingedit="GridView1_RowCancelingEdit" 
 5         onrowdeleting="GridView1_RowDeleting" onrowediting="GridView1_RowEditing" 
 6         onrowupdating="GridView1_RowUpdating" PageSize="4" 
 7         onrowdatabound="GridView1_RowDataBound">
 8         <Columns>
 9          <asp:BoundField DataField="id" HeaderText="证号" SortExpression="id" />
10              <asp:TemplateField>
11                  <ItemTemplate>
12                     <asp:CheckBox ID="CheckBox1" runat="server" />
13                  </ItemTemplate>
14               </asp:TemplateField>
15             <asp:BoundField DataField="pid" HeaderText="身份证号" SortExpression="pid" />
16             <asp:BoundField DataField="pname" HeaderText="姓名" SortExpression="pname" />
17             <asp:BoundField DataField="psex" HeaderText="性别" SortExpression="psex" />
18             <asp:BoundField DataField="padress" HeaderText="地址" SortExpression="padress" />
19             <asp:BoundField DataField="pyoubiao" HeaderText="邮编"  SortExpression="pyoubiao" />
20             <asp:BoundField DataField="pprice" HeaderText="工资起价" SortExpression="pprice" />
21             <%-- <asp:CommandField HeaderText="选择" ShowSelectButton="True" />
22             <asp:CommandField HeaderText="编辑" ShowEditButton="True" />--%>
23             <asp:CommandField HeaderText="删除" ShowDeleteButton="True" />
24         </Columns>
25         <EmptyDataRowStyle BackColor="Red" />
26         <HeaderStyle BackColor="#0000CC" Font-Bold="True" ForeColor="White" />
27         <PagerStyle BackColor="#864"  HorizontalAlign="Center" ForeColor="White"/>
28     </asp:GridView>

 

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                 else
22                 {
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 <asp:GridView ID="GridView1" runat="server" Height="138px" Width="1117px" 
 2         AllowPaging="True" AllowSorting="True" AutoGenerateColumns="False" 
 3         onpageindexchanging="GridView1_PageIndexChanging" 
 4         onrowcancelingedit="GridView1_RowCancelingEdit" 
 5         onrowdeleting="GridView1_RowDeleting" onrowediting="GridView1_RowEditing" 
 6         onrowupdating="GridView1_RowUpdating" PageSize="4" 
 7         onrowdatabound="GridView1_RowDataBound">
 8         <Columns>
 9          <asp:BoundField DataField="id" HeaderText="证号" SortExpression="id" />
10              <asp:TemplateField>
11                  <ItemTemplate>
12                     <asp:CheckBox ID="CheckBox1" AutoPostBack="true" runat="server" />
13                  </ItemTemplate>
14               </asp:TemplateField>
15             <asp:BoundField DataField="pid" HeaderText="身份证号" SortExpression="pid" />
16             <asp:BoundField DataField="pname" HeaderText="姓名" SortExpression="pname" />
17             <asp:BoundField DataField="psex" HeaderText="性别" SortExpression="psex" />
18             <asp:BoundField DataField="padress" HeaderText="地址"   SortExpression="padress" />
19             <asp:BoundField DataField="pyoubiao" HeaderText="邮编"  SortExpression="pyoubiao" />
20             <asp:BoundField DataField="pprice" HeaderText="工资起价" SortExpression="pprice" />
21             <%-- <asp:CommandField HeaderText="选择" ShowSelectButton="True" />
22             <asp:CommandField HeaderText="编辑" ShowEditButton="True" />--%>
23             <asp:CommandField HeaderText="删除" ShowDeleteButton="True" />
24         </Columns>
25         <EmptyDataRowStyle BackColor="Red" />
26         <HeaderStyle BackColor="#0000CC" Font-Bold="True" ForeColor="White" />
27         <PagerStyle BackColor="#864"  HorizontalAlign="Center" ForeColor="White"/>
28     </asp:GridView>
29     <br />
30     <asp:CheckBox ID="CheckBox2" runat="server" ForeColor="Red" Text="全选" 
31         AutoPostBack="True" oncheckedchanged="CheckBox2_CheckedChanged" />
32     
33     &nbsp;&nbsp;&nbsp;<asp:CheckBox ID="CheckBox3" runat="server" ForeColor="Red" Text="隐藏工资起价" 
34         AutoPostBack="True" oncheckedchanged="CheckBox3_CheckedChanged" />
35     
36     &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
37     <asp:Button ID="Button1" runat="server" Font-Bold="true" ForeColor="red"  
38         Text="删除" onclick="Button1_Click" />
39 &nbsp;&nbsp;
40     <asp:Button ID="Button2" runat="server" Font-Bold="true" ForeColor="red" 
41         Text="取消" onclick="Button2_Click" />

 

 

 

 

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 <asp:GridView ID="GridView1" runat="server" Height="138px" Width="1117px" 
 2         AllowPaging="True" AllowSorting="True" AutoGenerateColumns="False" 
 3         onpageindexchanging="GridView1_PageIndexChanging" 
 4         onrowcancelingedit="GridView1_RowCancelingEdit" 
 5         onrowdeleting="GridView1_RowDeleting" onrowediting="GridView1_RowEditing" 
 6         onrowupdating="GridView1_RowUpdating" PageSize="4" 
 7         onrowdatabound="GridView1_RowDataBound">
 8         <Columns>
 9             <asp:BoundField DataField="pid" HeaderText="身份证号" SortExpression="pid" />
10 <%--  <asp:BoundField DataField="pname" HeaderText="姓名" SortExpression="pname" />--%>
11          
12              <asp:HyperLinkField HeaderText="姓名" Text="姓名" DataNavigateUrlFields="pname" DataNavigateUrlFormatString="WebForm1.aspx?GoodsID={0}" Target="mainframe" NavigateUrl="~/WebForm1.aspx" DataTextField="pname" >
13              </asp:HyperLinkField>
14             <asp:BoundField DataField="psex" HeaderText="性别" SortExpression="psex" />
15             <asp:BoundField DataField="padress" HeaderText="地址"   SortExpression="padress" />
16             <asp:BoundField DataField="pyoubiao" HeaderText="邮编"  SortExpression="pyoubiao" />
17             <asp:BoundField DataField="pprice" HeaderText="工资起价" DataFormatString="{0:C}"  SortExpression="pprice" />
18              <asp:CommandField HeaderText="选择" ShowSelectButton="True" />
19             <asp:CommandField HeaderText="编辑" ShowEditButton="True" />
20             <asp:CommandField HeaderText="删除" ShowDeleteButton="True" />
21         </Columns>
22         <EmptyDataRowStyle BackColor="Red" />
23         <HeaderStyle BackColor="#0000CC" Font-Bold="True" ForeColor="White" />
24         <PagerStyle BackColor="#864"  HorizontalAlign="Center" ForeColor="White"/>
25     </asp:GridView>

 

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
<asp:GridView ID="GridView1" runat="server" Height="138px" Width="1117px" 
        AllowPaging="True" AllowSorting="True" AutoGenerateColumns="False" 
        onpageindexchanging="GridView1_PageIndexChanging" 
        onrowcancelingedit="GridView1_RowCancelingEdit" 
        onrowdeleting="GridView1_RowDeleting" onrowediting="GridView1_RowEditing" 
        onrowupdating="GridView1_RowUpdating" PageSize="4" 
        onrowdatabound="GridView1_RowDataBound">
        <Columns>
            <asp:BoundField DataField="pid" HeaderText="身份证号" SortExpression="pid" />
<%--  <asp:BoundField DataField="pname" HeaderText="姓名" SortExpression="pname" />--%>
         
             <asp:HyperLinkField HeaderText="姓名" Text="姓名" DataNavigateUrlFields="pname" DataNavigateUrlFormatString="WebForm1.aspx?GoodsID={0}" Target="mainframe" NavigateUrl="~/WebForm1.aspx" DataTextField="pname" >
             </asp:HyperLinkField>
            <asp:BoundField DataField="psex" HeaderText="性别" SortExpression="psex" />
            <asp:BoundField DataField="padress" HeaderText="地址"   SortExpression="padress" />
            <asp:BoundField DataField="pyoubiao" HeaderText="邮编"  SortExpression="pyoubiao" />
            <asp:BoundField DataField="pprice" HeaderText="工资起价" DataFormatString="{0:C}"  SortExpression="pprice" />
             <asp:CommandField HeaderText="选择" ShowSelectButton="True" />
            <asp:CommandField HeaderText="编辑" ShowEditButton="True" />
            <asp:CommandField HeaderText="删除" ShowDeleteButton="True" />
        </Columns>
        <EmptyDataRowStyle BackColor="Red" />
        <HeaderStyle BackColor="#0000CC" Font-Bold="True" ForeColor="White" />
        <PagerStyle BackColor="#864"  HorizontalAlign="Center" ForeColor="White"/>
        <FooterStyle BackColor="White" HorizontalAlign="Center" ForeColor="Red"/>
    </asp:GridView>

 

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://my.oschina.net/u/3579120/blog/1539161

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值