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;

namespace _0911ASP.NET
{
    public partial class _5GridView : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                //这里只能在页面第一次加载时绑定数据
                BindData();
            }
        }

protected void Button1_Click(object sender, EventArgs e)
        {
            BindData();
        }

private void BindData()
        {
            string sql = "select * from student";
            DataTable dt = SqlHelper.GetTable(sql);
            GridView1.DataSource = dt;//指定数据源
            GridView1.DataBind();//真正的绑定数据
        }

protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            //获取新页的索引
            GridView1.PageIndex = e.NewPageIndex;
            //指定完页面索引后,还是要把数据重新查询一下
            //GridView可以根据页的索引,把查询结果的第几条到第几条记录单独的显示出来
            //每次切换页的时候,全部数据都要重新查询绑定(效率低,数据量大时不用)
            BindData();
        }

protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            //删除行的索引
            int index = e.RowIndex;
            //获取删除行的id
            string stuid = GridView1.Rows[index].Cells[1].Text;
            string sql = "delete from student where stuid=" + stuid;
            int count = SqlHelper.ExecuteNonQuery(sql, null);
            if (count > 0)
            {
                //弹出提示框(删除成功)
                string script = "<script type='text/javascript'>alert('{0}');</script>";
                script = string.Format(script, "删除成功");
                Response.Write(script);
                //刷新
                BindData();
            }
            else
            {
                string script = "<script type='text/javascript'>alert('{0}');</script>";
                script = string.Format(script, "删除失败");
                Response.Write(script);
            }
        }

protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
        {
            //设置编辑行的索引
            GridView1.EditIndex = e.NewEditIndex;
            BindData();
        }

protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {  
            //更新(提交修改)
            //获取更新行的索引
            int index = e.RowIndex;
            //id
            string stuid = GridView1.Rows[index].Cells[1].Text;
            //姓名(controls是某个控件下所有子控件的集合)
            //用as转换,转换失败了不会报错,只会返回一个null
            TextBox txtStuName = GridView1.Rows[index].Cells[2].Controls[0] as TextBox;
            string stuname = "";
            if (txtStuName != null)
            {
                stuname = txtStuName.Text;
            }
            //备注
            TextBox txtRemark = GridView1.Rows[index].Cells[6].Controls[0] as TextBox;
            string remark = "";
            if (txtRemark != null)
            {
                remark = txtRemark.Text;
            }
            //把数据更新到数据库
            string sql = "update student set stuname=@stuname,remark=@remark where stuid=@stuid";
            SqlParameter[] pms = new SqlParameter[3];
            pms[0] = new SqlParameter("@stuname", stuname);
            pms[1] = new SqlParameter("@remark", remark);
            pms[2] = new SqlParameter("@stuid", stuid);

int count = SqlHelper.ExecuteNonQuery(sql, pms);
            if (count > 0)
            {
                MessageBox.Show("更新成功");
                //更新成功后要回到未编辑状态
                GridView1.EditIndex = -1;
                BindData();
            }
            else
            {
                MessageBox.Show("更新失败");
            }
        }

protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
        {
            //取消编辑
            GridView1.EditIndex = -1;
            BindData();
        }

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            //绑定每一行数据时触发
            //获取绑定的是那一行
            GridViewRow row = e.Row;
            if (row.RowType==DataControlRowType.DataRow) //判断是不是绑定数据的行
            {
                 string remark = row.Cells[6].Text;
                if (remark.Length>10)
                {
                    row.Cells[6].Text = remark.Substring(0, 10)+"...";

}
            }
            //备注只允许有十个字符,备注不能太长,因为单元格大小是随着内容大小而变化的,当备注超过10个字符,就截取前10个字符+“...”显示
          
        }

protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
        {

}

protected void Button2_Click(object sender, EventArgs e)
        {
            //sender就是触发事件的button按钮
            Button btn = sender as Button;
           // MessageBox.Show(btn.CommandArgument);
            //对应行的学生编号
            string id = btn.CommandArgument;
            string url = "Detail.aspx?id="+id;
            Response.Redirect(url);

}

protected void Button3_Click(object sender, EventArgs e)
        {
            //删除操作
            Button btn = sender as Button;
            MessageBox.Show("开始删除操作,被删除学生的id"+btn.CommandArgument);
        }

protected void Button4_Click(object sender, EventArgs e)
        {
             int count=0;
            foreach (GridViewRow item in GridView1.Rows)
            {
              //判断勾选框有没有选中==忘记了
             //  CheckBox cb = item.Cells[0].Controls[0] as CheckBox;
              CheckBox cb = item.Cells[0].FindControl("CheckBox1") as CheckBox;
             
                    if (cb.Checked)
                {
                    string stuid = item.Cells[1].Text;
                    string sql = "delete from student where stuid="+stuid;
                    count  += SqlHelper.ExecuteNonQuery(sql, null); 
                }  
            }
            if (count>0)
            {
                MessageBox.Show("删除成功" + count);
                BindData();
            }
            else
            {
                MessageBox.Show("删除失败");
            }

}

}
}

