GridView的Command命令集合
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
?
1 <form id="form1" runat="server">2 <div>
3 <asp:GridView ID="GridView1" runat="server">
4 </asp:GridView>
5 ?</div>
6 ?<br/>
7 ?<asp:Button ID="BtnExport" runat="server" OnClick="BtnExport_Click"
8 Text="Export to Excel" />
9 </form>
?
?
在default.aspx.cs中,寫入如下代碼:
?
1 protected void Page_Load(object sender, EventArgs e)2 {
3 if (!Page.IsPostBack)
4 {
5 BindData();
6 }
7 }
8 private void BindData()
9 {
10 string query = "SELECT * FROM customers";
11 SqlConnection myConnection = new SqlConnection(ConnectionString);
12 SqlDataAdapter ad = new SqlDataAdapter(query, myConnection);
13 DataSet ds = new DataSet();
14 ad.Fill(ds, "customers");
15 GridView1.DataSource = ds;
16 GridView1.DataBind();
17 }
18
19 public override void VerifyRenderingInServerForm(Control control)
20 {
21 // Confirms that an HtmlForm control is rendered for
22 }
23
24 protected void Button1_Click(object sender, EventArgs e)
25 {
26 Response.Clear();
27 Response.AddHeader("content-disposition","attachment;filename=FileName.xls");
28 Response.Charset = "gb2312";
29 Response.ContentType = "application/vnd.xls";
30 System.IO.StringWriter stringWrite = new System.IO.StringWriter();
31 System.Web.UI.HtmlTextWriter htmlWrite =new HtmlTextWriter(stringWrite);
32
33 GridView1.AllowPaging = false;
34 BindData();
35 GridView1.RenderControl(htmlWrite);
36
37 Response.Write(stringWrite.ToString());
38 Response.End();
39 GridView1.AllowPaging = true;
40 BindData();
41 }
42 protected void paging(object sender,GridViewPageEventArgs e)
43 {
44 GridView1.PageIndex = e.NewPageIndex;
45 BindData();
46 }
47
48
?
?
在上面的代碼中,我們首先將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控件,并輸出它們的值。
?
1 public DataSet PopulateDropDownList()2 {
3 SqlConnection myConnection =new SqlConnection(ConfigurationManager.ConnectionStrings["MyDatabase"].ConnectionString);
4 SqlDataAdapter ad = new SqlDataAdapter("SELECT * FROM tblPhone", myConnection);
5 DataSet ds = new DataSet();
6 ad.Fill(ds, "tblPhone");
7 return ds;
8 }
9
10
?
?
上面的代碼首先將數(shù)據(jù)庫中tblphone表的數(shù)據(jù)以dataset的形式返回。然后在頁面的itemtemplate中,如下設(shè)計(jì):
?
1 <ItemTemplate>2 <asp:DropDownList ID="DropDownList1" runat="server" DataSource="<%# PopulateDropDownList() %>"
3 DataTextField="Phone" DataValueField = "PhoneID">
4 </asp:DropDownList>
5 </ItemTemplate>
?
?
?
這里注意dropdownlist控件的datasource屬性綁定了剛才返回的dataset(調(diào)用了populatedropdownlist()方法),并要注意設(shè)置好datatextfield和datavaluefield屬性。
然后,在button的事件中,寫入以下代碼:
?
1 protected void Button2_Click(object sender, EventArgs e)2 {
3 StringBuilder str = new StringBuilder();
4 foreach (GridViewRow gvr in GridView1.Rows)
5 {
6 string selectedText = ((DropDownList)gvr.FindControl("DropDownList1")).SelectedItem.Text;
7 str.Append(selectedText);
8 }
9 Response.Write(str.ToString());
10 }
11
12
?
?
這里,我們用循環(huán),來獲得每一行的dropdownlist控件的值,并且將值添加到字符串中最后輸出。
接著,我們來看下如何訪問gridview控件中的checkbox控件。經(jīng)常在gridview控件中,需要給用戶多項(xiàng)選擇的功能,這個(gè)時(shí)候就需要使用checkbox控件。首先我們建立一個(gè)模版列,其中有checkbox如下:
?
1 <asp:GridView ID="GridView1" runat="server" AllowPaging="True" AllowSorting="True"2 AutoGenerateColumns="False" DataKeyNames="PersonID" DataSourceID="mySource" Width="366px" CellPadding="4" ForeColor="#333333" GridLines="None">
3 <Columns>
4 <asp:CommandField ShowSelectButton="True" />
5 <asp:BoundField DataField="PersonID" HeaderText="PersonID" InsertVisible="False"
6 ReadOnly="True" SortExpression="PersonID" />
7 <asp:BoundField DataField="Name" HeaderText="Name" SortExpression="Name" />
8 <asp:TemplateField HeaderText="Select">
9 <ItemTemplate>
10 <asp:CheckBox ID="chkSelect" runat="server" />
11 </ItemTemplate>
12 <HeaderTemplate>
13 </HeaderTemplate>
14 </asp:TemplateField>
15 </Columns>
16 </asp:GridView>
?
?
為了示意性地講解如何得到用戶選擇的checkbox,可以增加一個(gè)按鈕,當(dāng)用戶選擇gridview中的選項(xiàng)后,點(diǎn)該按鈕,則可以輸出用戶選了哪些選項(xiàng),在按鈕的CLICK事件中寫入如下代碼:
?
1 for (int i = 0; i < GridView1.Rows.Count; i++)2 {
3 GridViewRow row = GridView1.Rows[i];
4 bool isChecked = ((CheckBox) row.FindControl("chkSelect")).Checked;
5 if (isChecked)
6 {
7 str.Append(GridView1.Rows[i].Cells[2].Text);
8 }
9 }
10 Response.Write(str.ToString());
?
?
接下來,我們添加一個(gè)全選的選擇框,當(dāng)用戶選擇該框時(shí),可以全部選擇gridview中的checkbox.首先我們?cè)趆eadtemplate中如下設(shè)計(jì):
<HeaderTemplate>
<input id="chkAll" οnclick="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.
轉(zhuǎn)載于:https://www.cnblogs.com/xuwb/archive/2010/08/09/1796098.html
總結(jié)
以上是生活随笔為你收集整理的GridView的Command命令集合的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: .net DataGrid绑定列手动添加
- 下一篇: 关于 URL 的一些不可不知的知识