302班

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

          GridView的Command命令集合

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

            一、Gridview中的內(nèi)容導(dǎo)出到Excel

            在日常工作中,經(jīng)常要將gridview中的內(nèi)容導(dǎo)出到excel報表中去,在asp.net 2.0中,同樣可以很方便地實(shí)現(xiàn)將整個gridview中的內(nèi)容導(dǎo)出到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綁定到指定的數(shù)據(jù)源中,然后在button1的按鈕(用來做導(dǎo)出到EXCEL的)的事件中,寫入相關(guān)的代碼。這里使用Response.AddHeader("content-disposition","attachment;filename=exporttoexcel.xls");中的filename來指定將要導(dǎo)出的excel的文件名,這里是exporttoexcel.xls。要注意的是,由于gridview的內(nèi)容可能是分頁顯示的,因此,這里在每次導(dǎo)出excel時,先將gridview的allowpaging屬性設(shè)置為false,然后通過頁面流的方式導(dǎo)出當(dāng)前頁的gridview到excel中,最后再重新設(shè)置其allowpaging屬性。另外要注意的是,要寫一個空的VerifyRenderingInServerForm方法(必須寫),以確認(rèn)在運(yùn)行時為指定的ASP.NET 服務(wù)器控件呈現(xiàn)HtmlForm 控件。

            二、訪問gridview中的各類控件

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

            首先看下如何在gridview中訪問dropdownlist控件。假設(shè)在一個gridviw中,展現(xiàn)的每條記錄中都需要供用戶用下拉選擇的方式選擇dropdownlist控件中的內(nèi)容,則可以使用如下代碼,當(dāng)用戶選擇好gridview中的dropdownlist控件的選項后,點(diǎn)擊按鈕,則系統(tǒng)打印出用戶到底選擇了哪些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;
          }

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

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

            這里注意dropdownlist控件的datasource屬性綁定了剛才返回的dataset(調(diào)用了populatedropdownlist()方法),并要注意設(shè)置好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());
          }

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

            接著,我們來看下如何訪問gridview控件中的checkbox控件。經(jīng)常在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,可以增加一個按鈕,當(dāng)用戶選擇gridview中的選項后,點(diǎn)該按鈕,則可以輸出用戶選了哪些選項,在按鈕的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());

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

          <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中,都可以很容易實(shí)現(xiàn),那么在asp.net 2.0中要如何實(shí)現(xiàn)呢?下面舉例子說明,首先在HTML頁面中設(shè)計好如下代碼:

          <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>

            在上面的代碼中,我們設(shè)置了一個鏈接linkbutton,其中指定了commandname為"Delete",commandargument為要刪除的記錄的ID編號,注意一旦commandname設(shè)置為delete這個名稱后,gridview中的GridView_RowCommand 和 GridView_Row_Deleting 事件都會被激發(fā)接者,我們處理其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的做法差不多。

            之后,當(dāng)用戶選擇了確認(rèn)刪除后,我們有兩種方法對其進(jìn)行繼續(xù)的后續(xù)刪除處理,因為我們將刪除按鈕設(shè)置為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設(shè)置為要刪除記錄的編號,這里是categoryid.

          主站蜘蛛池模板: 大英县| 镇安县| 宁强县| 临潭县| 祁阳县| 哈巴河县| 郓城县| 秦安县| 北宁市| 兴安县| 兴山县| 蒙山县| 扶沟县| 昌邑市| 南漳县| 宜兴市| 耒阳市| 涞水县| 剑阁县| 海城市| 洛浦县| 叙永县| 卫辉市| 本溪市| 万宁市| 长阳| 乐安县| 隆德县| 东阳市| 临沂市| 固安县| 铁力市| 新津县| 贡觉县| 文水县| 准格尔旗| 壶关县| 高邑县| 青浦区| 威海市| 红原县|