包含有

数据的编辑,删除,

标题的添加,自定义分页,高亮显示鼠标所在,以及数据不足时添加空行

aspx页面代码

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" OnRowCancelingEdit="GridView1_RowCancelingEdit" OnRowEditing="GridView1_RowEditing" BackColor="White" BorderColor="White" BorderStyle="Ridge" BorderWidth="2px" CellPadding="3" CellSpacing="1" GridLines="None" OnRowDataBound="GridView1_RowDataBound" OnRowUpdating="GridView1_RowUpdating" Width="945px" AllowPaging="True" OnPageIndexChanged="GridView1_PageIndexChanged" OnPageIndexChanging="GridView1_PageIndexChanging" OnRowCreated="GridView1_RowCreated" OnRowDeleting="GridView1_RowDeleting" OnDataBound="GridView1_DataBound" OnRowCommand="GridView1_RowCommand">
            <Columns>
                <asp:BoundField DataField="stuid" HeaderText="学号" />
                <asp:BoundField DataField="stuname" HeaderText="姓名" />
                <asp:BoundField DataField="majorid" HeaderText="专业编号" />
                <asp:BoundField DataField="sex" HeaderText="性别" />
                <asp:BoundField DataField="birthdate" HeaderText="出生日期" />
                <asp:BoundField DataField="credit" HeaderText="总学分" />
                <asp:BoundField DataField="remark" HeaderText="备注" />
                <asp:CommandField HeaderText="操作" ShowEditButton="True" ShowDeleteButton="True" />
            </Columns>
            <FooterStyle BackColor="#C6C3C6" ForeColor="Black" />
            <HeaderStyle BackColor="#4A3C8C" Font-Bold="True" ForeColor="#E7E7FF" />
            <PagerStyle BackColor="#C6C3C6" ForeColor="Black" HorizontalAlign="Right" />
            <RowStyle BackColor="#DEDFDE" ForeColor="Black" />
            <SelectedRowStyle BackColor="#9471DE" Font-Bold="True" ForeColor="White" />
            <SortedAscendingCellStyle BackColor="#F1F1F1" />
            <SortedAscendingHeaderStyle BackColor="#594B9C" />
            <SortedDescendingCellStyle BackColor="#CAC9C9" />
            <SortedDescendingHeaderStyle BackColor="#33276A" />
            <PagerTemplate>
                <table>
                    <tr><td>
                        第<asp:Label ID="lblPageIndex" runat="server" Text="<%#((GridView)Container.Parent.Parent).PageIndex+1 %>"></asp:Label>页
                        共<asp:Label ID="lblPageCount" runat="server" Text="<%#((GridView)Container.Parent.Parent).PageCount %>"></asp:Label>页
                        <asp:LinkButton ID="btnFirst" runat="server" CausesValidation="false" CommandArgument="First" CommandName="Page">首页</asp:LinkButton>
                        <asp:LinkButton ID="btnPrev" runat="server" CausesValidation="false" CommandArgument="Prev" CommandName="Page">上一页</asp:LinkButton>
                        <asp:LinkButton ID="btnNext" runat="server" CausesValidation="false" CommandArgument="Next" CommandName="Page">下一页</asp:LinkButton>
                        <asp:LinkButton ID="btnLast" runat="server" CausesValidation="false" CommandArgument="Last" CommandName="Page">尾页</asp:LinkButton>
                        到<asp:DropDownList ID="listPageCount" runat="server" AutoPostBack="true" Width="50"></asp:DropDownList>
                        <asp:LinkButton ID="btnGo" runat="server" CausesValidation="false" CommandName="Go">Go</asp:LinkButton></td>
                    </tr>
                </table>
            </PagerTemplate>  
        </asp:GridView>

以下是后台代码:---------------------------------------------------------------------------------------------------------------------------------------------------------

protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            GridView1.PageSize = 6;
            GridView1.Columns[0].Visible = false;
            GridView1.PagerSettings.Mode = PagerButtons.NumericFirstLast;
            GridView1.PagerSettings.PageButtonCount = 4;
            // 页数居中显示
            GridView1.PagerStyle.HorizontalAlign = HorizontalAlign.Center;
            DataGridBind();
        }
    }
    string connStr = ConfigurationManager.ConnectionStrings["Key"].ToString();

// 数据绑定
    private void DataGridBind()
    {
        string sql = "select * from student";
        using (SqlConnection conn = new SqlConnection(connStr))
        {
            SqlCommand cmd = new SqlCommand(sql,conn);
            SqlDataAdapter sda = new SqlDataAdapter(cmd);
            conn.Close();
            DataSet ds = new DataSet();
            sda.Fill(ds);
            GridView1.DataSource = ds.Tables[0];
            GridView1.DataKeyNames = new string[] { "stuid" };
            GridView1.Columns[1].ItemStyle.Width=80;
            GridView1.Columns[2].ItemStyle.Width = 80;
            GridView1.Columns[3].ItemStyle.Width = 40;
            GridView1.Columns[4].ItemStyle.Width = 200;
            GridView1.Columns[5].ItemStyle.Width = 60;
            GridView1.Columns[6].ItemStyle.Width = 250;
            GridView1.Columns[7].ItemStyle.Width = 100;
            GridView1.DataBind();
        }
    }

// 编辑事件
    protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
    {
        GridView1.EditIndex = e.NewEditIndex;
        DataGridBind();
    }
    // 取消编辑
    protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
    {
        GridView1.EditIndex = -1;
        DataGridBind();
    }
    // 更新
    protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
        string stuid = GridView1.DataKeys[e.RowIndex].Value.ToString();
        string stuname = ((TextBox)(GridView1.Rows[e.RowIndex].Cells[1].Controls[0])).Text.ToString();
        int majorid = Convert.ToInt32(((TextBox)(GridView1.Rows[e.RowIndex].Cells[2].Controls[0])).Text.ToString());
        string sex = ((TextBox)(GridView1.Rows[e.RowIndex].Cells[3].Controls[0])).Text.ToString();
        DateTime Birthdate = Convert.ToDateTime(((TextBox)(GridView1.Rows[e.RowIndex].Cells[4].Controls[0])).Text.ToString());
        float credit = Convert.ToSingle(((TextBox)(GridView1.Rows[e.RowIndex].Cells[5].Controls[0])).Text.ToString());
        string remark = ((TextBox)(GridView1.Rows[e.RowIndex].Cells[6].Controls[0])).Text.ToString();
        SqlConnection conn = new SqlConnection(connStr);
        SqlParameter[] paras = {new SqlParameter("@stuid",stuid),
                                new SqlParameter("@stuname",stuname),
                                new SqlParameter("@majorid",majorid),
                                new SqlParameter("@sex",sex),
                                new SqlParameter("@birthdate",Birthdate),
                                new SqlParameter("@credit",credit),
                                new SqlParameter("@remark",remark)};
        string sql = @"update student set stuname=@stuname,majorid=@majorid,sex=@sex,
        birthdate=@birthdate,credit=@credit,remark=@remark where stuid=@stuid";
        conn.Open();
        SqlCommand cmd = new SqlCommand(sql, conn);
        foreach (SqlParameter para in paras)
        {
            cmd.Parameters.Add(para);
        }
        cmd.ExecuteNonQuery();
        cmd.Dispose();
        conn.Close();
        GridView1.EditIndex = -1;
        DataGridBind();
    }

// 高亮显示鼠标所在的行
    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            e.Row.Attributes.Add("onmouseover", "currentcolor=this.style.backgroundColor;this.style.backgroundColor='#6699ff';");
            e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor=currentcolor;");
            LinkButton linBtn = (LinkButton)(e.Row.Cells[7].Controls[2]);
            if (linBtn.Text == "删除")
            {
                linBtn.Attributes.Add("onclick", "return confirm('你确定要删除吗?')");
            }
        }
    }
    // 删除
    protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        string stuid = GridView1.DataKeys[e.RowIndex].Value.ToString();
        string sql = "delete from student where stuid=" + stuid;
        SqlConnection conn = new SqlConnection(connStr);
        SqlCommand cmd = new SqlCommand(sql, conn);
        conn.Open();
        cmd.ExecuteNonQuery();
        cmd.Dispose();
        conn.Close();
        DataGridBind();
    }

