 
                    
                
         
    
    
    
   
   
   
   
   
	
    
        
        
 Asp.net 2.0中新增的gridview控件,是十分强大的数据展示控件,在前面的系列文章里,分别展示了其中很多的基本用法和技巧(详见<<ASP.NET 2.0中Gridview控件高级技巧>>、<<ASP.NET2.0利用Gridview实现主从关系>>)。在本文中,将继续探讨有关的技巧。
Asp.net 2.0中新增的gridview控件,是十分强大的数据展示控件,在前面的系列文章里,分别展示了其中很多的基本用法和技巧(详见<<ASP.NET 2.0中Gridview控件高级技巧>>、<<ASP.NET2.0利用Gridview实现主从关系>>)。在本文中,将继续探讨有关的技巧。 

 一、Gridview中的内容导出到Excel
  一、Gridview中的内容导出到Excel

 在日常工作中,经常要将gridview中的内容导出到excel报表中去,在asp.net 2.0中,同样可以很方便地实现将整个gridview中的内容导出到excel报表中去,下面介绍其具体做法:
  在日常工作中,经常要将gridview中的内容导出到excel报表中去,在asp.net 2.0中,同样可以很方便地实现将整个gridview中的内容导出到excel报表中去,下面介绍其具体做法: 

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

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

 在default.aspx.cs中,写入如下代码:
  在default.aspx.cs中,写入如下代码:

 protected void Page_Load(object sender, EventArgs e)
protected void Page_Load(object sender, EventArgs e)


 {
{
 if (!Page.IsPostBack)
 if (!Page.IsPostBack)

 
  {
{
 BindData();
  BindData();
 }
 }
 }
}
 private void BindData()
private void BindData()


 {
{
 string query = "SELECT * FROM customers";
 string query = "SELECT * FROM customers";
 SqlConnection myConnection = new SqlConnection(ConnectionString);
 SqlConnection myConnection = new SqlConnection(ConnectionString);
 SqlDataAdapter ad = new SqlDataAdapter(query, myConnection);
 SqlDataAdapter ad = new SqlDataAdapter(query, myConnection);
 DataSet ds = new DataSet();
 DataSet ds = new DataSet();
 ad.Fill(ds, "customers");
 ad.Fill(ds, "customers");
 GridView1.DataSource = ds;
 GridView1.DataSource = ds;
 GridView1.DataBind();
 GridView1.DataBind();
 }
}

 public override void VerifyRenderingInServerForm(Control control)
public override void VerifyRenderingInServerForm(Control control)


 {
{
 // Confirms that an HtmlForm control is rendered for
 // Confirms that an HtmlForm control is rendered for
 }
}

 protected void Button1_Click(object sender, EventArgs e)
