GridView用法

public partial class WebForm1 : System.Web.UI.Page
    {
        int lcount=0;
        int xcount=0;
        int pagesize = 20;
        protected void Page_Load(object sender, EventArgs e)
        {
            if (IsPostBack == false)
            {
                ViewState["pageindex"] = 1;
                GetCount();
                LoadData();
            }
        }
        private void GetCount()//计算条数的
        {
            string str = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
            SqlConnection conn = new SqlConnection(str);
            SqlCommand cmd = new SqlCommand();
            cmd.Connection = conn;
            conn.Open();
            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 str = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
            SqlConnection conn = new SqlConnection(str);
            SqlCommand cmd = new SqlCommand();
            cmd.Connection = conn;
            conn.Open();
            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 left JOIN T_NewsClass T2 ON T1.ClassId=T2.ClassId left JOIN T_User T3 ON T1.NewsCreator=T3.UserId)A WHERE A.rownumber>(@pageindex-1)*@pagesize AND A.rownumber<=@pageindex*@pagesize";
         
            if (ViewState["sort"] != null)
            {
                Dictionary<string, string> dic = ViewState["sort"] 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();
            this.GridView1.DataSource = dt;
            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;
                Response.Redirect("WebForm2.aspx?id="+btnedit.CommandArgument);
            }

            protected void btndelete_Click(object sender, EventArgs e)//删除
            {
                LinkButton btnedit = sender as LinkButton;
                string str = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
                SqlConnection conn = new SqlConnection(str);
                conn.Open();
                SqlCommand cmd = new SqlCommand();
                cmd.Connection = conn;
                cmd.CommandText = "delete from T_News1 where Id=@id";
                cmd.Parameters.AddWithValue("@id", btnedit.CommandArgument);
                if (cmd.ExecuteNonQuery()>0)
                {
                    //删除之后加载页面后 让用户看到最新的变化
                    LoadData();
               
                }
                cmd.Dispose();
                conn.Dispose();

            }

            protected void LinkButton1_Click(object sender, EventArgs e)
            {
                Response.Redirect("WebAdd3.aspx");
            }//添加

            protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)//排序
            {
                #region  排序
                if (ViewState["sort"] == null)
                {
                    Dictionary<string, string> dic = new Dictionary<string, string>();
                    dic.Add(e.SortExpression, "ASC");
                    ViewState["sort"] = dic;
                }
                else
                {
                    Dictionary<string, string> dic = ViewState["sort"] as Dictionary<string, string>;
                    if (dic.ContainsKey(e.SortExpression))
                    {
                        if (dic[e.SortExpression] == "ASC")
                        {
                            dic[e.SortExpression] = "DESC";
                        }
                        else
                        {
                            dic[e.SortExpression] = "ASC";
                        }
                    }
                    else
                    {
                        dic.Add(e.SortExpression,"ASC");
                    }

                }
                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["sort"] != null)
                            {
                                Dictionary<string, string> dic = ViewState["sort"] 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[3].Text == "刘晓飞")
                    {
                        e.Row.BackColor = Color.Bisque;
                    }
                }

                #endregion
             

                if (e.Row.RowType == DataControlRowType.DataRow)
                {
                    if (e.Row.Cells[3].Text == "刘晓飞")
                    {
                        lcount++;
                    }
                    else if (e.Row.Cells[3].Text == "张东")
                    {
                        xcount++;

                    }
                }
                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 LinkButton2_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 = sqlid + link.CommandArgument + ",";
                    }
                }
                if (DeleteNews(sqlid.TrimEnd(',')) > 0)
                {
                    ClientScript.RegisterStartupScript(this.GetType(), "information", "alert('删除成功')", true);
                    LoadData();
                }

             
            }
            private int DeleteNews(string sqlid)
            {
                string strcon = @"Data Source=.;Initial Catalog=News;Persist Security Info=True;User ID=sa;Password=910809";
                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 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、付费专栏及课程。

余额充值