// 分页
    protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        if (e.NewPageIndex < 0)
        {
            GridView1.PageIndex = 0;
        }
        else
        {
            GridView1.PageIndex = e.NewPageIndex;
        }
    }
    protected void GridView1_PageIndexChanged(object sender, EventArgs e)
    {
        DataGridBind();
    }

// 行创建时
    protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
    {

// 添加标题
        if (e.Row.RowType == DataControlRowType.Header)
        {
            GridViewRow gvr = new GridViewRow(0, 0, DataControlRowType.Header, DataControlRowState.Normal);
            Literal lit = new Literal();
            lit.Text = @"<td colspan='6' align='center'><h2>学生信息</h2></td>";
            TableHeaderCell thc = new TableHeaderCell();
            thc.Controls.Add(lit);
            gvr.Cells.Add(thc);
            GridView1.Controls[0].Controls.AddAt(0, gvr);
        }

// 本页行数不足添加空行
        int count = 0;
        count = GridView1.Rows.Count;
        if (e.Row.RowType == DataControlRowType.Footer)
        {
            int rowCount = GridView1.PageSize - count;
            int colCount = GridView1.Rows[0].Cells.Count;
            for (int i = 0; i < rowCount; i++)
            {
                GridViewRow row = new GridViewRow(-1, -1, DataControlRowType.DataRow, DataControlRowState.Normal);
                for (int j = 0; j < colCount - 1; j++)
                {
                    TableCell cell = new TableCell();
                    cell.Text = "&nbsp";
                    row.Cells.Add(cell);
                }
                GridView1.Controls[0].Controls.AddAt(count +2, row);
            }
        }
    }

// 控件被数据绑定后
    protected void GridView1_DataBound(object sender, EventArgs e)
    {
        DropDownList list = (DropDownList)GridView1.BottomPagerRow.FindControl("listPageCount");
        for (int i = 1; i <= GridView1.PageCount; i++)
        {
            ListItem item = new ListItem(i.ToString());
            if (i==GridView1.PageIndex+1)
            {
                item.Selected = true;
            }
            list.Items.Add(item);
        }
    }
    // 响应跳转事件
    protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName=="Go")
        {
            DropDownList list = (DropDownList)GridView1.BottomPagerRow.FindControl("listPageCount");
            GridViewPageEventArgs arg = new GridViewPageEventArgs(list.SelectedIndex);
            GridView1_PageIndexChanging(null, arg);
            GridView1_PageIndexChanged(null, null);
        }
    }

