关于GRidView控件的用法总结

来源:互联网 发布:实名认证淘宝小号出售 编辑:程序博客网 时间:2024/04/30 18:35

 A.页面加载----

 protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                    BindData();
                if (Request.QueryString["userid"] != null)//判断,如果可以获取到id的值,则执行以下操作
                {

                    DataTable dt = BIL.teacherinfo.GetUserByID(Request.QueryString["userid"]);
                    this.txtid.Text = dt.Rows[0]["userid"].ToString();
                    this.txtnames.Text = dt.Rows[0]["username"].ToString();
                    this.txtsex.Text = dt.Rows[0]["sex"].ToString();
                    btnSelectOrg.Attributes["onclick"] = "test();";//后台调用js
                }

            }
        }

  //显示全部信息
        public void BindData()
        {
         List <user > list=new List<user>() ;
            DataTable dt = BIL.teacherinfo.showAlluser();
            for (int i = 0; i < dt.Rows.Count; i++)

            {
                user user=new user ();
                user.Sex=dt.Rows[i]["sex"].ToString();
                user.Username = dt.Rows[i]["username"].ToString();
                user.Address  = dt.Rows[i]["adderss"].ToString();
                user.Userid  =  int.Parse ( dt.Rows[i]["userid"].ToString());
                user.Birth = Convert .ToDateTime ( dt.Rows[i]["birthday"].ToString());
                user.Ischecked =dt.Rows[i]["ischeckd"].ToString();

               list.Add(user);
             }
            this.GridView1.DataSource = list;
            this.GridView1.DataBind();

        }

  //绑定数据行
        protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                //Label num = (Label)e.Row.FindControl("lNum");
                //num.Text = (GridView1.PageIndex * GridView1.PageSize + e.Row.RowIndex + 1) + "";//自动增长序号
                Label sex = (Label)e.Row.Cells[3].FindControl("lbsex");//方法1
                user user = (user)e.Row.DataItem; //方法2(这里只有当dridview的绑定类型为list时才可以用)
                switch (user.Sex )
               // switch (sex.Text)
                {
                    case "男":
                        Button Status1 = (Button)e.Row.Cells[4].FindControl("ModifyStatus");//设置按钮的文本
                        Status1.Text = "禁用";
                      Status1.Enabled = false;
                        break;
                    case "女":
                        Button Status2 = (Button)e.Row.Cells[4].FindControl("ModifyStatus");
                        Status2.Text = "启用";
                        Status2.Enabled = true ;
                        break;
                    default:
                        break;
                }

                switch (user.Ischecked )
                {
                    case "true":
                       
                        CheckBox ckbox = (CheckBox)e.Row.Cells[5].FindControl("ischecked");
                        ckbox.Checked = true;
                        break;
                    case "false":
                        CheckBox ckbox2 = (CheckBox)e.Row.Cells[5].FindControl("ischecked");
                        ckbox2.Checked = false;
                        break;
                    default:
                        break;
                }
                //光帮效果
                e.Row.Attributes.Add("onmouseover", "currentcolor=this.style.backgroundColor;this.style.backgroundColor='pink'");
                e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor=currentcolor");
                CheckBox box = (CheckBox)e.Row.FindControl("CheckBox1");
                box.Attributes.Add("ItemID", ((Label)e.Row.FindControl("id1")).Text);//给checkbox加属性
            }
                //底部
            else if (e.Row.RowType == DataControlRowType.Footer)
            {
                e.Row.Cells[0].Text = "<font color=red>用户人数:</font>";
                e.Row.Cells[1].Text = "<font color=red>" + GridView1.Rows.Count.ToString() + "人</font>";
                Usercount = e.Row.Cells[0].Text + e.Row.Cells[1].Text

            }
        }

