在gridview中用checkbox选择及排序功能

前台代码

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="GridView.aspx.cs" Inherits="GridView.GridView" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
     <script type="text/javascript">
         function showinfo() {
             if (confirm('真的要删除吗') == false)
                 return false;
         }
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
            AllowSorting="True" onrowdatabound="GridView1_RowDataBound"
            onsorting="GridView1_Sorting" ShowFooter="True" >
           
            <Columns>
                <asp:TemplateField HeaderText="选择">
                    <ItemTemplate>
                        <asp:CheckBox ID="ck1" runat="server" />
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:BoundField DataField="NewsTitle" HeaderText="标题" />
                <asp:BoundField DataField="NewsContent" HeaderText="内容" />
                <asp:BoundField DataField="CreateTime" DataFormatString="{0:yyyy-mm-dd}"
                    HeaderText="创建时间" SortExpression="CreateTime" />
                <asp:BoundField DataField="ClassName" HeaderText="类别" />
                <asp:BoundField DataField="RealName" HeaderText="创建人"
                    SortExpression="RealName" />
                <asp:TemplateField HeaderText="操作">
                    <ItemTemplate>
                        <asp:LinkButton ID="btnEdit" runat="server" CommandArgument='<%#Eval("Id") %>' οnclick="btnEdit_Click">编辑</asp:LinkButton>
                      
                    </ItemTemplate>
                   
                </asp:TemplateField>
                <asp:TemplateField HeaderText="操作">
                    <ItemTemplate>
                        <asp:LinkButton ID="btndelete" runat="server" CommandArgument='<%#Eval("Id") %>'  οnclick="btndelete_Click"  OnClientClick="return showinfo();">删除</asp:LinkButton>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="操作">
                    <ItemTemplate>
                        <asp:LinkButton ID="btnAdd" runat="server" οnclick="btnAdd_Click">添加</asp:LinkButton>
                    </ItemTemplate>
                </asp:TemplateField>
            </Columns>
        </asp:GridView>
        <table style="width: 40%;">
            <tr>
             <td>
                <asp:Button ID="btnFirst" runat="server" Text="第一页" οnclick="btnFirst_Click" />
            </td>
            <td>
                <asp:Button ID="btnPre" runat="server" Text="上一页" οnclick="btnPre_Click" />
            </td>
            <td>
                <asp:Button ID="btnNext" runat="server" Text="下一页" οnclick="btnNext_Click" />
            </td>
             <td>
                 <asp:Button ID="btnLast" runat="server" Text="最后一页" οnclick="btnLast_Click" />
            </td>
            <td>
            <asp:Button ID="btndelete2" runat="server" Text="删除" OnClientClick="return showinfo()" οnclick="btndelete2_Click" />
            </td>
            </tr>
           
        </table>

    </div>
    </form>
</body>
</html>

 

