目前分類:C# (67)

瀏覽方式: 標題列表 簡短摘要
  • Jan 08 Tue 2008 17:31
  • DOM

It is an abbreviation for the Document Object Model for HTML

羅 朝淇 發表在 痞客邦 PIXNET 留言(0) 人氣()

Introduction:

The article "ASP.Net 2.0: Export GridView to Excel" received a very good response from our user community. Some of the excellent tips collected from the user feedback have been included in the first version of the article. 

One of the most common questions from our readers is regarding the handling of a Hyperlink column in the GridView Export to Excel. This article will expand on the original article and in this version, we will include the handling the export of the Hyperlink columns in the GridView export to Excel functionality and also re-factor our original logic to use more general features of reflection, allowing for easy extension to include additional control types. This code generalization does have a performance overhead and if the controls embedded in your GridView are limited to a particular set, the original implementation may be more suitable for your requirements.

Architectural Changes:

  1. Define a Hash Table which holds the values for the controls to be replaced before the GridView control is exported to Excel.
    This HashTable will map the control types that can be potentially embedded in the GridView to the corresponding control property that will be used to represent the particular control when exported to Excel.
  2. The generalized "GetControlPropertyValue" method: In this version, we define a generalized method which will fetch the value of "key" property of the embedded control by using Reflection. We define the key properties for different types of embedded control using our HashTable member variable.

羅 朝淇 發表在 痞客邦 PIXNET 留言(0) 人氣()

Introduction:

In this article, we will see how to Export an ASP.Net 2.0 GridView to Excel. 

The focus of the article is the Export to Excel functionality - the Gridview and it's data binding are only for demonstrating the Export functionality.

The code fragments for the Export to Excel functionality below are not linked to the backend structure and can be re-used across projects for the common functionality provided.

Step 1: Setup your web page with the Gridview

In this article, we will assume you are starting with a web page which holds a GridView named GridView1. The GridView in our demo code is bound to a table named "ContactPhone" in a SQL Express database. The following code which exports the databound GridView to Excel is not dependent on the specific databindings and can be used without changes for your scenario.

ContactPhone Table Structure:

Column Name

Type

ContactID

Int (Identity)

FName

Varchar(50)

LName

Varchar(50)

ContactPhone

Varchar(20)

Step: The Actual Export

The code to do the Excel Export is very straightforward. You can also export to different application type by changing the content-disposition and ContentType. 

string attachment = "attachment; filename=Contacts.xls";

Response.ClearContent();

Response.AddHeader("content-disposition", attachment);

Response.ContentType = "application/ms-excel";

StringWriter sw = new StringWriter();

HtmlTextWriter htw = new HtmlTextWriter(sw);

GridView1.RenderControl(htw);

Response.Write(sw.ToString());

Response.End();

If you run the code as above, it will result in an HttpException as follows:

Control 'GridView1' of type 'GridView' must be placed inside a form tag with runat=server."

To avoid this error, add the following code:  

public override void VerifyRenderingInServerForm(Control control)

{

}

Step : Convert the contents

If the GridView contains any controls, such as Checkboxes, Dropdownlists, we need to replace the contents with their relevant values. The following recursive function uses Reflection to determine the type of control. The control is deleted in preparation for the Excel export and the relevant value of the control is added.

private void PrepareGridViewForExport(Control gv)

