• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

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

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

 

对于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=" 

鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap