GridView的使用

前台代码:

<head runat="server">

<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title>用户信息管理系统</title>
    <style>
.Freezing
   {
   
   position:relative ;
   table-layout:fixed;
   top:expression(this.offsetParent.scrollTop);  
   z-index: 10;
   }


.Freezing th{text-overflow:ellipsis;overflow:hidden;white-space: nowrap;padding:2px;}
p{
    color:red;
   
    text-align:center;
}


</style>
</head>
<body style="background-color: #FFE4CA;">
    <div>
   
        <div id="header_index">
            <img src="img/shan.png" width="100%" height="10%" />
        </div>
        <hr />
        <div align="center"> <form id="form2" runat="server">
            <asp:GridView ID="GridView2" runat="server" AllowPaging="True" AllowSorting="True" PageSize="5" AutoGenerateColumns="False" DataKeyNames="ID"
                border="3"
                OnPageIndexChanging="GridView2_PageIndexChanging"
                OnRowDeleting="GridView2_RowDeleting"
                OnRowEditing="GridView2_RowEditing"
                OnRowUpdating="GridView2_RowUpdating"
                OnRowCancelingEdit="GridView2_RowCancelingEdit"
                OnRowDataBound="GridView2_Bianhua"
                OnSorting="GridView2_Sorting">


                <Columns>
                    <asp:BoundField DataField="ID" HeaderText="序号" InsertVisible="False" ReadOnly="True" SortExpression="ID" />
                    <asp:BoundField DataField="name"  HeaderText="姓名" />
                    <asp:BoundField DataField="pwd" HeaderText="密码"/>
                    <asp:BoundField DataField="age" HeaderText="年龄" SortExpression="age" />
                    <asp:BoundField DataField="sex" HeaderText="性别" />
                    <asp:BoundField DataField="ph" HeaderText="手机号" />
                    <asp:CommandField HeaderText="更新" ShowEditButton="True" />
                    <asp:CommandField HeaderText="删除" ShowDeleteButton="True"/>


                </Columns>
                <RowStyle ForeColor="#00008B" />
                <SelectedRowStyle BackColor="#669999" Font-Bold="True" ForeColor="#FFB6C1" />
                <PagerStyle BackColor="White" ForeColor="#750000" />
                <HeaderStyle BackColor="#006699" Font-Bold="True" ForeColor="White" CssClass="Freezing" />
            </asp:GridView>
            
            <asp:LinkButton ID="lbnFirst" runat="Server" Text="首页" CommandName="Page" CommandArgument="First" OnClick="lbnFirst_Click"></asp:LinkButton>
            <asp:LinkButton ID="lbnPrev" runat="server" Text="上一页" CommandName="Page" CommandArgument="Prev" OnClick="lbnPrev_Click"></asp:LinkButton>
            <asp:LinkButton ID="lbnNext" runat="Server" Text="下一页" CommandName="Page" CommandArgument="Next" OnClick="lbnNext_Click"></asp:LinkButton>
            <asp:LinkButton ID="lbnLast" runat="Server" Text="末页" CommandName="Page" CommandArgument="Last" OnClick="lbnLast_Click"></asp:LinkButton>
            <p>
                <asp:Label ID="lblCurrentIndex" runat="server" Text="第 1 页"></asp:Label>
                <asp:Label ID="lblPageCount" runat="server" Text=""></asp:Label>
                <asp:Label ID="lblRecordCount" runat="server" Text=""></asp:Label>
                <asp:TextBox ID="txtJumpPage" runat="server" Width="24px">1</asp:TextBox>
                <asp:LinkButton ID="lnkbtnJumpPage" runat="server" OnClick="lnkbtnJumpPage_Click">跳转</asp:LinkButton>
            </p> </form>
         
        </div>
        <hr />
          <div id="footer" style="background-color:#C0C0C0"><p>Copyright@濮阳富起建筑机械租赁销售</p></div>
      
   
        </div>
</body>

</html>

