gridveiw的使用

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>

 

 

posted @ 2013-07-11 09:39  木兔女侠  阅读(342)  评论(0编辑  收藏  举报