GridView的简单用法(分页,编辑,删除,选中删除)

用法包含分页,编辑,删除,选中删除等

前台:

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


<!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>
        <table>
        <tr><td>
            <asp:LinkButton ID="btnAdd" runat="server" onclick="btnAdd_Click">添加</asp:LinkButton>
            <asp:Button ID="btnDelete" runat="server" Text="删除" 
                onclick="btnDelete_Click1" />
            </td></tr>
            <tr>
                <td>
                    <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:TemplateField HeaderText="标题">
                                <ItemTemplate>
                                    <a href='WebShowXx.aspx?id=<%# Eval("Id") %>'><%# Eval("NewsTitle") %></a>
                                </ItemTemplate>
                            </asp:TemplateField>
                            <asp:BoundField DataField="NewsContent" HeaderText="内容" />
                            <asp:BoundField DataField="RealName" HeaderText="创建者" 
                                SortExpression="RealName" />
                            <asp:BoundField DataField="CreateTime" DataFormatString="{0:yyyy-MM-dd hh:mm:ss}"
                                HeaderText="创建时间" SortExpression="CreateTime" />
                            <asp:BoundField DataField="ClassName" HeaderText="类别" />
                            <asp:TemplateField HeaderText="操作">
                                <ItemTemplate>
                                    <asp:LinkButton ID="btnEdit" runat="server" CommandArgument='<%#Eval("Id") %>' onclick="btnEdit_Click">编辑</asp:LinkButton>
                                </ItemTemplate>
                            </asp:TemplateField>
                            <asp:TemplateField HeaderText="操作">
                                <ItemTemplate>
                                    <asp:LinkButton ID="btnDelete" CommandArgument='<%#Eval("Id") %>' 
                                        runat="server" onclick="btnDelete_Click" OnClientClick="return showinfo();">删除</asp:LinkButton>
                                </ItemTemplate>
                            </asp:TemplateField>
                        </Columns>
                    </asp:GridView>
                </td>
            </tr>
            <tr>
                <td>
                    <asp:LinkButton ID="btnFirst" runat="server" onclick="btnFirst_Click">第一页</asp:LinkButton>
                    <asp:LinkButton ID="btnPre" runat="server" onclick="btnPre_Click">上一页</asp:LinkButton>
                    <asp:LinkButton ID="btnNext" runat="server" onclick="btnNext_Click">下一页</asp:LinkButton>
                    <asp:LinkButton ID="btnLast" runat="server" onclick="btnLast_Click" >最后一页</asp:LinkButton>
                </td>
            </tr>
        </table>


    </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.SqlClient;
using System.Data;
using System.Drawing;


namespace GridWive
{
    public partial class grid : System.Web.UI.Page
    {
        #region 定义变量
        int pagesize = 20;
        int num1 = 0;   //定义变量,为了下面计算出每页某人的新闻条数
        int num2 = 0;   //定义变量,为了下面计算出每页某人的新闻条数
        #endregion
        
        protected void Page_Load(object sender, EventArgs e)
        {
            if (IsPostBack == false)
            {
                ViewState["pageindex"] = 1;
                GetCount();
                LoadData();
            }
        }


        private void GetCount()
        {
            string strcon = @"Data Source=PC-DLL;Initial Catalog=News;Persist Security Info=True;User ID=sa;Password=linlin";
            SqlConnection conn = new SqlConnection(strcon);
            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 COUNT(*) FROM T_News1";
            int totalcount = Convert.ToInt32(cmd.ExecuteScalar());
            cmd.Dispose();
            conn.Dispose();


            if (totalcount % pagesize == 0)
            {
                ViewState["pagelastindex"] = totalcount / pagesize;
            }
            else
            {
                ViewState["pagelastindex"] = totalcount / pagesize + 1;
            }
        }


        private void LoadData()
        {
            string strcon = @"Data Source=PC-DLL;Initial Catalog=News;Persist Security Info=True;User ID=sa;Password=linlin";
            SqlConnection conn = new SqlConnection(strcon);
            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";
             
            string sqlstr="  SELECT * FROM (SELECT ROW_NUMBER() OVER(ORDER BY T1.Id)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.AddWithValue("@pageindex", ViewState["pageindex"]);
            cmd.Parameters.AddWithValue("@pagesize", pagesize);
            SqlDataAdapter adapter = new SqlDataAdapter(cmd);
            DataTable dt = new DataTable();
            adapter.Fill(dt);
            cmd.Dispose();
            conn.Dispose();
            //将查询出来的数据绑定到GridView
            //原来需要手动拼接字符串的工作由GridView代劳了
            this.GridView1.DataSource = dt;
            //DataBind负责拼接字符串
            this.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 > 1)
            {
                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 btnLast_Click(object sender, EventArgs e)
        {
            ViewState["pageindex"] = ViewState["pagelastindex"];
            LoadData();
        }


        protected void btnEdit_Click(object sender, EventArgs e)
        {
            LinkButton btnEdit=sender as LinkButton;    //获取点击的那行的id
            Response.Redirect("WebEdit.aspx?id=" + btnEdit.CommandArgument);
        }


        protected void btnDelete_Click(object sender, EventArgs e)
        {
            LinkButton btnDelete = sender as LinkButton;
            string strcon = @"Data Source=PC-DLL;Initial Catalog=News;Persist Security Info=True;User ID=sa;Password=linlin";
            SqlConnection conn = new SqlConnection(strcon);
            SqlCommand cmd = new SqlCommand();
            cmd.Connection = conn;
            conn.Open();
            cmd.CommandText = "Delete FROM T_News1 WHERE Id=@id ";
            cmd.Parameters.AddWithValue("@id",btnDelete.CommandArgument);
            if (cmd.ExecuteNonQuery()>0)
            {
                LoadData();
            }
            
            cmd.Dispose();
            conn.Dispose();
        }


        protected void btnAdd_Click(object sender, EventArgs e)
        {
            Response.Redirect("WeAdd.aspx");
        }


        protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
        {
            //判断用户点击了哪个排序字段
            //说明用户第一次点击排序字段
            if (ViewState["sortexp"] == null)
            {
                Dictionary<string, string> dic = new Dictionary<string, string>();
                dic.Add(e.SortExpression, "ASC");
                ViewState["sortexp"] = dic;
            }
            else//用户第二次或者次点击排序字段
            {
                Dictionary<string, string> dic = ViewState["sortexp"] as Dictionary<string, string>;
                //判断用户本次点击的排序字段是否和上次点击的排序字段一致,如果一致的话,那么就更改此字段的排序规则,如果不是就清除上次的排序字段,添加新的排序字段和规则(这是根据一个字段排序的情况)
                if (dic.ContainsKey(e.SortExpression))
                {
                    //如果上次是升序,则改为降序,如果是降序则改为升序
                    if (dic[e.SortExpression] == "ASC")
                    {
                        dic[e.SortExpression] = "DESC";
                    }
                    else
                    {
                        dic[e.SortExpression] = "ASC";
                    }
                    //ViewState["sortexp"] = dic;
                }
                else//清除上次排序字段和规则,添加新的排序字段和规则
                {
                    //dic.Clear();
                    dic.Add(e.SortExpression, "ASC");
                    //ViewState["sortexp"] = dic;
                }
            }
            //重新加载数据
            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)
            {
                for (int i = 0; i < e.Row.Cells.Count; i++)
                {
                    if (e.Row.Cells[3].Text == "刘晓飞")
                    {
                        e.Row.BackColor = Color.DarkOrange;
                    }
                }
            } 
            #endregion


            #region 分别计算出每一页刘晓飞和肖伟哲新闻记录的条数
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                if (e.Row.Cells[3].Text == "刘晓飞")
                    {
                        num1++;
                        //Response.Write(num1);
                    }
                    else if (e.Row.Cells[3].Text == "肖唯哲")
                    {
                        num2++;
                        //Response.Write(num2);
                    }
            }
            //将最后结果输出到页脚
            if (e.Row.RowType==DataControlRowType.Footer)
            {
                //合并单元格,就是删除多余的单元格,然后让剩下的单元格占所有单元格的宽度之和
                e.Row.Cells[0].Text = string.Format("刘晓飞{0},肖唯哲{1}", num1, num2);
                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;     //合并8列
                e.Row.Cells[0].HorizontalAlign = HorizontalAlign.Center;    //让文字的在中间显示
            }
            #endregion
        }


        protected void btnDelete_Click1(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)
            {
                LoadData();
            }
        }


        private int DeleteNews(string sqlid)
        {
            string strcon = @"Data Source=PC-DLL;Initial Catalog=News;Persist Security Info=True;User ID=sa;Password=linlin";
            SqlConnection conn = new SqlConnection(strcon);
            SqlCommand cmd = new SqlCommand();
            cmd.Connection = conn;
            conn.Open();
            cmd.CommandText = " DELETE FROM T_News1 WHERE Id IN(" + sqlid + ")";
            int totle=cmd.ExecuteNonQuery();
            cmd.Dispose();
            conn.Dispose();
            return totle;
        }


    }
}

原文地址:https://www.cnblogs.com/duanlinlin/p/2994387.html