GridView 用法一

前臺: testGridView.aspx

  1<%@ Page Language="C#" AutoEventWireup="true" CodeFile="testGridView.aspx.cs" Inherits="testGridView" %>
  2
  3<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  4
  5<html xmlns="http://www.w3.org/1999/xhtml" >
  6<head runat="server">
  7    <title>無標題頁</title>
  8    <style type="text/css">
  9        td{
 10            font-size:12px;
 11        }

 12    
</style>
 13</head>
 14<body>
 15    <form id="form1" runat="server">
 16    <div>
 17        <asp:GridView ID="GridView1" runat="server" AllowPaging="True" PageSize="2" AutoGenerateColumns="False"
 18            BackColor="White" BorderColor="#CCCCCC" BorderStyle="None" BorderWidth="1px"
 19            CellPadding="3" DataKeyNames="id" DataSourceID="SqlDataSource1" OnRowCreated="GridView1_RowCreated" OnRowDataBound="GridView1_RowDataBound">
 20            <FooterStyle BackColor="White" ForeColor="#000066" />
 21            <Columns>
 22                <asp:CommandField HeaderText="編輯" ShowDeleteButton="True" ShowEditButton="True" />
 23                <asp:BoundField DataField="id" HeaderText="用戶ID" InsertVisible="False" ReadOnly="True"
 24                    SortExpression="id" />
 25                <asp:BoundField DataField="username" HeaderText="用戶名" SortExpression="username" >
 26                    <ItemStyle BackColor="LightSkyBlue" BorderColor="#FFC0C0" BorderStyle="Dotted" ForeColor="Navy" />
 27                </asp:BoundField>
 28                <asp:BoundField DataField="TJname" HeaderText="性別" SortExpression="sex" />
 29                <asp:BoundField DataField="age" HeaderText="年齡" SortExpression="age" />
 30                <asp:BoundField DataField="intro" HeaderText="介紹" SortExpression="intro" />
 31                <asp:BoundField DataField="submitTime" HeaderText="加入日期" SortExpression="submitTime" DataFormatString="{0:y}" HtmlEncode="False"/>
 32                <asp:TemplateField HeaderText="註冊時間">
 33                    <ItemTemplate>
 34                        <asp:Label ID="subTime" runat="server" Text='<%# Bind("submitTime", "{0:d}") %>'></asp:Label>
 35                    </ItemTemplate>
 36                </asp:TemplateField>
 37                <asp:CheckBoxField DataField="vip" HeaderText="vip會員" ShowHeader="False" SortExpression="vip" />
 38                <asp:TemplateField HeaderText="自定義(Sex)">
 39                    <ItemTemplate>
 40                        <asp:Label ID="Label1" runat="server" Text='<%# Convert.ToInt32(Eval("sex"))==1?"推薦":"不推薦" %>'></asp:Label>
 41                    </ItemTemplate>
 42                </asp:TemplateField>
 43                <asp:TemplateField>
 44                    <HeaderTemplate>
 45                        <asp:CheckBox ID="chkAll" runat="server" AutoPostBack="True" OnCheckedChanged="chkAll_CheckedChanged"
 46                            Text="全選" />
 47                    </HeaderTemplate>
 48                    <ItemTemplate>
 49                        <asp:CheckBox ID="itemChk" runat="server" Text=""/>
 50                    </ItemTemplate>
 51                </asp:TemplateField>
 52                <asp:TemplateField HeaderText="此列顯示HTML代碼">
 53                    <ItemTemplate>
 54                        <asp:Literal ID="Literal1" runat="server" Mode="Encode" Text="<B><p>Html Code</p></B>"></asp:Literal>
 55                    </ItemTemplate>
 56                </asp:TemplateField>
 57            </Columns>
 58            <RowStyle ForeColor="#000066" />
 59            <SelectedRowStyle BackColor="#669999" Font-Bold="True" ForeColor="White" />
 60            <PagerStyle BackColor="White" ForeColor="#000066" HorizontalAlign="Left" />
 61            <HeaderStyle BackColor="#006699" Font-Bold="False" ForeColor="#FFFFC0" Font-Size="13px" />
 62            <EmptyDataTemplate>
 63                沒有數據嗎
 64            </EmptyDataTemplate>
 65        </asp:GridView>
 66        <br />
 67        共<asp:Label ID="Label2" runat="server" Text=""><%=GridView1.PageCount %></asp:Label>頁,當前是第<asp:Label
 68            ID="Label3" runat="server" Text=""><%=GridView1.PageIndex+1 %></asp:Label>頁.<br />
 69        <br />
 70        <asp:DropDownList ID="DropDownList1" runat="server">
 71        </asp:DropDownList>
 72        &nbsp;&nbsp;
 73        <asp:Button ID="btnYuc" runat="server" OnClick="btnYuc_Click" Text="隱藏選定的列" />
 74        &nbsp;
 75        <asp:Button ID="btnShow" runat="server" OnClick="btnShow_Click" Text="顯示全部列" />
 76        &nbsp;
 77        <asp:Button ID="btnDele" runat="server" Text="刪除所選的列" OnClientClick=" return window.confirm('女人 ');" OnClick="btnDele_Click" /><br />
 78        <br />
 79        www.verycd.com
 80    
 81    </div>
 82        <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:digConnectionString %>"
 83            SelectCommand="select *, TJname=(CASE when sex=1 then '男人' when  sex=0 then '女人' end) from test" DeleteCommand="DELETE FROM [test] WHERE [id] = @id" InsertCommand="INSERT INTO [test] ([id], [username], [sex], [age], [intro], [submitTime], [vip]) VALUES (@id, @username, @sex, @age, @intro, @submitTime, @vip)" UpdateCommand="UPDATE [test] SET [username] = @username, [sex] = @sex, [age] = @age, [intro] = @intro, [submitTime] = @submitTime, [vip] = @vip WHERE [id] = @id">
 84            <DeleteParameters>
 85                <asp:Parameter Name="id" Type="Int32" />
 86            </DeleteParameters>
 87            <UpdateParameters>
 88                <asp:Parameter Name="username" Type="String" />
 89                <asp:Parameter Name="sex" Type="Byte" />
 90                <asp:Parameter Name="age" Type="Int32" />
 91                <asp:Parameter Name="intro" Type="String" />
 92                <asp:Parameter Name="submitTime" Type="DateTime" />
 93                <asp:Parameter Name="vip" Type="Boolean" />
 94                <asp:Parameter Name="id" Type="Int32" />
 95            </UpdateParameters>
 96            <InsertParameters>
 97                <asp:Parameter Name="id" Type="Int32" />
 98                <asp:Parameter Name="username" Type="String" />
 99                <asp:Parameter Name="sex" Type="Byte" />