后台代码:

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
using System.Text; 
public partial class GridView1 : System.Web.UI.Page
{
    string str = ConfigurationManager.ConnectionStrings["DataConnectStr"].ConnectionString;
    string sqlstr = "select * from person2";
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            bind();
        }
    }
    public void bind()
    {
        //将数据部署到GridView中
        string sqlstr = "select * from person2";
        SqlConnection con = new SqlConnection(str);
        SqlDataAdapter ad = new SqlDataAdapter(sqlstr, con);
        DataSet ds = new DataSet();
        ad.Fill(ds, "person2");
       GridView2.DataSource = ds;
       GridView2.DataBind();
       lblPageCount.Text = "共 " + this.GridView2.PageCount.ToString() + " 页";
       lblRecordCount.Text = "总共 " + ds.Tables[0].Rows.Count + " 条";
    }
    //编辑
    protected void GridView2_RowEditing(object sender, GridViewEditEventArgs e)
    {
        GridView2.EditIndex = e.NewEditIndex;
        bind();
    }
    //删除
    protected void GridView2_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
         string sqlstr = "delete from person2 where ID='" + GridView2.DataKeys[e.RowIndex].Value.ToString() + "'";
        
        SqlConnection sqlcon = new SqlConnection(str);
        SqlCommand sqlcom = new SqlCommand(sqlstr, sqlcon);
        sqlcon.Open();
        sqlcom.ExecuteNonQuery();
        sqlcon.Close();
        bind();
    }
    //取消
    protected void GridView2_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
    {
        GridView2.EditIndex = -1;
        bind();
    }
    //更新
    protected void GridView2_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
        SqlConnection sqlcon = new SqlConnection(str);
        string sqlstr = "update person2 set name='"
            + ((TextBox)(GridView2.Rows[e.RowIndex].Cells[2].Controls[0])).Text + "',pwd='"
            + ((TextBox)(GridView2.Rows[e.RowIndex].Cells[3].Controls[0])).Text + "',age='"
            + ((TextBox)(GridView2.Rows[e.RowIndex].Cells[4].Controls[0])).Text + "',sex='"
            + ((TextBox)(GridView2.Rows[e.RowIndex].Cells[5].Controls[0])).Text + "', ph='"
            + ((TextBox)(GridView2.Rows[e.RowIndex].Cells[6].Controls[0])).Text + "'where ID=" +
            Convert.ToInt32(GridView2.DataKeys[e.RowIndex].Value);
        SqlCommand sqlcom = new SqlCommand(sqlstr, sqlcon);
        sqlcon.Open();
        sqlcom.ExecuteNonQuery();
        sqlcon.Close();
        GridView2.EditIndex = -1;
        bind();
    }
//排序
//在这里,接收两个参数,分别是sortExpression和direction,然后构成dataview进行排序。
    protected void GridView2_Sorting(object sender, GridViewSortEventArgs e)
    {
        if (ViewState["SortDirection"] == null)
            ViewState["SortDirection"] = "DESC";
        if (ViewState["SortDirection"].ToString() == "ASC")
            ViewState["SortDirection"] = "DESC";
        else
            ViewState["SortDirection"] = "ASC";
        ViewState["SortExpression"] = e.SortExpression;
        this.bindgrid();
    }
    protected void bindgrid()
    {
        string sqlconnstr = ConfigurationManager.ConnectionStrings["DataConnectStr"].ConnectionString;
        DataSet ds = new DataSet();
        using (SqlConnection sqlconn = new SqlConnection(sqlconnstr))
        {
            SqlDataAdapter sqld = new SqlDataAdapter("select * from person2", sqlconn);
            sqld.Fill(ds, "person2");
        }
        //判断是否已经进行排序,如果是则按照ViewState中存储的信息生成排序后的DataView对象  
       if (ViewState["SortDirection"] == null)
            GridView2.DataSource = ds.Tables["person2"].DefaultView;
        else
        {
            DataView SortedDV = new DataView(ds.Tables["person2"]);
            SortedDV.Sort = ViewState["SortExpression"].ToString() + " " +
            ViewState["SortDirection"].ToString();
            GridView2.DataSource = SortedDV;
        }
        GridView2.DataBind();
    }


    //第几页  
    protected void lnkbtnJumpPage_Click(object sender, EventArgs e)  
    {
       
         GridView2.PageIndex = int.Parse(txtJumpPage.Text) - 1; 
        if (GridView2.PageIndex < GridView2.PageCount)
        {
            lblCurrentIndex.Text = "第 " + (GridView2.PageIndex+1).ToString() + " 页";
        }
        else
        {


            lblCurrentIndex.Text = "不存在";
        }
        bind();
  
    }
    //点击数据表中的1、2、3、......发生的变化
    protected void GridView2_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        GridView2.PageIndex = e.NewPageIndex;
        bind();
    } 
    //鼠标到行的颜色变化
    protected void GridView2_Bianhua(object sender, GridViewRowEventArgs e)
    {
      int i;
        //执行循环,保证每条数据都可以更新
        for (i = 0; i < GridView2.Rows.Count + 1; i++)
        {
            //首先判断是否是数据行
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                //当鼠标停留时更改背景色
                e.Row.Attributes.Add("onmouseover", "c=this.style.backgroundColor;this.style.backgroundColor='#00A9FF'");
                //当鼠标移开时还原背景色
                e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor=c");
            }
        }
       
    }
    //首页
    protected void lbnFirst_Click(object sender, EventArgs e)
    {
        this.GridView2.PageIndex = 0;
        bind();


    }
    //上一页
    protected void lbnPrev_Click(object sender, EventArgs e)
    {
        if (this.GridView2.PageIndex > 0)
        {
            this.GridView2.PageIndex = this.GridView2.PageIndex - 1;
            bind();
        }
    }
    //下一页
    protected void lbnNext_Click(object sender, EventArgs e)
    {
        if (this.GridView2.PageIndex < this.GridView2.PageCount)
        {
            this.GridView2.PageIndex = this.GridView2.PageIndex + 1;
            bind();
        }
    }
    //尾页
    protected void lbnLast_Click(object sender, EventArgs e)
    {
        this.GridView2.PageIndex = this.GridView2.PageCount;
        bind();
    }
}
   

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

陈善强

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值