GridView 实例

这篇博客介绍了如何在ASP.NET中使用GridView控件进行数据展示、编辑和删除操作。包括使用BoundField和TemplateField显示数据,以及添加编辑、删除按钮。同时,展示了如何实现全选功能和行颜色改变的JavaScript函数。
摘要由CSDN通过智能技术生成
using  System;
using  System.Data;
using  System.Configuration;
using  System.Collections;
using  System.Web;
using  System.Web.Security;
using  System.Web.UI;
using  System.Web.UI.WebControls;
using  System.Web.UI.WebControls.WebParts;
using  System.Web.UI.HtmlControls;
using  System.Text;
using  System.Data.SqlClient;
public   partial   class  Admin_Users : System.Web.UI.Page
{
    
//总记录数
    private int TotalCountRecord;
    
//每页显示的条数
    private int PageItem = 5;
    
//当前页
    private int CurrentPage = 1;
    
private string strUrl = string.Empty;

    
protected void Page_Load(object sender, EventArgs e)
    
{
        
if (Request.QueryString["page"!= null)
        
{
            
if (!Int32.TryParse(Request.QueryString["page"].ToString(), out CurrentPage))
            
{
                Response.Write(
"请输入整数页");
                Response.End();
                
return;
            }


        }

        
if (Session["UserName"!= null)
        
{
            Label1.Text 
= Session["UserName"].ToString();
        }

        
if (!this.IsPostBack)
        
{
            
this.BindData();
            BuildPagers();
        }

    }

    
public void BindData()
    
{
        
string strWhere = string.Empty;

        
if (Request.QueryString["key"!= null)
        
{
            
string key = Convert.ToString(Request.QueryString["key"]);
            strWhere 
= string.Format("UserName like '%{0}%'", key);
            strUrl 
= string.Format("&key={0}", key);
        }

        
this.GridView1.DataSource = Users.GetAllUsersByStrWhere(PageItem, CurrentPage, strWhere, out TotalCountRecord);
        
this.GridView1.DataBind();
    }

    
public void BuildPagers()
    
{
        
//偏移量
        int Step = 10;
        
int LeftNum = 0;
        
int RightNum = 0;
        
string PageUrl = Request.FilePath;
        
int PageCount = (int)Math.Ceiling((double)(TotalCountRecord) / PageItem);
        
if (CurrentPage - Step < 1)
        
{
            LeftNum 
= 1;
        }

        
else
        
{
            LeftNum 
= CurrentPage - Step;
        }


        
if (CurrentPage + Step > PageCount)
        
{
            RightNum 
= PageCount;
        }

        
else
        
{
            RightNum 
= CurrentPage + Step;
        }

        StringBuilder OutPut 
= new StringBuilder();

        
for (int i = LeftNum; i <= RightNum; i++)
        
{
            
if (i == CurrentPage)
            
{
                OutPut.Append(
"<font style='margin-left:3px;' color=red>");
                OutPut.Append(i.ToString());
                OutPut.Append(
"</font>");
            }

            
else
            
{
                OutPut.Append(
"<a style='margin-left:3px;' href='");
                OutPut.Append(PageUrl);
                OutPut.Append(
"?page=");
                OutPut.Append(i.ToString());
                OutPut.Append(strUrl);
                OutPut.Append(
"'>");
                OutPut.Append(i.ToString());
                OutPut.Append(
"</a>");
            }

        }


        
if (CurrentPage > 1)
        
{
            OutPut.Insert(
0string.Format("<a href='{0}?page={1}{2}'>上一页</a>", PageUrl, (CurrentPage - 1), strUrl));
        }


        
if (CurrentPage < PageCount)
        
{
            OutPut.Append(
"<a href='");
            OutPut.Append(PageUrl);
            OutPut.Append(
"?page=");
            OutPut.Append(CurrentPage 
+ 1);
            OutPut.Append(strUrl);
            OutPut.Append(
"'>下一页</a></li>");
        }

        
this.Label3.Text = OutPut.ToString();
        
this.Label2.Text = string.Format("总记录数:<font color='red'>{0}</font>  总页数:<font color='red'>{1}</font>", TotalCountRecord, PageCount);
    }




    
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    
{
        
if (e.Row.Cells[5].HasControls())
        
{
            LinkButton BtnDelete 
= (LinkButton)e.Row.Cells[5].Controls[0];
            
if (BtnDelete.Text.Equals("删除"))
            
{
                BtnDelete.Attributes.Add(
"OnClick""javascript:return confirm('" + string.Format("您确认要删除{0}吗?", DataBinder.Eval(e.Row.DataItem, "UserName")) + "')");
            }


        }


        
if (e.Row.RowType == DataControlRowType.DataRow)
        
{
            CheckBox checkbox2 
= e.Row.Cells[6].FindControl("CheckBox1"as CheckBox;
            checkbox2.Attributes.Add(
"onclick""javascript:ChangeColor(this,'" + e.Row.ClientID + "')");
        }

    }

    
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
    
{
        
int UserID = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Values[0]);
        Users singleUser 
= new Users();
        singleUser.UserID 
= UserID;
        
if (Users.DeleteUser(singleUser))
        
{
            
this.BindData();
            BuildPagers();
            Label4.Text 
= "删除成功";
        }

        
else
        
{
            Label4.Text 
= "删除失败";
        }


    }

    
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
    
{
        
int UserID = Convert.ToInt32(GridView1.DataKeys[e.RowIndex]["UserID"].ToString());

        
string newUserName = ((TextBox)GridView1.Rows[e.RowIndex].FindControl("UserName")).Text;
        
string newUserPwd = ((TextBox)GridView1.Rows[e.RowIndex].FindControl("UserPwd")).Text;
        
int newGrade = Convert.ToInt32(((TextBox)GridView1.Rows[e.RowIndex].FindControl("Grade")).Text);

        Users singleUser 
= new Users();

        singleUser.UserID 
= UserID;
        singleUser.UserName 
= newUserName;
        singleUser.UserPwd 
= newUserPwd;
        singleUser.Grade 
= newGrade;

        Users.UpdateUser(singleUser);
        GridView1.EditIndex 
= -1;

        
this.BindData();
        BuildPagers();
    }



    
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
    
{
        GridView1.EditIndex 
= e.NewEditIndex;
        
this.BindData();
        BuildPagers();
    }

    
protected void Button1_Click(object sender, EventArgs e)
    
{
        
int intCount = GridView1.Rows.Count;
        
for (int i = 0; i < intCount; i++)
        
{
            CheckBox checkbox2 
= this.GridView1.Rows[i].Cells[7].FindControl("CheckBox1"as CheckBox;
            
if (checkbox2.Checked)
            
{
                
int UserID = Convert.ToInt32(this.GridView1.Rows[i].Cells[0].Text);
                Users SingleUser 
= new Users();
                SingleUser.UserID 
= UserID;
                Users.DeleteUser(SingleUser);
            }


        }

        
this.BindData();
        BuildPagers();
    }

    
protected void CustomValidator1_ServerValidate(object source, ServerValidateEventArgs args)
    
{
        
string UserName = args.Value;
        
if (Users.IsValidateUserName(UserName))
        
{
            args.IsValid 
= false;

        }

        
else
        
{
            args.IsValid 
= true;
        }

       
    }

    
protected void Button2_Click(object sender, EventArgs e)
    
{
        
if (Page.IsValid)
        
{
            
string UserName = TextBox1.Text.ToString();
            
string UserPwd = TextBox2.Text.ToString();
            
int Grade = RadioButtonList1.SelectedValue.ToString();
            Users SingleUser 
= new Users();
            SingleUser.UserName 
= UserName;
            SingleUser.UserPwd 
= UserPwd;
            SingleUser.Grade 
= Grade;

            
if (Users.AddUser(SingleUser))
            
{
                Label2.Text 
= "添加成功!";
                
this.GridView1.DataBind();
            }

            
else
            
{

                Label2.Text 
= "添加失败!";
            }


        }

    }

}

<%@ Page Language="C#" MasterPageFile="~/Admin/Admin.master" AutoEventWireup="true" CodeFile="Admin.aspx.cs" Inherits="Admin_Users" Title="Untitled Page" %>
<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
         <script type="text/javascript">

function SelectAll(tempControl)
    {
     var theBox=tempControl;
    xState=theBox.checked;
   elem=theBox.form.elements;
    for(i=0;i<elem.length;i++)
    {
        if(elem[i].type=="checkbox" && elem[i].id!=theBox.id)
        {
            if(elem[i].checked!=xState)
            {
                elem[i].click();
            }
           
        }
    }

}
function ChangeColor(a,b)
{
    var theBox=a;
    var tr=document.getElementById(b);
    if (theBox.checked)
    {
        tr.style.backgroundColor="red";
       
    }
    else
        tr.style.backgroundColor="#cccccc"
   

}

</script>
   
    <table border="0" cellpadding="0" cellspacing="0" style="width:600px; height: 182px">
        <tr>
            <td style="width: 622px">
                欢迎<asp:Label ID="Label1" runat="server" Width="33px"></asp:Label>登陆</td>
        </tr>
        <tr>
            <td style="text-align: right; width: 622px; height: 156px;" >
                <asp:GridView ID="GridView1" runat="server" Height="100%" Width="100%" AutoGenerateColumns="False" DataKeyNames="UserID" OnRowDataBound="GridView1_RowDataBound" OnRowDeleting="GridView1_RowDeleting" CellPadding="4" ForeColor="#333333" GridLines="None" OnRowEditing="GridView1_RowEditing" OnRowUpdating="GridView1_RowUpdating" HorizontalAlign="Center" >
                    <Columns>
                        <asp:BoundField DataField="UserID" HeaderText="ID" >
                            <ControlStyle Width="20px" />
                        </asp:BoundField>
                        <asp:TemplateField HeaderText="用户名">
                        <ItemTemplate>
                               <%#Eval("username") %>
                            </ItemTemplate>
                            <EditItemTemplate>
                                <asp:TextBox ID="UserName" runat="server" Text='<%#Eval("username") %>' Width="100px"></asp:TextBox>
                            </EditItemTemplate>
                        </asp:TemplateField>
                       
                        <asp:TemplateField HeaderText="密码">
                        <ItemTemplate>
                               <%#Eval("UserPwd") %>
                            </ItemTemplate>
                            <EditItemTemplate>
                                <asp:TextBox ID="UserPwd" runat="server" Text='<%#Eval("UserPwd") %>' Width="100px"></asp:TextBox>
                            </EditItemTemplate>
                        </asp:TemplateField>   
                                           
                        <asp:BoundField DataField="RegisterDate" HeaderText="添加日期" >
                            <ControlStyle Width="100px" />
                        </asp:BoundField>
                       
                        <asp:TemplateField HeaderText="权限">
                        <ItemTemplate>
                               <%#Eval("Grade") %>
                            </ItemTemplate>
                            <EditItemTemplate>
                                <asp:TextBox ID="Grade" runat="server" Text='<%#Eval("Grade") %>' Width="30px"></asp:TextBox>
                            </EditItemTemplate>
                        </asp:TemplateField>   
                      
                        <asp:CommandField ShowEditButton="True" />
                        <asp:CommandField ShowDeleteButton="True" />
                        <asp:TemplateField>
                            <ItemTemplate>
                                <asp:CheckBox ID="CheckBox1" runat="server" />
                            </ItemTemplate>
                            <HeaderTemplate>                       
                                <asp:CheckBox ID="CheckBox2" runat="server" οnclick="javascript:SelectAll(this);"/>
                            </HeaderTemplate>
                        </asp:TemplateField>

                    </Columns>
                    <FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
                    <RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
                    <EditRowStyle BackColor="#999999" />
                    <SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
                    <PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
                    <HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
                    <AlternatingRowStyle BackColor="White" ForeColor="#284775" />
                </asp:GridView>
                <asp:Label ID="Label2" runat="server" Width="150px"></asp:Label>
                <asp:Label ID="Label3" runat="server" Width="71px"></asp:Label>
                &nbsp; &nbsp;
                <asp:Label ID="Label4" runat="server" Width="77px"></asp:Label>
                &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;<asp:Button
                    ID="Button1" runat="server" Text="删除" Width="45px" OnClick="Button1_Click" CausesValidation="False" /></td>
        </tr>
        <tr>
            <td style="height: 160px; width: 622px;" >
                <br />
                <table border="1" cellpadding="0" cellspacing="0" style="width: 317px; height: 136px">
                    <tr>
                        <td colspan="2" style="background-color: #c9c9c9; height: 26px;">
                            添加管理员</td>
                    </tr>
                    <tr>
                        <td style="width: 100px; text-align: right; height: 47px;">
                            管理员:</td>
                        <td style="text-align: left; width: 213px; height: 47px;" >
                            <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
                            <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="TextBox1"
                                ErrorMessage="**"></asp:RequiredFieldValidator><br />
                            <asp:CustomValidator ID="CustomValidator1" runat="server" ControlToValidate="TextBox1"
                                ErrorMessage="用户名已存在!" Font-Size="12px" OnServerValidate="CustomValidator1_ServerValidate"
                                Width="84px"></asp:CustomValidator></td>
                    </tr>
                    <tr>
                        <td style="text-align: right; height: 47px;" >
                            密 &nbsp;&nbsp; 码:</td>
                        <td style="text-align: left; width: 213px; height: 47px;" >
                            <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
                            <asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ControlToValidate="TextBox2"
                                ErrorMessage="**"></asp:RequiredFieldValidator></td>
                    </tr>
                    <tr>
                        <td style="height: 46px; text-align: right" >
                            权 &nbsp;&nbsp; 限:</td>
                        <td style="width: 213px; height: 46px; text-align: left" >
                            <asp:RadioButtonList ID="RadioButtonList1" runat="server" Font-Size="Smaller" RepeatDirection="Horizontal"
                                TextAlign="Left" Width="189px">
                                <asp:ListItem Value="0" Selected>一般管理员</asp:ListItem>
                                <asp:ListItem Value="1">超级管理员</asp:ListItem>
                            </asp:RadioButtonList></td>
                    </tr>
                    <tr>
                        <td colspan="2" style="height: 36px">
                            <asp:Button ID="Button2" runat="server" OnClick="Button2_Click" Text="添加" Width="45px" /></td>
                    </tr>
                </table>
            </td>
        </tr>
    </table>
</asp:Content>

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值