protected void Button1_Click(object sender, EventArgs e)


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

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

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


 {
{
 GridView1.PageIndex = e.NewPageIndex;
 GridView1.PageIndex = e.NewPageIndex;
 BindData();
 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绑定到指定的数据源中,然后在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中的各类控件

 在gridview中,经常要访问其中的各类控件,比如dropdownlist,radiobutton,checkbox等,下面归纳下在gridview中访问各类控件的方法。
  在gridview中,经常要访问其中的各类控件,比如dropdownlist,radiobutton,checkbox等,下面归纳下在gridview中访问各类控件的方法。

 首先看下如何在gridview中访问dropdownlist控件。假设在一个gridviw中,展现的每条记录中都需要供用户用下拉选择的方式选择dropdownlist控件中的内容,则可以使用如下代码,当用户选择好gridview中的dropdownlist控件的选项后,点击按钮,则系统打印出用户到底选择了哪些dropdownlist控件,并输出它们的值。
  首先看下如何在gridview中访问dropdownlist控件。假设在一个gridviw中,展现的每条记录中都需要供用户用下拉选择的方式选择dropdownlist控件中的内容,则可以使用如下代码,当用户选择好gridview中的dropdownlist控件的选项后,点击按钮,则系统打印出用户到底选择了哪些dropdownlist控件,并输出它们的值。

 public DataSet PopulateDropDownList()
public DataSet PopulateDropDownList()


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

 上面的代码首先将数据库中tblphone表的数据以dataset的形式返回。然后在页面的itemtemplate中,如下设计:
  上面的代码首先将数据库中tblphone表的数据以dataset的形式返回。然后在页面的itemtemplate中,如下设计:

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

 这里注意dropdownlist控件的datasource属性绑定了刚才返回的dataset(调用了populatedropdownlist()方法),并要注意设置好datatextfield和datavaluefield属性。
  这里注意dropdownlist控件的datasource属性绑定了刚才返回的dataset(调用了populatedropdownlist()方法),并要注意设置好datatextfield和datavaluefield属性。

 然后,在button的事件中,写入以下代码:
  然后,在button的事件中,写入以下代码:

 protected void Button2_Click(object sender, EventArgs e)
protected void Button2_Click(object sender, EventArgs e) 


 {
{
 StringBuilder str = new StringBuilder();
 StringBuilder str = new StringBuilder(); 
 foreach (GridViewRow gvr in GridView1.Rows)
 foreach (GridViewRow gvr in GridView1.Rows)

 
  {
{
 string selectedText = ((DropDownList)gvr.FindControl("DropDownList1")).SelectedItem.Text;
  string selectedText = ((DropDownList)gvr.FindControl("DropDownList1")).SelectedItem.Text;
 str.Append(selectedText);
  str.Append(selectedText); 
 }
 }
 Response.Write(str.ToString());
 Response.Write(str.ToString()); 
 }
} 

 这里,我们用循环,来获得每一行的dropdownlist控件的值,并且将值添加到字符串中最后输出。
  这里,我们用循环,来获得每一行的dropdownlist控件的值,并且将值添加到字符串中最后输出。

 接着,我们来看下如何访问gridview控件中的checkbox控件。经常在gridview控件中,需要给用户多项选择的功能,这个时候就需要使用checkbox控件。首先我们建立一个模版列,其中有checkbox如下:
  接着,我们来看下如何访问gridview控件中的checkbox控件。经常在gridview控件中,需要给用户多项选择的功能,这个时候就需要使用checkbox控件。首先我们建立一个模版列,其中有checkbox如下:

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

 为了示意性地讲解如何得到用户选择的checkbox,可以增加一个按钮,当用户选择gridview中的选项后,点该按钮,则可以输出用户选了哪些选项,在按钮的CLICK事件中写入如下代码:
  为了示意性地讲解如何得到用户选择的checkbox,可以增加一个按钮,当用户选择gridview中的选项后,点该按钮,则可以输出用户选了哪些选项,在按钮的CLICK事件中写入如下代码:

 for (int i = 0; i < GridView1.Rows.Count; i++)
for (int i = 0; i < GridView1.Rows.Count; i++)


 {
{
 GridViewRow row = GridView1.Rows[i];
 GridViewRow row = GridView1.Rows[i];
 bool isChecked = ((CheckBox) row.FindControl("chkSelect")).Checked;
 bool isChecked = ((CheckBox) row.FindControl("chkSelect")).Checked;
 if (isChecked)
 if (isChecked)

 
  {
{
 str.Append(GridView1.Rows[i].Cells[2].Text);
  str.Append(GridView1.Rows[i].Cells[2].Text); 
 }
 } 
 }
}
 Response.Write(str.ToString());
Response.Write(str.ToString());  

 接下来,我们添加一个全选的选择框,当用户选择该框时,可以全部选择gridview中的checkbox.首先我们在headtemplate中如下设计:
  接下来,我们添加一个全选的选择框,当用户选择该框时,可以全部选择gridview中的checkbox.首先我们在headtemplate中如下设计:

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

 javascript部分的代码如下所示:
  javascript部分的代码如下所示:

 <script language=javascript>
<script language=javascript> 

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

 
  {
{
 if(elm[i].checked!=xState)
  if(elm[i].checked!=xState)
 elm[i].click();
  elm[i].click();
 }
 }
 }
}
 </script>
</script> 


 三、gridview中删除记录的处理
三、gridview中删除记录的处理

 在gridview中,我们都希望能在删除记录时,能弹出提示框予以提示,在asp.net 1.1中,都可以很容易实现,那么在asp.net 2.0中要如何实现呢?下面举例子说明,首先在HTML页面中设计好如下代码:
  在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">
<asp:GridView DataKeyNames="CategoryID" ID="GridView1" runat="server" AutoGenerateColumns="False" OnRowCommand="GridView1_RowCommand" OnRowDataBound="GridView1_RowDataBound" OnRowDeleted="GridView1_RowDeleted" OnRowDeleting="GridView1_RowDeleting"> 
 <Columns>