//行命令
        protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
        {

            if (e.CommandName == "del")
            {
                string str = e.CommandArgument.ToString();
                BIL.teacherinfo.deleteUse(str);
                BindData();
            }
            else if (e.CommandName == "add")
            {
                Response.Redirect("addUser.aspx");
            }

            else if (e.CommandName == "ModifyStatus")
            {
                Button Operate = (Button)e.CommandSource;//命令的按钮
                if (Operate.Text == "启用") {
                    Operate.Enabled = true;
               
                }
                else   if (Operate.Text == "禁用")
                {
                    Operate.Enabled = false;

                }            
            }

        }
        //编辑
        protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {
            GridViewRow gvr = this.GridView1.Rows[e.RowIndex];
            Label str = gvr.FindControl("id1") as Label;
            int id = Convert.ToInt32(str.Text);
            Response.Redirect("UpdateUser.aspx?id=" + id);
        }
        //分页
        protected void GridView1_PageIndexChanging1(object sender, GridViewPageEventArgs e)
        {
            int i = e.NewPageIndex;
            int j = i < 0 ? 0 : i;
            this.GridView1.PageIndex = j;
            BindData();
        }

//查询

        protected void btsearch_Click(object sender, EventArgs e)
        {
            string name = this.txtname.Text.Trim();
            if (name.Length == 0)
            {
                Response.Write("<script>alert('输入查询的用户名!')</script>");
            }
            else
            {
                DataTable dt = BIL.teacherinfo.showUserByname(name);
                if (dt.Rows.Count > 0)
                {
                    this.GridView1.DataSource = dt;
                    this.GridView1.DataBind();
                }
                else
                {

                    Response.Write("<script>alert('对不起,没有查到!!!!')</script>");
                }


            }
        }

        //选项变化
        protected void CheckBox2_CheckedChanged(object sender, EventArgs e)
        {
            for (int i = 0; i <= GridView1.Rows.Count - 1; i++)
            {
                CheckBox cbox = (CheckBox)GridView1.Rows[i].FindControl("CheckBox1");

                if (CheckBox2.Checked == true)
                {
                    cbox.Checked = true;
                }
                else
                {
                    cbox.Checked = false;
                }
            }
        }
        //导出Excel
        protected void Btimport_Click(object sender, EventArgs e)
        {
         
        }

//这个重载方法必须有,不然导出excel时引发异常
        public override void VerifyRenderingInServerForm(Control control)
        {

        }
        protected void btcancel_Click(object sender, EventArgs e)
        {
            CheckBox2.Checked = false;
            for (int i = 0; i <= GridView1.Rows.Count - 1; i++)
            {
                CheckBox cbox = (CheckBox)GridView1.Rows[i].FindControl("CheckBox1");
                cbox.Checked = false;
            }
        }
       //批量删除
        protected void Btdel_Click(object sender, EventArgs e)
        {
            for (int i = 0; i <= GridView1.Rows.Count - 1; i++)
            {
                //应用FindControl方法查找GridView控件中id值为CheckBox1的CheckBox控件
                CheckBox cbox = (CheckBox)GridView1.Rows[i].FindControl("CheckBox1");
                //判断GridView控件中CheckBox控件是否被选中
                if (cbox.Checked == true)
                {
                    string b = ((CheckBox)GridView1.Rows[i].FindControl("CheckBox1")).Attributes["ItemID"];
                    int a = BIL.teacherinfo.deleteUse(b); 
                }
            }
            BindData();

        }

//数据导出到Excel

        protected void Btimport_Click1(object sender, EventArgs e)
        {
            Response.Clear();
            Response.Buffer = true;
            Response.Charset = "GB2312";
            Response.AppendHeader("Content-Disposition", "attachment;filename=Message.xls");
            Response.ContentEncoding = System.Text.Encoding.UTF8;
            Response.ContentType = "application/ms-excel";//设置输出文件类型为excel文件。
            System.IO.StringWriter oStringWriter = new System.IO.StringWriter();
            System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter);
            this.GridView1.RenderControl(oHtmlTextWriter);
            Response.Output.Write(oStringWriter.ToString());
            Response.Flush();
            Response.End();
        }