100                <asp:Parameter Name="age" Type="Int32" />
101                <asp:Parameter Name="intro" Type="String" />
102                <asp:Parameter Name="submitTime" Type="DateTime" />
103                <asp:Parameter Name="vip" Type="Boolean" />
104            </InsertParameters>
105        </asp:SqlDataSource>
106        &nbsp; &nbsp;
107    </form>
108</body>
109</html>
110

後臺: testGridView.aspx.cs

  1using System;
  2using System.Data;
  3using System.Configuration;
  4using System.Collections;
  5using System.Web;
  6using System.Web.Security;
  7using System.Web.UI;
  8using System.Web.UI.WebControls;
  9using System.Web.UI.WebControls.WebParts;
 10using System.Web.UI.HtmlControls;
 11
 12public partial class testGridView : System.Web.UI.Page
 13{
 14    protected void Page_Load(object sender, EventArgs e)
 15    {
 16        if (!IsPostBack)
 17        {
 18            for (int i = 1; i <= GridView1.Columns.Count;i++ )
 19            {
 20                DropDownList1.Items.Add(i.ToString());
 21            }

 22        }

 23    }

 24    public string returnSex(int i)
 25    
 26        return i==0?"":"";
 27      
 28        
 29    }

 30    protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
 31    {
 32        //效果:增加鼠標所在行的樣式.
 33        //先判斷是否是數據行
 34        if(e.Row.RowType==DataControlRowType.DataRow)
 35        {
 36            e.Row.Attributes.Add("onmouseover","c=this.style.backgroundColor;this.style.backgroundColor='#EFEFEF'");
 37            e.Row.Attributes.Add("onmouseout","this.style.backgroundColor=c;");
 38        }

 39    }

 40    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
 41    {
 42        //效果:特定列的樣式,比如你的哪一個列的樣式
 43        for (int i = 0; i < GridView1.Rows.Count;i++)
 44        {
 45            //注意這裏的寫法,取得綁定的某列的值,要轉換爲字符串型.
 46            //寫法: Convert.String(DataBinder.Eval(e.Row.DataItem,"字段名"));
 47            string lbl = Convert.ToString(DataBinder.Eval(e.Row.DataItem,"userName"));
 48            if (lbl == "DotNet")
 49            {
 50                e.Row.BackColor = System.Drawing.Color.LightBlue;   //指定顏色.
 51            }

 52        }

 53
 54    }

 55    protected void btnYuc_Click(object sender, EventArgs e)
 56    {
 57        int clo=int.Parse(DropDownList1.SelectedValue)-1;
 58        /*這樣寫有問題,當你點了一列隱藏後,再隱藏其他列,原來的列還是隱藏的
 59        
 60         GridView1.Columns[clo].Visible = false;
 61        
 62         */

 63        //下面這方法是每一種狀態下,最多隻能隱藏一個列
 64        //如果第二次隱藏列,原來被隱藏的列又顯示回來
 65
 66        for (int i = 0; i < GridView1.Columns.Count;i++ )
 67        {
 68            if (i == clo)
 69            {
 70                GridView1.Columns[i].Visible = false;
 71            }

 72            else
 73            {
 74                GridView1.Columns[i].Visible = true;
 75            }

 76        }

 77
 78    }

 79    protected void btnShow_Click(object sender, EventArgs e)
 80    {
 81        //顯示全部列.
 82        for(int i=0;i<GridView1.Columns.Count;i++)
 83        {
 84            GridView1.Columns[i].Visible = true;
 85        }

 86    }

 87
 88    protected void chkAll_CheckedChanged(object sender, EventArgs e)
 89    {
 90        //注意這裏的寫法/
 91        //CheckBox chkAll = (CheckBox)GridView1.Cells[10].FindControl("chkAll");
 92        CheckBox chkAll = (CheckBox)GridView1.HeaderRow.Cells[10].FindControl("chkAll");
 93
 94        if (chkAll.Checked)
 95        {
 96            foreach (GridViewRow gr in GridView1.Rows)
 97            {
 98                CheckBox chk = (CheckBox)gr.Cells[10].FindControl("itemChk");
 99                if (!chk.Checked)//如果沒選中,就讓它選中
100                {
101                    chk.Checked = true;
102                }

103                ////else              //這裏我把它註釋掉了,因爲加了的話,選中的會被不選中了
104                ////{
105                ////    chk.Checked = false;
106                ////}

107            }

108        }

109        else //取消全選
110        {
111            foreach (GridViewRow gr in GridView1.Rows)
112            {
113                CheckBox chk = (CheckBox)gr.Cells[10].FindControl("itemChk");
114                chk.Checked = false;
115            }

116        }

117    }

118
119    protected void btnDele_Click(object sender, EventArgs e)
120    {
121        string id = "";
122        foreach(GridViewRow gr in GridView1.Rows)
123        {
124            CheckBox chk = (CheckBox)gr.Cells[10].FindControl("itemChk");
125            if(chk.Checked) //如果選中,則刪除
126            {
127                if (id == "")
128                {
129                    id += GridView1.DataKeys[gr.DataItemIndex].Value.ToString();
130                }

131                else
132                {
133                    id += "," + GridView1.DataKeys[gr.DataItemIndex].Value.ToString();
134                }

135            }

136        }

137       // Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "alert", " alert('" + id + "')");
138        Response.Write("您要刪除的記錄是:"+id);
139    }

140}

 
發佈了30 篇原創文章 · 獲贊 2 · 訪問量 4萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章