Asp.net 2.0中新增的gridview控件,是十分強(qiáng)大的數(shù)據(jù)展示控件,在前面的系列文章里,分別展示了其中很多的基本用法和技巧(詳見<<ASP.NET 2.0中Gridview控件高級(jí)技巧>>、<<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報(bào)表中去,在asp.net 2.0中,同樣可以很方便地實(shí)現(xiàn)將整個(gè)gridview中的內(nèi)容導(dǎo)出到excel報(bào)表中去,下面介紹其具體做法:
首先,建立基本的頁面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時(shí),先將gridview的allowpaging屬性設(shè)置為false,然后通過頁面流的方式導(dǎo)出當(dāng)前頁的gridview到excel中,最后再重新設(shè)置其allowpaging屬性。另外要注意的是,要寫一個(gè)空的VerifyRenderingInServerForm方法(必須寫),以確認(rèn)在運(yùn)行時(shí)為指定的ASP.NET 服務(wù)器控件呈現(xiàn)HtmlForm 控件。
二、訪問gridview中的各類控件 在gridview中,經(jīng)常要訪問其中的各類控件,比如dropdownlist,radiobutton,checkbox等,下面歸納下在gridview中訪問各類控件的方法。
首先看下如何在gridview中訪問dropdownlist控件。假設(shè)在一個(gè)gridviw中,展現(xiàn)的每條記錄中都需要供用戶用下拉選擇的方式選擇dropdownlist控件中的內(nèi)容,則可以使用如下代碼,當(dāng)用戶選擇好gridview中的dropdownlist控件的選項(xiàng)后,點(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è)計(jì):
<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控件中,需要給用戶多項(xiàng)選擇的功能,這個(gè)時(shí)候就需要使用checkbox控件。首先我們建立一個(gè)模版列,其中有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,可以增加一個(gè)按鈕,當(dāng)用戶選擇gridview中的選項(xiàng)后,點(diǎn)該按鈕,則可以輸出用戶選了哪些選項(xiàng),在按鈕的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()); |
接下來,我們添加一個(gè)全選的選擇框,當(dāng)用戶選擇該框時(shí),可以全部選擇gridview中的checkbox.首先我們?cè)趆eadtemplate中如下設(shè)計(jì):
<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中,我們都希望能在刪除記錄時(shí),能彈出提示框予以提示,在asp.net 1.1中,都可以很容易實(shí)現(xiàn),那么在asp.net 2.0中要如何實(shí)現(xiàn)呢?下面舉例子說明,首先在HTML頁面中設(shè)計(jì)好如下代碼:
<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> |
在上面的代碼中,我們?cè)O(shè)置了一個(gè)鏈接linkbutton,其中指定了commandname為"Delete",commandargument為要?jiǎng)h除的記錄的ID編號(hào),注意一旦commandname設(shè)置為delete這個(gè)名稱后,gridview中的GridView_RowCommand 和 GridView_Row_Deleting 事件都會(huì)被激發(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("是否要?jiǎng)h除該記錄? " + DataBinder.Eval(e.Row.DataItem, "id") + "')"); } } |
在這段代碼中,首先檢查是否是datarow,是的話則得到每個(gè)linkbutton,再為其添加客戶端代碼,基本和asp.net 1.1的做法差不多。
之后,當(dāng)用戶選擇了確認(rèn)刪除后,我們有兩種方法對(duì)其進(jìn)行繼續(xù)的后續(xù)刪除處理,因?yàn)槲覀儗h除按鈕設(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); } |
要注意的是,這個(gè)必須將datakeynames設(shè)置為要?jiǎng)h除記錄的編號(hào),這里是categoryid.