B----部分页面前台代码

    <div align="center">
        用户信息<br />
        输入用户姓名:
        <asp:TextBox ID="txtname" runat="server"></asp:TextBox>
        <asp:Button ID="btsearch" runat="server" Text="查询" OnClick="btsearch_Click" />
        <asp:Button ID="Btdel" runat="server" Text="批量删除" OnClick="Btdel_Click" />
        <%--<asp:Button ID="btall" runat="server" Text="全选" onclick="btall_Click"></asp:Button>--%>
        <asp:Button ID="btcancel" runat="server" Text="取消" OnClick="btcancel_Click"></asp:Button>
        <asp:CheckBox ID="CheckBox2" runat="server" AutoPostBack="True" Font-Size="9pt" OnCheckedChanged="CheckBox2_CheckedChanged"
            Text="全选" Width="56px" />
        <asp:GridView ID="GridView1" runat="server" Width="630px" AutoGenerateColumns="False"
            OnRowCommand="GridView1_RowCommand" OnRowDataBound="GridView1_RowDataBound" Style="margin-left: 0px"
            Height="98px" AllowPaging="True" PageSize="2" OnRowUpdating="GridView1_RowUpdating"
            OnPageIndexChanging="GridView1_PageIndexChanging1">
            <Columns>
              <%--  <asp:TemplateField HeaderText="勾选">
                    <ItemTemplate>
                        <asp:CheckBox ID="CheckBox1" runat="server" Font-Size="9pt" Width="9px" />
                    </ItemTemplate>
                </asp:TemplateField>--%>
                  <asp:TemplateField HeaderText="勾选">
                                <ItemTemplate>
                                    <asp:CheckBox ID="CheckBox1" runat="server" Font-Size="9pt" Width="9px" />
                                </ItemTemplate>
                            </asp:TemplateField>
                <asp:TemplateField HeaderText="用户编号">
                    <EditItemTemplate>
                        <asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("userid") %>'></asp:TextBox>
                    </EditItemTemplate>
                    <ItemTemplate>
                        <asp:Label ID="id1" runat="server" Text='<%# Bind("userid") %>'></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="用户姓名">
                    <EditItemTemplate>
                        <asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("username") %>'></asp:TextBox>
                    </EditItemTemplate>
                    <ItemTemplate>
                        <asp:Label ID="Label1" runat="server" Text='<%# Bind("username") %>'></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="性别">
                    <EditItemTemplate>
                        <asp:TextBox ID="txtsex" runat="server" Text='<%# Bind("sex") %>'></asp:TextBox>
                    </EditItemTemplate>
                    <ItemTemplate>
                        <asp:Label ID="lbsex" runat="server" Text='<%# Bind("sex") %>'></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="更改状态">
                            <ItemTemplate>
                                <asp:Button ID="ModifyStatus" runat="server" CommandArgument='<%# Eval("userid") %>'
                                    CommandName="ModifyStatus" />
                            </ItemTemplate>
                        </asp:TemplateField>
                <asp:TemplateField HeaderText="选中状态">
                            <ItemTemplate>
                                <asp:CheckBox ID="ischecked" runat="server" />
                            </ItemTemplate>
                        </asp:TemplateField>
                       <asp:HyperLinkField DataNavigateUrlFields="userid" DataNavigateUrlFormatString="alluser.aspx?userid={0}"
                                HeaderText="修改" Text="修改" />  
                <asp:TemplateField HeaderText="修改用户信息">
                    <ItemTemplate>
                        <asp:ImageButton ID="btupdate" runat="server" Text="修改" CommandName="update" CommandArgument='<%# Eval("userid ") %>'
                            ImageUrl="~/LinkButtonImage/编辑.jpg" />
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="删除用户信息">
                    <ItemTemplate>
                        <asp:ImageButton ID="btdel" runat="server" Text="删除" CommandName="del" CommandArgument='<%# Eval("userid") %>'
                            ImageUrl="~/LinkButtonImage/删除.jpg" OnClientClick='return confirm("确实要删除吗?")' />
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="添加新用户">
                    <ItemTemplate>
                        <asp:ImageButton ID="btadd" runat="server" Text="新建" CommandName="add" ImageUrl="~/LinkButtonImage/处理.jpg" />
                    </ItemTemplate>
                </asp:TemplateField>
            </Columns>
            <PagerTemplate>
                第<asp:Label ID="lb_current" runat="server" Text='<%#((GridView)Container.Parent.Parent).PageIndex+1%>'></asp:Label>页
                共<asp:Label ID="lb_total" runat="server" Text='<%#((GridView)Container.Parent.Parent).PageCount%>'></asp:Label>页
                <asp:LinkButton ID="LinkButton1" runat="server" CommandName="Page" CommandArgument="First">首页</asp:LinkButton>
                <asp:LinkButton ID="LinkButton2" runat="server" CommandName="Page" CommandArgument="Prev">上页</asp:LinkButton>
                <asp:LinkButton ID="LinkButton3" runat="server" CommandName="Page" CommandArgument="Next">下页</asp:LinkButton>
                <asp:LinkButton ID="LinkButton4" runat="server" CommandName="Page" CommandArgument="Last">末页</asp:LinkButton>
            </PagerTemplate>
        </asp:GridView>
        <%=Usercount %>
        <table border="0" cellpadding="0" cellspacing="0" align="center">
                        <tr>
                            <td align="right" style="width: 73px">
                               用户编号:</td>
                            <td style="width: 100px">
                    <asp:TextBox ID="txtid" runat="server" Width="160px" CssClass="search"></asp:TextBox></td>
                            <td style="width: 100px">
                            </td>
                         
                        </tr>
                        <tr>
                            <td align="right" style="width: 73px">
                                <asp:Label ID="Label2" runat="server" Text="姓名:" Width="69px"></asp:Label></td>
                            <td style="width: 100px">
                    <asp:TextBox ID="txtnames" runat="server" Width="160px"></asp:TextBox></td>
                            <td align="center" style="width: 100px">
                                &nbsp;</td>
                        </tr>
                        <tr>
                            <td align="right" style="width: 73px">
                                <asp:Label ID="Label3" runat="server" Text="性别:" Width="88px" Height="16px"></asp:Label></td>
                            <td style="width: 100px">
                    <asp:TextBox ID="txtsex" runat="server" Width="160px"></asp:TextBox></td>
                            <td style="width: 100px">
                            </td>
                        </tr>
                        <tr>
                            <td style="width: 73px">
                            </td>
                            <td align="center" style="width: 100px">
                                &nbsp;<table border="0" cellpadding="0" cellspacing="0">
                                    <tr>
                                        <td style="width: 100px">
                                            <asp:Button ID="btnEdit" runat="server" OnClick="btnEdit_Click"
                        Text="修改" Width="59px" CssClass="login" /></td>
                                        <td style="width: 100px">
                    <asp:Button ID="btnCancel" runat="server" OnClick="btnCancel_Click"
                        Text="重置" Width="63px" CausesValidation="False" CssClass="login" /></td>
                                    </tr>
                                </table>
                            </td>
                            <td align="left" style="width: 100px">
                                &nbsp;</td>
                        </tr>
                    </table>
        <input id="btnSelectOrg"  runat="server" class="commonButton" style="width: 25px" type="button" value="..." onclick="return btnSelectOrg_onclick()" />
 <asp:Button ID="Button1" runat="server" Text="测试"   OnClientClick="test3();" />
        <asp:Button ID="Btimport" runat="server" Text="导出到Excel"
            onclick="Btimport_Click1"  ToolTip="请允许弹出式页面"/>
        </asp:Button>
    </div>

 

 


 

原创粉丝点击