302班

          java突擊隊
          posts - 151, comments - 74, trackbacks - 0, articles - 14
            BlogJava :: 首頁 :: 新隨筆 :: 聯系 :: 聚合  :: 管理

          GridView的Command命令集合

          Posted on 2007-04-19 11:30 停留的風 閱讀(2090) 評論(0)  編輯  收藏 所屬分類: .NET技術
          Asp.net 2.0中新增的gridview控件,是十分強大的數據展示控件,在前面的系列文章里,分別展示了其中很多的基本用法和技巧(詳見<<ASP.NET 2.0中Gridview控件高級技巧>>、<<ASP.NET2.0利用Gridview實現主從關系>>)。在本文中,將繼續探討有關的技巧。

            一、Gridview中的內容導出到Excel

            在日常工作中,經常要將gridview中的內容導出到excel報表中去,在asp.net 2.0中,同樣可以很方便地實現將整個gridview中的內容導出到excel報表中去,下面介紹其具體做法:

            首先,建立基本的頁面default.aspx

          <form id="form1" runat="server">
          <div>
          <asp:GridView ID="GridView1" runat="server">
          </asp:GridView>
          </div>
          <br/>
          <asp:Button ID="BtnExport" runat="server" OnClick="BtnExport_Click"
          Text="Export to Excel" />
          </form>

            在default.aspx.cs中,寫入如下代碼:

          protected void Page_Load(object sender, EventArgs e)
          {
           if (!Page.IsPostBack)
           {
            BindData();
           }
          }
          private void BindData()
          {
           string query = "SELECT * FROM customers";
           SqlConnection myConnection = new SqlConnection(ConnectionString);
           SqlDataAdapter ad = new SqlDataAdapter(query, myConnection);
           DataSet ds = new DataSet();
           ad.Fill(ds, "customers");
           GridView1.DataSource = ds;
           GridView1.DataBind();
          }

          public override void VerifyRenderingInServerForm(Control control)
          {
           // Confirms that an HtmlForm control is rendered for
          }

          protected void Button1_Click(object sender, EventArgs e)
          {
           Response.Clear();
           Response.AddHeader("content-disposition","attachment;filename=FileName.xls");
           Response.Charset = "gb2312";
           Response.ContentType = "application/vnd.xls";
           System.IO.StringWriter stringWrite = new System.IO.StringWriter();
           System.Web.UI.HtmlTextWriter htmlWrite =new HtmlTextWriter(stringWrite);

           GridView1.AllowPaging = false;
           BindData();
           GridView1.RenderControl(htmlWrite);

           Response.Write(stringWrite.ToString());
           Response.End();
           GridView1.AllowPaging = true;
           BindData();
          }
          protected void paging(object sender,GridViewPageEventArgs e)
          {
           GridView1.PageIndex = e.NewPageIndex;
           BindData();
          }

            在上面的代碼中,我們首先將gridview綁定到指定的數據源中,然后在button1的按鈕(用來做導出到EXCEL的)的事件中,寫入相關的代碼。這里使用Response.AddHeader("content-disposition","attachment;filename=exporttoexcel.xls");中的filename來指定將要導出的excel的文件名,這里是exporttoexcel.xls。要注意的是,由于gridview的內容可能是分頁顯示的,因此,這里在每次導出excel時,先將gridview的allowpaging屬性設置為false,然后通過頁面流的方式導出當前頁的gridview到excel中,最后再重新設置其allowpaging屬性。另外要注意的是,要寫一個空的VerifyRenderingInServerForm方法(必須寫),以確認在運行時為指定的ASP.NET 服務器控件呈現HtmlForm 控件。

            二、訪問gridview中的各類控件

            在gridview中,經常要訪問其中的各類控件,比如dropdownlist,radiobutton,checkbox等,下面歸納下在gridview中訪問各類控件的方法。

            首先看下如何在gridview中訪問dropdownlist控件。假設在一個gridviw中,展現的每條記錄中都需要供用戶用下拉選擇的方式選擇dropdownlist控件中的內容,則可以使用如下代碼,當用戶選擇好gridview中的dropdownlist控件的選項后,點擊按鈕,則系統打印出用戶到底選擇了哪些dropdownlist控件,并輸出它們的值。

          public DataSet PopulateDropDownList()
          {
           SqlConnection myConnection =new SqlConnection(ConfigurationManager.ConnectionStrings["MyDatabase"].ConnectionString);
           SqlDataAdapter ad = new SqlDataAdapter("SELECT * FROM tblPhone", myConnection);
           DataSet ds = new DataSet();
           ad.Fill(ds, "tblPhone");
           return ds;
          }

            上面的代碼首先將數據庫中tblphone表的數據以dataset的形式返回。然后在頁面的itemtemplate中,如下設計:

          <ItemTemplate>
          <asp:DropDownList ID="DropDownList1" runat="server" DataSource="<%# PopulateDropDownList() %>"
          DataTextField="Phone" DataValueField = "PhoneID">
          </asp:DropDownList>
          </ItemTemplate>

            這里注意dropdownlist控件的datasource屬性綁定了剛才返回的dataset(調用了populatedropdownlist()方法),并要注意設置好datatextfield和datavaluefield屬性。

            然后,在button的事件中,寫入以下代碼:

          protected void Button2_Click(object sender, EventArgs e)
          {
           StringBuilder str = new StringBuilder();
           foreach (GridViewRow gvr in GridView1.Rows)
           {
            string selectedText = ((DropDownList)gvr.FindControl("DropDownList1")).SelectedItem.Text;
            str.Append(selectedText);
           }
           Response.Write(str.ToString());
          }

            這里,我們用循環,來獲得每一行的dropdownlist控件的值,并且將值添加到字符串中最后輸出。

            接著,我們來看下如何訪問gridview控件中的checkbox控件。經常在gridview控件中,需要給用戶多項選擇的功能,這個時候就需要使用checkbox控件。首先我們建立一個模版列,其中有checkbox如下:

          <asp:GridView ID="GridView1" runat="server" AllowPaging="True" AllowSorting="True"
          AutoGenerateColumns="False" DataKeyNames="PersonID" DataSourceID="mySource" Width="366px" CellPadding="4" ForeColor="#333333" GridLines="None">
          <Columns>
          <asp:CommandField ShowSelectButton="True" />
          <asp:BoundField DataField="PersonID" HeaderText="PersonID" InsertVisible="False"
          ReadOnly="True" SortExpression="PersonID" />
          <asp:BoundField DataField="Name" HeaderText="Name" SortExpression="Name" />
          <asp:TemplateField HeaderText="Select">
          <ItemTemplate>
          <asp:CheckBox ID="chkSelect" runat="server" />
          </ItemTemplate>
          <HeaderTemplate>
          </HeaderTemplate>
          </asp:TemplateField>
          </Columns>
          </asp:GridView>

            為了示意性地講解如何得到用戶選擇的checkbox,可以增加一個按鈕,當用戶選擇gridview中的選項后,點該按鈕,則可以輸出用戶選了哪些選項,在按鈕的CLICK事件中寫入如下代碼:

          for (int i = 0; i < GridView1.Rows.Count; i++)
          {
           GridViewRow row = GridView1.Rows[i];
           bool isChecked = ((CheckBox) row.FindControl("chkSelect")).Checked;
           if (isChecked)
           {
            str.Append(GridView1.Rows[i].Cells[2].Text);
           }
          }
          Response.Write(str.ToString());

            接下來,我們添加一個全選的選擇框,當用戶選擇該框時,可以全部選擇gridview中的checkbox.首先我們在headtemplate中如下設計:

          <HeaderTemplate>
          <input id="chkAll" onclick="javascript:SelectAllCheckboxes(this);" runat="server" type="checkbox" />
          </HeaderTemplate>

            javascript部分的代碼如下所示:

          <script language=javascript>
          function SelectAllCheckboxes(spanChk){
           var oItem = spanChk.children;
           var theBox=(spanChk.type=="checkbox")?spanChk:spanChk.children.item[0];
           xState=theBox.checked;
           elm=theBox.form.elements;
           for(i=0;i<elm.length;i++)
           if(elm[i].type=="checkbox" && elm[i].id!=theBox.id)
           {
            if(elm[i].checked!=xState)
            elm[i].click();
           }
          }
          </script>

           三、gridview中刪除記錄的處理

            在gridview中,我們都希望能在刪除記錄時,能彈出提示框予以提示,在asp.net 1.1中,都可以很容易實現,那么在asp.net 2.0中要如何實現呢?下面舉例子說明,首先在HTML頁面中設計好如下代碼:

          <asp:GridView DataKeyNames="CategoryID" ID="GridView1" runat="server" AutoGenerateColumns="False" OnRowCommand="GridView1_RowCommand" OnRowDataBound="GridView1_RowDataBound" OnRowDeleted="GridView1_RowDeleted" OnRowDeleting="GridView1_RowDeleting">
          <Columns>
          <asp:BoundField DataField="CategoryID" HeaderText="CategoryID" />
          <asp:BoundField DataField="CategoryName" HeaderText="CategoryName" />
          <asp:TemplateField HeaderText="Select">
          <ItemTemplate>
          <asp:LinkButton ID="LinkButton1" CommandArgument='<%# Eval("CategoryID") %>' CommandName="Delete" runat="server">Delete</asp:LinkButton>
          </ItemTemplate>
          </asp:TemplateField>
          </Columns>
          </asp:GridView>

            在上面的代碼中,我們設置了一個鏈接linkbutton,其中指定了commandname為"Delete",commandargument為要刪除的記錄的ID編號,注意一旦commandname設置為delete這個名稱后,gridview中的GridView_RowCommand 和 GridView_Row_Deleting 事件都會被激發接者,我們處理其rowdatabound事件中:

          protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
          {
           if (e.Row.RowType == DataControlRowType.DataRow)
           {
            LinkButton l = (LinkButton)e.Row.FindControl("LinkButton1");
            l.Attributes.Add('onclick", "javascript:return " + "confirm("是否要刪除該記錄? " +
            DataBinder.Eval(e.Row.DataItem, "id") + "')");
           }
          }

            在這段代碼中,首先檢查是否是datarow,是的話則得到每個linkbutton,再為其添加客戶端代碼,基本和asp.net 1.1的做法差不多。

            之后,當用戶選擇了確認刪除后,我們有兩種方法對其進行繼續的后續刪除處理,因為我們將刪除按鈕設置為Delete,方法一是在row_command事件中寫入如下代碼:

          protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
          {
           if (e.CommandName == "Delete")
           {
            int id = Convert.ToInt32(e.CommandArgument);
            // 刪除記錄的專門過程
            DeleteRecordByID(id);
           }
          }

            另外一種方法是使用gridview的row_deletting事件,先在頁面HTML代碼中,添加<asp:GridView DataKeyNames="CategoryID" ID="GridView1" runat="server" AutoGenerateColumns="False" OnRowCommand="GridView1_RowCommand" OnRowDataBound="GridView1_RowDataBound" onRowDeleting="GridView1_RowDeleting">
          然后添加row_deleting事件:

          protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
          {
           int categoryID = (int) GridView1.DataKeys[e.RowIndex].Value;
           DeleteRecordByID(categoryID);
          }

            要注意的是,這個必須將datakeynames設置為要刪除記錄的編號,這里是categoryid.

          主站蜘蛛池模板: 绿春县| 康平县| 泾川县| 开阳县| 云梦县| 兴和县| 贡山| 五大连池市| 乡城县| 怀仁县| 陵水| 锡林郭勒盟| 兖州市| 余江县| 曲阳县| 灵台县| 临颍县| 屏南县| 维西| 济阳县| 泽普县| 儋州市| 南皮县| 康平县| 京山县| 叶城县| 视频| 芦溪县| 宁远县| 彩票| 凌源市| 中牟县| 房产| 屯门区| 牙克石市| 庆云县| 崇阳县| 田林县| 正阳县| 惠来县| 钦州市|