后台代码

 

 private void LoadData()
        {
            SqlConnection conn = new SqlConnection(constr);
            SqlCommand cmd = new SqlCommand();
            cmd.Connection = conn;
            conn.Open();
            //cmd.CommandText = "select T1.Id,T1.NewsTitle,SUBSTRING(T1.NewsContent,0,20)+'......' as NewsContent,T1.CreateTime,T2.ClassName,T3.RealName From T_News1 T1 inner join T_NewsClass T2 on T1.ClassId=T2.ClassId inner join T_User T3 on T1.NewsCreator=T3.UserId";
            //cmd.CommandText = "select * from (select ROW_NUMBER() over(order by T1.Id) as rownum,T1.Id,T1.NewsTitle,SUBSTRING(T1.NewsContent,0,20)+'......' as NewsContent,T1.CreateTime,T2.ClassName,T3.RealName From T_News1 T1 inner join T_NewsClass T2 on T1.ClassId=T2.ClassId inner join T_User T3 on T1.NewsCreator=T3.UserId)as A where A.rownum>(@pageIndex-1)* @pageSize and A.rownum<= @pageSize*@pageIndex";
            string sqlstr = "SELECT * FROM (SELECT ROW_NUMBER() OVER(ORDER BY T1.Id DESC)AS rownumber, T1.Id,T1.NewsTitle,SUBSTRING(T1.NewsContent,0,20)+'......' AS NewsContent,T1.CreateTime,T2.ClassName,T3.RealName  FROM T_News1 T1 INNER JOIN T_NewsClass T2 ON T1.ClassId=T2.ClassId INNER JOIN T_User T3 ON T1.NewsCreator=T3.UserId)A WHERE A.rownumber>(@pageindex-1)*@pagesize AND A.rownumber<=@pageindex*@pagesize";
            if (ViewState["sortexp"]!=null)
            {
                Dictionary<string, string> dic = ViewState["sortexp"] as Dictionary<string, string>;
                string sqlorder = string.Empty;
                foreach (KeyValuePair<string,string> item in dic)
                {
                    sqlorder += item.Key + " " + item.Value+",";
                }
                sqlstr=sqlstr+" ORDER BY "+sqlorder.TrimEnd(',');
            }
            cmd.CommandText = sqlstr;

           
            cmd.Parameters.Add(new SqlParameter("@pageindex", ViewState["pageindex"]));
            cmd.Parameters.Add(new SqlParameter("@pagesize", pagesize));
            SqlDataAdapter adapter = new SqlDataAdapter(cmd);
            DataTable dt = new DataTable();
            adapter.Fill(dt);
            GridView1.DataSource = dt;
            GridView1.DataBind();

        }

        protected void btnFirst_Click(object sender, EventArgs e)
        {
            ViewState["pageindex"] = 1;
            LoadData();
        }

        protected void btnPre_Click(object sender, EventArgs e)
        {
            int pageindex = Convert.ToInt32(ViewState["pageindex"]);
            if (pageindex <= Convert.ToInt32(ViewState["pagelastindex"]))
            {
                pageindex--;
                ViewState["pageindex"] = pageindex;
                LoadData();
            }
        }

        protected void btnNext_Click(object sender, EventArgs e)
        {
            int pageindex =Convert.ToInt32( ViewState["pageindex"]);
            if (pageindex < Convert.ToInt32(ViewState["pagelastindex"]))
            {
                pageindex++;
                ViewState["pageindex"] = pageindex;
                LoadData();
            }
        }

 

 

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
        {
           
            #region
            if (e.Row.RowType == DataControlRowType.Header)
            {
                for (int i = 0; i < e.Row.Cells.Count; i++)
                {
                    if (e.Row.Cells[i].Controls.Count > 0)
                    {
                        LinkButton link = e.Row.Cells[i].Controls[0] as LinkButton;
                        string sortexp = link.CommandArgument;
                        if (ViewState["sortexp"] != null)
                        {
                            Dictionary<string, string> dic = ViewState["sortexp"] as Dictionary<string, string>;
                            if (dic.ContainsKey(sortexp))
                            {
                                Literal li = new Literal();
                                if (dic[sortexp] == "ASC")
                                {
                                    li.Text = "↑";

                                }
                                else
                                {
                                    li.Text = "↓";
                                }
                                e.Row.Cells[i].Controls.Add(li);

                            }
                        }
                    }
                }
            }
            #endregion
            #region 分别计算出每一页中创建者为刘晓飞和肖维哲的新闻记录的数量
            if (e.Row.RowType == DataControlRowType.DataRow)
                {
                    if (e.Row.Cells[5].Text == "刘晓飞")
                    {
                        lcount++;
                    }
                    else if (e.Row.Cells[5].Text == "肖唯哲")
                    {
                        xcount++;
                    }
                }
            #endregion
            #region 在页脚显示新闻记录数量
            if (e.Row.RowType == DataControlRowType.Footer)
                {
                    e.Row.Cells[0].Text = string.Format("刘晓飞:{0},肖伟哲:{1}", lcount, xcount);
                    //合并单元格,就是删除多余的单元格,然后让剩下的单元格占据所有单元格的宽度之和
                    e.Row.Cells.RemoveAt(7);
                    e.Row.Cells.RemoveAt(6);
                    e.Row.Cells.RemoveAt(5);
                    e.Row.Cells.RemoveAt(4);
                    e.Row.Cells.RemoveAt(3);
                    e.Row.Cells.RemoveAt(2);
                    e.Row.Cells.RemoveAt(1);
                    e.Row.Cells[0].ColumnSpan = 8;
                    e.Row.Cells[0].HorizontalAlign = HorizontalAlign.Right;
                }
            #endregion
        }

        //选中多条删除
        protected void btndelete2_Click(object sender, EventArgs e)
        {
            string sqlid = string.Empty;
            foreach (GridViewRow row in this.GridView1.Rows)
            {
               CheckBox chek= row.Cells[0].FindControl("ck1") as CheckBox;
               if (chek.Checked == true)
               {
                   LinkButton link = row.Cells[6].FindControl("btnEdit") as LinkButton;
                   sqlid+= link.CommandArgument + ",";
                
               }
               if (DeleteNews(sqlid.TrimEnd(',')) > 0)
               {
                   ClientScript.RegisterStartupScript(this.GetType(), "aaa", "alert('删除成功')", true);
                   LoadData();
               }
            }
           
        }
        private int DeleteNews(string sqlid)
        {
            SqlConnection conn = new SqlConnection(constr);
            SqlCommand cmd = new SqlCommand();
            cmd.Connection = conn;
            //每次都显式打开
            conn.Open();
            cmd.CommandText = " DELETE FROM T_News1 WHERE Id IN(" + sqlid + ")";
            int totalcount = cmd.ExecuteNonQuery();
            cmd.Dispose();
            conn.Dispose();
            return totalcount;
        }
      
    }

 


protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
        {
           
            #region
            if (e.Row.RowType == DataControlRowType.Header)
            {
                for (int i = 0; i < e.Row.Cells.Count; i++)
                {
                    if (e.Row.Cells[i].Controls.Count > 0)
                    {
                        LinkButton link = e.Row.Cells[i].Controls[0] as LinkButton;
                        string sortexp = link.CommandArgument;
                        if (ViewState["sortexp"] != null)
                        {
                            Dictionary<string, string> dic = ViewState["sortexp"] as Dictionary<string, string>;
                            if (dic.ContainsKey(sortexp))
                            {
                                Literal li = new Literal();
                                if (dic[sortexp] == "ASC")
                                {
                                    li.Text = "↑";

                                }
                                else
                                {
                                    li.Text = "↓";
                                }
                                e.Row.Cells[i].Controls.Add(li);

                            }
                        }
                    }
                }
            }
            #endregion
            #region 分别计算出每一页中创建者为刘晓飞和肖维哲的新闻记录的数量
            if (e.Row.RowType == DataControlRowType.DataRow)
                {
                    if (e.Row.Cells[5].Text == "刘晓飞")
                    {
                        lcount++;
                    }
                    else if (e.Row.Cells[5].Text == "肖唯哲")
                    {
                        xcount++;
                    }
                }
            #endregion
            #region 在页脚显示新闻记录数量
            if (e.Row.RowType == DataControlRowType.Footer)
                {
                    e.Row.Cells[0].Text = string.Format("刘晓飞:{0},肖伟哲:{1}", lcount, xcount);
                    //合并单元格,就是删除多余的单元格,然后让剩下的单元格占据所有单元格的宽度之和
                    e.Row.Cells.RemoveAt(7);
                    e.Row.Cells.RemoveAt(6);
                    e.Row.Cells.RemoveAt(5);
                    e.Row.Cells.RemoveAt(4);
                    e.Row.Cells.RemoveAt(3);
                    e.Row.Cells.RemoveAt(2);
                    e.Row.Cells.RemoveAt(1);
                    e.Row.Cells[0].ColumnSpan = 8;
                    e.Row.Cells[0].HorizontalAlign = HorizontalAlign.Right;
                }
            #endregion
        }

        //选中多条删除
        protected void btndelete2_Click(object sender, EventArgs e)
        {
            string sqlid = string.Empty;
            foreach (GridViewRow row in this.GridView1.Rows)
            {
               CheckBox chek= row.Cells[0].FindControl("ck1") as CheckBox;
               if (chek.Checked == true)
               {
                   LinkButton link = row.Cells[6].FindControl("btnEdit") as LinkButton;
                   sqlid+= link.CommandArgument + ",";
                
               }
               if (DeleteNews(sqlid.TrimEnd(',')) > 0)
               {
                   ClientScript.RegisterStartupScript(this.GetType(), "aaa", "alert('删除成功')", true);
                   LoadData();
               }
            }
           
        }
        private int DeleteNews(string sqlid)
        {
            SqlConnection conn = new SqlConnection(constr);
            SqlCommand cmd = new SqlCommand();
            cmd.Connection = conn;
            //每次都显式打开
            conn.Open();
            cmd.CommandText = " DELETE FROM T_News1 WHERE Id IN(" + sqlid + ")";
            int totalcount = cmd.ExecuteNonQuery();
            cmd.Dispose();
            conn.Dispose();
            return totalcount;
        }
      
    }

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值