包含有

数据的编辑,删除,

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

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);
        }
    }

转载于:https://www.cnblogs.com/ianunspace/p/3438233.html

刚刚开通博客,分享Asp.Net的GridView的基本用法相关推荐

  1. 第一天开通博客,记录自己在编程道路上的点点滴滴

    第一天开通博客,第一天写随笔:今年刚毕业,希望能用博客记录自己在编程道路上的点点滴滴,会记录自己在编程过程中遇到的问题及解决办法,也会记录自己的程序人生,分享出来和大家共勉. 希望自己能早日成为一名快 ...

  2. XSL3399我开通博客了谢多交流

    大数据研究开通博客了 今天开通博客,应亠大粉丝要求,分享交流经验.希望共同进步,谢谢CSDN.让我们有个好的交流平台. 你好! 这是你第一次使用 Markdown编辑器 所展示的欢迎页.如果你想学习如 ...

  3. Nooice, 首次开通博客园

    今天2019年9月7日周六,受各大博主在此共享知识的原因,我亦开通博客园的博客,或许能分享一些东西. 顺便说一下,今天因为眼睛不正当使用(起床就看手机)引起的散光让我很不舒服..

  4. 新开通博客园,纪念一下。

    新开通博客园,纪念一下. 转载于:https://www.cnblogs.com/tiger4066/p/4685039.html

  5. 今天刚开通博客,很开心

    今天刚开通博客,很开心,我是一名大三的一名学生,机电专业的,下个月都要出去实习,很忐忑,也对外面的世界充满这憧憬.....明天继续,今天太晚了. 转载于:https://www.cnblogs.com ...

  6. 热烈庆祝蓝启旭大佬开通博客

    AKIOI的大佬蓝启旭开通博客啦!!!!! 点一下,看一年,读文章不花一分钱!!!! 点这里!!https://www.cnblogs.com/perisino/ 大佬TQL%%%%% 转载于:htt ...

  7. 开博第一篇,附上我开通博客的理由

    作为一个计算机专业的学生,虽然本科学的是计算机,但是很多东西还只是停留在书本上对知识的认识,一年的前端工作经验,让我学到了很多,也让我明白了博客的重要性,开通博客只是为了梳理一下自己的知识,完善自己的 ...

  8. 学语言·写博客·分享交流——《我是一只IT小小鸟》读书笔

    学语言·写博客·分享交流 --<我是一只IT小小鸟>读书笔记(8) 原贴地址:http://byourselves.ycool.com/post.2507061.html 刘未鹏的故事现在 ...

  9. android 摇摇棒 之surfaceView vs. View--第二届 Google 暑期大学生博客分享大赛 - 2011 Android 成长篇...

    第二届 Google 暑期大学生博客分享大赛 - 2011 Android 成长篇 我的主题是: Android 应用程序开发经验 一直做的是嵌入式C/C++(Qt)语言开发,Java看了一个月,没想 ...

最新文章

  1. 混合深度卷积,更少参数下的轻量级网络
  2. LinFu Dynamic Proxy - LinFu 2.3, LinFu.DynamicProxy 1.031
  3. ansible相关说明
  4. JDK 8时代的抽象类与接口
  5. InputStream 、 InputStreamReader和BufferedReader
  6. LeetCode 297. 二叉树的序列化与反序列化(前序遍历层序遍历)
  7. 传百度无人车计划分拆,百度回复:不实信息,目前未有分拆计划
  8. CPL,RPL和DPL的关系
  9. expdp导出 schema_[转载]导入导出:impdpexpdp
  10. DockOne微信分享(一四一):如何开发部署Kubernetes Native应用
  11. 高通平台如何新增加一个分区,并mount到android系统中
  12. Java ftp 上传文件名乱码
  13. python3.6 numpy下载_numpy下载安装 NumPy MKL v1.13.1 cp36 for Python3.6 官方安装版 64位 下载-脚本之家...
  14. 大数据GIS系列(2)——空间大数据处理与分析案例
  15. 【Android】常用对话框大全(一)Android Dialog
  16. JavaScript设计模式——状态模式
  17. 满满的提高芝麻分实操技巧!
  18. 看php网站论文的感想,阅读学术论文心得体会
  19. 玩转EXCEL系列-选择性粘贴几个实用技巧
  20. 玩吃鸡用什么蓝牙耳机比较好?内行推荐四款吃鸡低延迟蓝牙耳机

热门文章

  1. react 父子传值_React父子组件间的传值
  2. Spring 国际化 MessageSource
  3. 国外html游戏发展历史,17个国外游戏行业的网页设计欣赏
  4. java基本语法心得_Java学习笔记(一)——基础语法(上)
  5. java 遍历 likedlist_Java集合02----LinkedList的遍历方式及应用
  6. JS中对数组元素进行增、删、改、查的方法,以及其他方法
  7. pycharm默认注释与快捷键功能
  8. popen和system问题
  9. 工程项目成本/进度综合控制方法及应用
  10. 再谈布局,栅栏式自适应布局的学习和实现(calc自适应布局)