aspx页面:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="5GridView.aspx.cs" Inherits="_0911ASP.NET._5GridView" %>

<!--EnableViewState="false"可以禁用视图图状态,一旦禁用后,在服务器端就不能通过对象名打点,对它进行各种操作了;当只做数据的显示,可以把ViewState禁用掉 -->
<!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 selectAll(sender) {
            //把触发事件的对象传过来
            //找gridview下面的input标记,判断type是不是checkbox
            //是的话就设置它们的checked属性和表头的checked属性一致
          
            var gridview = document.getElementById("GridView1").getElementsByTagName("input");
            for (var i = 0; i < gridview.length; i++) {
                if (gridview[i].type == "checkbox") {
                    gridview[i].checked = sender.checked;
                }
            }

}
        function del() {
            //弹出是否确定对话框
            return confirm("是否确定删除?"); //要将返回值返回出去
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="查询所有学生" />
        &nbsp;
        <asp:Button ID="Button4" runat="server" onclick="Button4_Click" Text="多项删除" />
        <br />
        <asp:GridView ID="GridView1" runat="server" CellPadding="4" GridLines="None"
            Width="100%" AllowPaging="True" AutoGenerateColumns="False"
            onpageindexchanging="GridView1_PageIndexChanging"
            onrowcancelingedit="GridView1_RowCancelingEdit"
            onrowdeleting="GridView1_RowDeleting" onrowediting="GridView1_RowEditing"
            onrowupdating="GridView1_RowUpdating" PageSize="5" ForeColor="#333333"
            onrowdatabound="GridView1_RowDataBound"
            onselectedindexchanged="GridView1_SelectedIndexChanged">
            <AlternatingRowStyle BackColor="White" ForeColor="#284775" />
            <Columns>
                <asp:TemplateField HeaderText="勾选">
                    <HeaderTemplate>
                        <asp:CheckBox ID="CheckBox2" runat="server" onclick="selectAll(this)" />
                        勾选
                    </HeaderTemplate>
                    <ItemTemplate>
                        &nbsp;
                        <asp:CheckBox ID="CheckBox1" runat="server" />
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:BoundField DataField="stuid" HeaderText="编号" ReadOnly="True" />
                <asp:BoundField DataField="stuname" HeaderText="姓名" />
                <asp:BoundField DataField="sex" HeaderText="性别" ReadOnly="True" />
                <asp:BoundField DataField="birthday" DataFormatString="{0:d}" HeaderText="生日"
                    ReadOnly="True" />
                <asp:BoundField DataField="stuno" HeaderText="学号" ReadOnly="True" />
                <asp:BoundField DataField="remark" HeaderText="备注" />
                <asp:TemplateField HeaderText="信息">
                    <EditItemTemplate>
                        <asp:RadioButton ID="RadioButton1" runat="server"
                            Checked='<%# Eval("sex").Equals("男") %>' GroupName="sex" Text="男" />
                        <asp:RadioButton ID="RadioButton2" runat="server"
                            Checked='<%# Eval("sex").Equals("女") %>' GroupName="sex" Text="女" />
                    </EditItemTemplate>
                    <ItemTemplate>
                        姓名:<asp:Label ID="Label1" runat="server" Text='<%# Eval("stuname") %>'></asp:Label>
                        <br />
                        性别:<asp:Label ID="Label2" runat="server" Text='<%# Eval("sex") %>'></asp:Label>
                        <br />
                        学号:<asp:Label ID="Label3" runat="server" Text='<%# Eval("stuid") %>'></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:CommandField ShowDeleteButton="True" />
                <asp:CommandField ShowEditButton="True" />
                <asp:TemplateField HeaderText="操作">
                    <ItemTemplate>
                        <asp:Button ID="Button2" runat="server" CommandArgument='<%# Eval("stuid") %>'
                            onclick="Button2_Click" Text="详情" />
                        &nbsp;
                        <asp:Button ID="Button3" runat="server" CommandArgument='<%# Eval("stuid") %>'
                            OnClientClick="return del()" onclick="Button3_Click" Text="删除" />
                    </ItemTemplate>
                </asp:TemplateField>
            </Columns>
            <EditRowStyle BackColor="#999999" />
            <FooterStyle BackColor="#5D7B9D" ForeColor="White" Font-Bold="True" />
            <HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
            <PagerSettings FirstPageText="首页" LastPageText="末页" NextPageText="下一页"
                PreviousPageText="上一页" />
            <PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
            <RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
            <SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
            <SortedAscendingCellStyle BackColor="#E9E7E2" />
            <SortedAscendingHeaderStyle BackColor="#506C8C" />
            <SortedDescendingCellStyle BackColor="#FFFDF8" />
            <SortedDescendingHeaderStyle BackColor="#6F8DAE" />
        </asp:GridView>
        <br />
    </div>
    </form>
</body>
</html>

gridveiw的使用的更多相关文章

  1. GridVeiw 使用

    1. 因使用的是 Mongodb,因此要在 ActiveDataProvider 中指定 key 属性 2. 自定义表格中的按钮 'class' => 'yii\grid\ActionColum ...

  2. 在GridView控件内文本框实现TextChanged事件

    本篇是教你实现GridView控件内的TextBox文本框实现自身的TextChanged事件.由于某些功能的需求,GridView控件内嵌TextBox,当TextBox值发生变化时,触发TextC ...

  3. Mouse点击之后,复制GridView控件的数据行

    本篇是实现用mouse点击GridView控件任意一行,把所点击的数据复制至另一个GridView控件上. 实现大概思路,把所点击的数据行的记录主键找出来,再去过滤数据源. 点击功能,已经实现,可以参 ...

  4. 单击GridView进入编辑模式

    一直以来,Insus.NET在实现GridView编辑时,均是在每笔记录第一列或是最后一列放置编辑铵钮,点击编辑铵钮之后,进行编辑模式.本博文是使用另外方式,即是点击GridView记录行任一位置,进 ...

  5. extjs用iframe的问题

    项目中用extjs做前提系统的界面是左边用树做目录 右边用tabpanel做内容展示点击树节点的时候 在tabpanel添加新的tab JScript code var newTab = center ...

  6. GridView Item 大小可能不一样,如何保持同一行的Item 高度大小相同,且GridView高度自适应!

    昨天用到GridView,但是遇到几个问题,就是GridView默认的item其实大小是一致的,但是我们经常会遇到item大小不同,系统默认会留白的问题,很头疼!如下图这样的:      就会造成,右 ...

  7. 动态绑数据(GridView控件Header和ItemTemplate)

    想了解此篇文章,建议先预习一下<动态变更GridView控件列名>http://www.cnblogs.com/insus/p/3232057.html,因为多少有些关联.不管怎样,它能够 ...

  8. 动态合并Repeater控件数据列

    前天Insus.NET实现<动态合并GridView数据行DataRow的列>.今天再玩玩Repeater控件,功能也是动态合并某列栏位.Repeater控件跟GridView控件一样集成 ...

  9. Android 高级UI组件(一)GridView与ListView

    1.GridView 1.GridView学习 GridView和ListView都是比较常用的多控件布局,而GridView更是实现九宫图的首选 main.xml: <?xml version ...

随机推荐

  1. DAY2敏捷冲刺

    站立式会议 工作安排 (1)服务器配置 (2)数据库连接 (3)页面创意 燃尽图 代码提交记录 感想 林一心:centos配置服务器真的算是一个不小的坑,目前数据库配置清楚,脚本部署好明天测试交互,还 ...

  2. lintcode-36-翻转链表 II

    36-翻转链表 II 翻转链表中第m个节点到第n个节点的部分 注意事项 m,n满足1 ≤ m ≤ n ≤ 链表长度 样例 给出链表1->2->3->4->5->null, ...

  3. iOS- 如何将非ARC的项目转换成ARC项目(实战)

    1.前言   因为公司有个国外餐饮系统,编程开发了3-4年,之前用的都是非ARC,开发到今年,第一批迭代开发的人员早已不见,目前发现了有许多的内存泄露之类的,系统没有自动释放该释放的内存.一旦app长 ...

  4. 《Effective C#》快速笔记(三)- 使用 C# 表达设计

    目录 二十一.限制类型的可见性 二十二.通过定义并实现接口替代继承 二十三.理解接口方法和虚方法的区别 二十四.用委托实现回调 二十五.用事件模式实现通知 二十六.避免返回对内部类对象的引用 二十七. ...

  5. BZOJ 1789 Y形项链(思维)

    这题类似于1787,最后的节点一定是两点的LCA,这里也就是两个字符串的最长公共前缀. # include <cstdio> # include <cstring> # inc ...

  6. python中元组与小括号的关系

    在学习Python 的时候.说到有两种数据类型,一种叫 列表,一种叫做元组,可以认为,元组是功能精简的列表.因为它少了列表很多功能.但是又有相识.定义他们的时候,主要是用中括号和小括号之分. 例如:定 ...

  7. CentOS7 从查看、启动、停止服务说起systemctl

    执行命令“systemctl status 服务名.service”可查看服务的运行状态,其中服务名后的.service 可以省略,这是CenOS7以后采用systemd作为初始化进程后产生的变化. ...

  8. Elasticsearch cat Apis

    1._cat列入所有有效命令 GET /_cat 返回:有个猫...所以不难想象为啥是cat api =^.^= /_cat/allocation /_cat/shards /_cat/shards/ ...

  9. Spring boot——构建rest风格

    前言rest风格严格意义上说不是一种标准,而是一种风格,在如今互联网界,这个风格被广泛用于微服务系统之间的交互. REST简单介绍 REST(Representional State Transfer ...

  10. bzoj1257: [CQOI2007]余数之和sum(数论)

    非常经典的题目... 要求 则有 实际上 最多只有2*sqrt(k)种取值,非常好证明 因为>=sqrt(k)的数除k下取整得到的数一定<=sqrt(k),而k除以<=sqrt(k) ...