刚刚开通博客,分享Asp.Net的GridView的基本用法的更多相关文章

  1. 开通博客啦 Let‘s Go!

    入园两年半,在博客园学到很多知识.得到了很大帮助,今天终于开通博客啦,准备将自己所学到的有用知识分享给大家,共同学习共同进步.

  2. hello word!------为什么开通博客以及自我介绍

    来北京已经一年半的日子了,已经完全成功熟练的成为了另一个我,没有了半年前刚来时的那种焦虑.急躁和格格不入. 回想起来那段时间,大概是我人生中非常重要的时期了,去年那个夏天,只身一人背上行囊踏上了北上的 ...

  3. SQL Server 学习博客分享列表(应用式学习 + 深入理解)

    SQL Server 学习博客分享列表(应用式学习 + 深入理解) 转自:https://blog.csdn.net/tianjing0805/article/details/75047574 SQL ...

  4. 我在CSDN开通博客啦!

    今天,我最终在CSDN开通博客啦! 

  5. 开通博客第一天,记录此时此刻,开始学习加强c#

    从2017年6月毕业到现在,不断的学习.net,在工作中不断的加强技术,终于在此时此刻决定开通博客,记录此后每一天学习的技术点,两年来,每天所涉及的技术点很杂,学了这个忘了那个,总感觉在进步却总是觉得 ...

  6. 在CSDN开通博客专栏后如何发布文章(图文)

    今天打开电脑登上CSDN发现自己授予了专栏勋章,有必要了解如何在专栏发布文章. 很感谢已经有前辈给出了图文教程,此文章转载自博客:http://blog.csdn.net/upi2u/article/ ...

  7. .NetCore外国一些高质量博客分享

    前言 我之前看.netcore一些问题时候,用bing搜索工具搜到了一些外国人的博客.翻看以下,有学习的价值,就分享在这里了. 个人博客 andrewlock.net 最新几篇如下,一看标题就知道很有 ...

  8. 开始android博客分享

    现在开始写博客,分享android开发中的心得.

  9. 从零开始一个个人博客 by asp.net core and angular(三)

    这是第三篇了,第一篇只是介绍,第二篇介绍了api项目的运行和启动,如果api项目没什么问题了,调试都正常了,那基本上就没什么事了,由于这一篇是讲前端项目的,所以需要运行angular项目了,由于前端项 ...

随机推荐

  1. android 渐变展示启动屏

    启动界面Splash Screen在应用程序是很常用的,往往在启动界面中显示产品Logo.公司Logo或者开发者信息,如果应用程序启动时间比较长,那么启动界面就是一个很好的东西,可以让用户耐心等待这段 ...

  2. BW标准数据源初始化设置

    在安装了一干补丁和做好了BW与R3的链接之后(此处有BISIS操心,具体事宜不详),我们就可以登录到R3系统看个究竟了. 磨刀不误砍柴工,先检查一下两边系统的补丁: R3端如下, ,貌似我们是19,通 ...

  3. SQL语句调优-基础知识准备

    当确定了应用性能问题可以归结到某一个,或者几个耗时资源的语句后,对这些语句进行调优,就是数据库管理员或者数据库应用程序开发者当仁不让的职责了.语句调优是和数据库打交道的必备基本功之一. 当你面对一个“ ...

  4. mac下python实现vmstat

    mac下没有linux/unix 的vmstat,只有vm_stat; sh-3.2# vm_statMach Virtual Memory Statistics: (page size of 409 ...

  5. 优化IIS7.5支持10万个同时请求windows 2008 R2

    通过对IIS7的配置进行优化,调整IIS7应用池的队列长度,请求数限制,TCPIP连接数等方面,从而使WEB服务器的性能得以提升,保证WEB访问的访问流畅. -

  6. 一种高效的 vector 四则运算处理方法

    实现 vector 的四则运算 这里假设 vector 的运算定义为对操作数 vector 中相同位置的元素进行运算,最后得到一个新的 vector.具体来说就是,假如 vector<int&g ...

  7. php高级面试题知识点(转载)

    php高级面试题知识点大全 时间:2016-01-26 06:36:22来源:网络 导读:php高级面试题知识点大全,本套面试题内容包括php魔术方法.php单点登录.linux基本命令.前端开发技术 ...

  8. 让我们一起Go(十三)

    前言: 上篇,我们了解了Go语言接口的一些知识,在这篇中,我们将继续聊聊接口这东西. Go语言空接口 Go语言中定义一个空接口,也就是没有任何函数需要实现的接口就是一个空接口,作为一个空接口,因为对象 ...

  9. 聊一聊google的Knowledge Graph

    什么是Knowledge Graph? 它是google用于增强它的搜索引擎的功能和提高搜索结果质量的一种技术.在2012年5月16日提出,除了提供基本的与主题相关的链接服务之外,它还能结构化与主题相 ...

  10. [转]几种常见SQL分页方式

    创建环境: create table pagetest ( id ,) not null, col01 int null, col02 ) null, col03 datetime null ) -- ...