<Columns>
 <asp:BoundField DataField="CategoryID" HeaderText="CategoryID" />
<asp:BoundField DataField="CategoryID" HeaderText="CategoryID" />
 <asp:BoundField DataField="CategoryName" HeaderText="CategoryName" />
<asp:BoundField DataField="CategoryName" HeaderText="CategoryName" />
 <asp:TemplateField HeaderText="Select">
<asp:TemplateField HeaderText="Select">
 <ItemTemplate>
<ItemTemplate>
 <asp:LinkButton ID="LinkButton1" CommandArgument='<%# Eval("CategoryID") %>' CommandName="Delete" runat="server">Delete</asp:LinkButton>
<asp:LinkButton ID="LinkButton1" CommandArgument='<%# Eval("CategoryID") %>' CommandName="Delete" runat="server">Delete</asp:LinkButton>
 </ItemTemplate>
</ItemTemplate>
 </asp:TemplateField>
</asp:TemplateField>
 </Columns>
</Columns>
 </asp:GridView>
</asp:GridView> 

 在上面的代码中,我们设置了一个链接linkbutton,其中指定了commandname为"Delete",commandargument为要删除的记录的ID编号,注意一旦commandname设置为delete这个名称后,gridview中的GridView_RowCommand 和 GridView_Row_Deleting 事件都会被激发接者,我们处理其rowdatabound事件中:
  在上面的代码中,我们设置了一个链接linkbutton,其中指定了commandname为"Delete",commandargument为要删除的记录的ID编号,注意一旦commandname设置为delete这个名称后,gridview中的GridView_RowCommand 和 GridView_Row_Deleting 事件都会被激发接者,我们处理其rowdatabound事件中:

 protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)


 {
{
 if (e.Row.RowType == DataControlRowType.DataRow)
 if (e.Row.RowType == DataControlRowType.DataRow)

 
  {
{
 LinkButton l = (LinkButton)e.Row.FindControl("LinkButton1");
  LinkButton l = (LinkButton)e.Row.FindControl("LinkButton1"); 
 l.Attributes.Add('onclick", "javascript:return " + "confirm("是否要删除该记录? " +
  l.Attributes.Add('onclick", "javascript:return " + "confirm("是否要删除该记录? " +
 DataBinder.Eval(e.Row.DataItem, "id") + "')");
  DataBinder.Eval(e.Row.DataItem, "id") + "')"); 
 }
 }
 }
} 

 在这段代码中,首先检查是否是datarow,是的话则得到每个linkbutton,再为其添加客户端代码,基本和asp.net 1.1的做法差不多。
  在这段代码中,首先检查是否是datarow,是的话则得到每个linkbutton,再为其添加客户端代码,基本和asp.net 1.1的做法差不多。

 之后,当用户选择了确认删除后,我们有两种方法对其进行继续的后续删除处理,因为我们将删除按钮设置为Delete,方法一是在row_command事件中写入如下代码:
  之后,当用户选择了确认删除后,我们有两种方法对其进行继续的后续删除处理,因为我们将删除按钮设置为Delete,方法一是在row_command事件中写入如下代码:

 protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)


 {
{
 if (e.CommandName == "Delete")
 if (e.CommandName == "Delete")

 
  {
{
 int id = Convert.ToInt32(e.CommandArgument);
  int id = Convert.ToInt32(e.CommandArgument);
 // 删除记录的专门过程
  // 删除记录的专门过程
 DeleteRecordByID(id);
  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">
  另外一种方法是使用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事件:
然后添加row_deleting事件:

 protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)


 {
{
 int categoryID = (int) GridView1.DataKeys[e.RowIndex].Value;
 int categoryID = (int) GridView1.DataKeys[e.RowIndex].Value;
 DeleteRecordByID(categoryID);
 DeleteRecordByID(categoryID); 
 }
} 

 要注意的是,这个必须将datakeynames设置为要删除记录的编号,这里是categoryid.
  要注意的是,这个必须将datakeynames设置为要删除记录的编号,这里是categoryid.

 小结
  小结

 在本文中,继续探讨了gridview控件的一些用法,如导出到excel,在删除记录时的处理,以及如何访问gridview中的控件等。
  在本文中,继续探讨了gridview控件的一些用法,如导出到excel,在删除记录时的处理,以及如何访问gridview中的控件等。


 
        posted on 
2007-02-04 09:32 
ipusr 
阅读(
216) 
评论() 
 
收藏 
举报