{

LinkButton lb = new LinkButton();

Literal l = new Literal();

string name = String.Empty;

for (int i = 0; i < gv.Controls.Count; i++)

{

if (gv.Controls[i].GetType() == typeof(LinkButton))

{

l.Text = (gv.Controls[i] as LinkButton).Text;

gv.Controls.Remove(gv.Controls[i]);

gv.Controls.AddAt(i, l);

}

else if (gv.Controls[i].GetType() == typeof(DropDownList))

{

l.Text = (gv.Controls[i] as DropDownList).SelectedItem.Text;

gv.Controls.Remove(gv.Controls[i]);

gv.Controls.AddAt(i, l);

}

else if (gv.Controls[i].GetType() == typeof(CheckBox))

{

l.Text = (gv.Controls[i] as CheckBox).Checked? "True" : "False";

gv.Controls.Remove(gv.Controls[i]);

gv.Controls.AddAt(i, l);

}

if (gv.Controls[i].HasControls())

{

PrepareGridViewForExport(gv.Controls[i]);

}

}

Code Listing:

Image: Page Design

Image : Sample in action

Image: Export to Excel button is clicked

Image: GridView contents exported to Excel

ExcelExport.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="ExportExcel.aspx.cs" Inherits="DeleteConfirm" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >

<head runat="server">

<title>Contacts Listing</title>

</head>

<body>

<form id="form1" runat="server">

<div>

<strong><span style="font-size: small; font-family: Arial; text-decoration: underline">

Contacts Listing

<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Export To Excel" /></span></strong><br />

<br />

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="ContactID"

DataSourceID="SqlDataSource1" EmptyDataText="There are no data records to display." style="font-size: small; font-family: Arial" BackColor="White" BorderColor="#DEDFDE" BorderStyle="None" BorderWidth="1px" CellPadding="4" ForeColor="Black" GridLines="Vertical">

<Columns>

<asp:BoundField DataField="ContactID" HeaderText="ContactID" ReadOnly="True" SortExpression="ContactID" Visible="False" />

<asp:BoundField DataField="FName" HeaderText="First Name" SortExpression="FName" />

<asp:BoundField DataField="LName" HeaderText="Last Name" SortExpression="LName" />

<asp:BoundField DataField="ContactPhone" HeaderText="Phone" SortExpression="ContactPhone" />

<asp:TemplateField HeaderText="Favorites">

<ItemTemplate>

&nbsp;

<asp:CheckBox ID="CheckBox1" runat="server" />

</ItemTemplate></asp:TemplateField>

</Columns>

<FooterStyle BackColor="#CCCC99" />

<RowStyle BackColor="#F7F7DE" />

<SelectedRowStyle BackColor="#CE5D5A" Font-Bold="True" ForeColor="White" />

<PagerStyle BackColor="#F7F7DE" ForeColor="Black" HorizontalAlign="Right" />

<HeaderStyle BackColor="#6B696B" Font-Bold="True" ForeColor="White" />

<AlternatingRowStyle BackColor="White" />

</asp:GridView>

<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:ContactsConnectionString1 %>"

DeleteCommand="DELETE FROM [ContactPhone] WHERE [ContactID] = @ContactID" InsertCommand="INSERT INTO [ContactPhone] ([FName], [LName], [ContactPhone]) VALUES (@FName, @LName, @ContactPhone)"

ProviderName="<%$ ConnectionStrings:ContactsConnectionString1.ProviderName %>"

SelectCommand="SELECT [ContactID], [FName], [LName], [ContactPhone] FROM [ContactPhone]"

UpdateCommand="UPDATE [ContactPhone] SET [FName] = @FName, [LName] = @LName, [ContactPhone] = @ContactPhone WHERE [ContactID] = @ContactID">

<InsertParameters>

<asp:Parameter Name="FName" Type="String" />

<asp:Parameter Name="LName" Type="String" />

<asp:Parameter Name="ContactPhone" Type="String" />

</InsertParameters>

<UpdateParameters>

<asp:Parameter Name="FName" Type="String" />

<asp:Parameter Name="LName" Type="String" />

<asp:Parameter Name="ContactPhone" Type="String" />

<asp:Parameter Name="ContactID" Type="Int32" />

</UpdateParameters>

<DeleteParameters>

<asp:Parameter Name="ContactID" Type="Int32" />

</DeleteParameters>

</asp:SqlDataSource>

&nbsp;

<br />

</div>

</form>

</body>

</html>

ExcelExport.aspx.cs 

using System;

using System.Data;

using System.Configuration;

using System.Collections;

using System.Web;

using System.Web.Security;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Web.UI.WebControls.WebParts;

using System.Web.UI.HtmlControls;

using System.Text;

using System.IO;

public partial class DeleteConfirm : System.Web.UI.Page

{

protected void Page_Load(object sender, EventArgs e)

{

}

protected void Button1_Click(object sender, EventArgs e)

{

//Export the GridView to Excel

PrepareGridViewForExport(GridView1);

ExportGridView();

}

private void ExportGridView()

{

string attachment = "attachment; filename=Contacts.xls";

Response.ClearContent();

Response.AddHeader("content-disposition", attachment);

Response.ContentType = "application/ms-excel";

StringWriter sw = new StringWriter();

HtmlTextWriter htw = new HtmlTextWriter(sw);

GridView1.RenderControl(htw);

Response.Write(sw.ToString());

Response.End();

}

public override void VerifyRenderingInServerForm(Control control)

{

}

private void PrepareGridViewForExport(Control gv)

{

LinkButton lb = new LinkButton();

Literal l = new Literal();

string name = String.Empty;

for (int i = 0; i < gv.Controls.Count; i++)

{

if (gv.Controls[i].GetType() == typeof(LinkButton))

{

l.Text = (gv.Controls[i] as LinkButton).Text;

gv.Controls.Remove(gv.Controls[i]);

gv.Controls.AddAt(i, l);

}

else if (gv.Controls[i].GetType() == typeof(DropDownList))

{

l.Text = (gv.Controls[i] as DropDownList).SelectedItem.Text;

gv.Controls.Remove(gv.Controls[i]);

gv.Controls.AddAt(i, l);

}

else if (gv.Controls[i].GetType() == typeof(CheckBox))

{

l.Text = (gv.Controls[i] as CheckBox).Checked ? "True" : "False";

gv.Controls.Remove(gv.Controls[i]);

gv.Controls.AddAt(i, l);

}

if (gv.Controls[i].HasControls())

{

PrepareGridViewForExport(gv.Controls[i]);

}

}

}

}

Implementation Options:

In quite a few cases, developers face an error in the Export functionality - typically the error message is "RegisterForEventValidation can only be called during Render();".

Our website readers have contributed some good suggestions in the article comments below. I would particularly like to highlight the suggestion by Marianna, who provides an alternative implementation to the VerifyRenderingInServerForm override. This approach is described below: 

  • Step 1: Implement the Export functionality as described above.
  • Step 2: Remove the code to override the VerifyRenderingInServerForm method.
  • Step 3: Modify the code for the ExportGridView function as below. The code highlighted in green creates and HtmlForm on the fly, before exporting the gridview, adds the gridview to this new form and renders the form (instead of rendering the gridview in our original implementation)

private void ExportGridView()

{

string attachment = "attachment; filename=Contacts.xls";

Response.ClearContent();

Response.AddHeader("content-disposition", attachment);

Response.ContentType = "application/ms-excel";

StringWriter sw = new StringWriter();

HtmlTextWriter htw = new HtmlTextWriter(sw);

// Create a form to contain the grid

HtmlForm frm = new HtmlForm();

GridView1.Parent.Controls.Add(frm);

frm.Attributes["runat"] = "server";

frm.Controls.Add(GridView1);

frm.RenderControl(htw);

//GridView1.RenderControl(htw);

Response.Write(sw.ToString());

Response.End();

}

This implementation has the advantage that it can be setup as re-usable code in a separate library, without having to override the base class method each time.

Note to readers:

Thank you for your comments and feedback! Happy coding!!!

ASP.Net 2.0: Export GridView to Excel - Part II

This version of the article includes handling of the Hyperlink columns in the GridView export to Excel and also re-factors our original logic to use more general features of Reflection 

Conclusion:

In this article, we saw how to Export an ASP.Net 2.0 GridView to Excel. The code fragments are not linked to the backend structure and can be re-used across projects for the common functionality provided.

The focus of the article is the Export to Excel functionality - the Gridview and it's data binding are only for demonstrating the following functionality. 

For reference on Exporting ASP.Net 1.1 DataGrid to Excel: Export ASP.NET DataGrid to Excel

Disclaimer: This article is for purely educational purposes and is a compilation of notes, material and my understanding on this subject. Any resemblance to other material is an un-intentional coincidence and should not be misconstrued as malicious, slanderous, or any anything else hereof.

羅 朝淇 發表在 痞客邦 PIXNET 留言(0) 人氣()

<head runat="server">
    <title>未命名頁面</title>

羅 朝淇 發表在 痞客邦 PIXNET 留言(0) 人氣()

form1.DefaultButton = "btn_submit";
form1.DefaultFocus = "txt_what";

放在Page_load就可以了。預設按鈕一定要是Button不然就錯了

羅 朝淇 發表在 痞客邦 PIXNET 留言(0) 人氣()

    protected void Page_Load(object sender, EventArgs e)
    {

羅 朝淇 發表在 痞客邦 PIXNET 留言(0) 人氣()

//建立連線
SqlConnection conn;

羅 朝淇 發表在 痞客邦 PIXNET 留言(0) 人氣()

DropDownList.Items.Add("ABC");

羅 朝淇 發表在 痞客邦 PIXNET 留言(0) 人氣()

string[ ] which = new string[3] { "員工名稱", "員工代號","部門代號"};
for (int i = 0; i <= which.GetUpperBound(0) ; i++)

羅 朝淇 發表在 痞客邦 PIXNET 留言(0) 人氣()

DropDownList 控制項會在使用者選取項目時,引發 SelectedIndexChanged 事件。根據預設,這個事件不會造成網頁張貼至伺服器,但您可以將 AutoPostBack 屬性設定為 true(這是重點),讓控制項強制執行立即張貼。

羅 朝淇 發表在 痞客邦 PIXNET 留言(0) 人氣()

一種「方法的指標」,利用委派可以間接叫用方法。主要應用在「事件的驅動」
如何使用:

羅 朝淇 發表在 痞客邦 PIXNET 留言(0) 人氣()

我想在文字方塊上預設文字「請輸入你的帳號」,然後等使用者將滑鼠或游標點入文字方塊時,文字方塊內的文字就會清除為空白,可以讓使用者輸入資料。因為我發現TextBox的事件只有TextChanged(),沒有Focus等事件,這樣要怎麼寫呢。
我使用C#,謝謝。

方法一:

羅 朝淇 發表在 痞客邦 PIXNET 留言(0) 人氣()

有兩種方式:
1.子類別透過new來取代父類別的成員

羅 朝淇 發表在 痞客邦 PIXNET 留言(0) 人氣()

在宣告該命名空間的所屬專案內,皆能叫用該命名空間
只要透過using 關鍵字即可匯入命名空間,當然事先必須加入該命名空間所屬的參考

羅 朝淇 發表在 痞客邦 PIXNET 留言(0) 人氣()

宣告類別
public class car

羅 朝淇 發表在 痞客邦 PIXNET 留言(0) 人氣()

類別和物件(Class and Object):類別是用來描述某物件的結構,而物件是把變數(Variable)、屬性(Property)和方法(Method)包在一起的一種軟體技術,為某類別的「執行個體」。我們將Class視為車體設計圖,那麼Object就是依據車體設計圖所打造出的汽車。
class familyA  //類別

羅 朝淇 發表在 痞客邦 PIXNET 留言(0) 人氣()

建構函式就是類別的「方法」,主要對物件進行初始化設定,當對類別進行「實體化(new)」成為物件時,便會自動執行建構函式。
1.建構函式名稱與類別名稱相同

羅 朝淇 發表在 痞客邦 PIXNET 留言(0) 人氣()

傳值呼叫:
private void button1_Click(object sender, EventArgs e)

羅 朝淇 發表在 痞客邦 PIXNET 留言(0) 人氣()

public class father
{ }

羅 朝淇 發表在 痞客邦 PIXNET 留言(0) 人氣()

private:同一類別
internal:同一組件(dll)

羅 朝淇 發表在 痞客邦 PIXNET 留言(0) 人氣()

1 234