Subscribe

RSS Feed (xml)

Powered By

Skin Design:
Free Blogger Skins

Powered by Blogger

Thursday, October 2, 2008

Extend BoundField Of GridView



.
In this post i will show you how to extend BoundField Column of Gridview to add MultiLine support
Step 1.Place the code in app_code directory


using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace CustomBoundField
{
public class BoundTextBoxField : System.Web.UI.WebControls.BoundField
{

public TextBoxMode TextMode
{
get
{
TextBoxMode _tm = TextBoxMode.SingleLine;
if (this.ViewState["TextMode"] != null)
_tm = (TextBoxMode)this.ViewState["TextMode"];
return _tm;
}
set { this.ViewState["TextMode"] = value; }
}

public int Columns
{
get
{
int i = 0;
if (this.ViewState["Columns"] != null)
i = (int)this.ViewState["Columns"];
return i;
}
set { this.ViewState["Columns"] = value; }
}

public int Rows
{
get
{
int i = 0;
if (this.ViewState["Rows"] != null)
i = (int)this.ViewState["Rows"];
return i;
}
set { this.ViewState["Rows"] = value; }
}

public bool Wrap
{
get
{
bool b = true;
if (this.ViewState["Wrap"] != null)
b = (bool)this.ViewState["Wrap"];
return b;
}
set { this.ViewState["Wrap"] = value; }
}

protected override void OnDataBindField(object sender, EventArgs e)
{
base.OnDataBindField(sender, e);
Control c = (Control)sender;
if (c is TextBox)
{
TextBox txt = (TextBox)c;
txt.TextMode = this.TextMode;
txt.Columns = this.Columns;
txt.Rows = this.Rows;
txt.Wrap = this.Wrap;
}
}

}

}

Step2. Register the Control in asp page

Default.aspx


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

<%@ Register Namespace="CustomBoundField" TagPrefix="custom"%>

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>Untitled Pagetitle>
head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView AutoGenerateColumns="false" ID="GridView1" runat="server" AutoGenerateEditButton="True" OnRowEditing="GridView1_RowEditing">
<Columns>
<asp:BoundField DataField="Id" HeaderText="Single Line" />
<custom:boundtextboxfield datafield="Name" headertext="MultiLine Text" sortexpression="Text"
textmode="MultiLine" rows="5" columns="25" wrap="True" />
Columns>
asp:GridView>
div>
form>
body>
html>
Default.aspx.cs


using System;
using System.Data;
using System.Configuration;
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;

public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindGrid();
}

}
private void BindGrid()
{
GridView1.DataSource = GetDataSource();
GridView1.DataBind();
}
protected DataTable GetDataSource()
{

const string key = "MyDataSource";
DataTable dt = Session[key] as DataTable;

if (dt == null)
{

dt = new DataTable();
dt.Columns.Add("ID", typeof(int));

dt.Columns.Add("Name", typeof(string));
dt.Rows.Add("1", "first object");

dt.Rows.Add("2", "second object");
dt.Rows.Add("3", "second object");
dt.Rows.Add("4", "second object");
Session[key] = dt;

}

return dt;
}
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
BindGrid();

}

}

How To Add Tooltip in GridView





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


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 id="Head1" runat="server">
<title>Untitled Pagetitle>

<script language="JavaScript">



script>

head>
<body onload='reg();'>
<form id="form1" runat="server">
<div id="linkex" style="position: absolute; visibility: hidden; width: 80%">
div>
<layer name="linkex" visibility="hide" width="80%:">
layer>
<div>
<asp:GridView ID="GridView1" runat="server" OnRowDataBound="GridView1_RowDataBound">
asp:GridView>
div>
form>
body>
html>


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;

public partial class tooltip : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
bind();
}

private void bind()
{
DataTable table = new DataTable();
table.Columns.Add("booktitle");
table.Columns.Add("tooltip");


DataRow dr = table.NewRow();
dr["booktitle"] = "aaaaa";
dr["tooltip"] = "cart_icon.jpg";
table.Rows.Add(dr);
DataRow dr1 = table.NewRow();
dr1["booktitle"] = "ddd";
dr1["tooltip"] = "cart_icon2.jpg";
table.Rows.Add(dr1);
this.GridView1.DataSource = table;
GridView1.DataBind();
}

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
DataRowView drv = ((DataRowView)e.Row.DataItem);
string path = drv["tooltip"].ToString();
e.Row.Attributes.Add("onmouseover", "don(this,'" + path + "')");
e.Row.Attributes.Add("onmouseout", "doff()");
}
}
}

Building a Simple CSV Parser in C#





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.IO;
using System.Collections.Generic;

public partial class ParseCSV : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
List<string[]> testParse =
parseCSV("C:\\TestParse.csv");
DataTable newTable = new DataTable();
foreach (string column in testParse[0])
{
newTable.Columns.Add();
}

foreach (string[] row in testParse)
{
newTable.Rows.Add(row);
}
GridView1.DataSource = newTable;
GridView1.DataBind();
}
public List<string[]> parseCSV(string path)
{
List<string[]> parsedData = new List<string[]>();

using (StreamReader readFile = new StreamReader(path))
{
string line;
string[] row;

while ((line = readFile.ReadLine()) != null)
{
row = line.Split(',');
parsedData.Add(row);
}
}

return parsedData;
}
}


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

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>Untitled Pagetitle>
head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="GridView1" runat="server">
asp:GridView>

div>
form>
body>
html>

C# Tutorial - Extension Methods


take a look extension methods, which is a language feature introduced to C# in .NET 3.0. Extension methods are a piece of syntactic sugar that allow you add new functionality to a class that you don't have direct access to. Sound cool yeah? Cause it is.

C# Tutorial - The Readonly Keyword


C# has a ton of keywords, and it is sometimes hard to keep track of them all. One keyword that often gets lost in the shuffle is the readonly keyword, often because many people just group it with the const keyword and leave it at that. Well, the readonly keyword deserves better than that - and so here today we are going to talk about what exactly it does, how it differs from const, and why you would ever want to use it at all.The readonly keyword does ............................
check out this link

How To - Prevent Script Attacks


This post describes the request validation feature of ASP.NET where, by default, the application is prevented from processing unencoded HTML content submitted to the server. This request validation feature can be disabled when the application has been designed to safely process HTML data.

Applies to ASP.NET 1.1 and ASP.NET 2.0.

Check out this article

How To: Prevent Cross-Site Scripting in ASP.NET


This How To shows how you can help protect your ASP.NET applications from cross-site scripting attacks by using proper input validation techniques and by encoding the output. It also describes a number of other protection mechanisms that you can use in addition to these two main countermeasures.

Cross-site scripting (XSS) attacks exploit vulnerabilities in Web page validation by injecting client-side script code. Common vulnerabilities that make your Web applications susceptible to cross-site scripting attacks include failing to properly validate input, failing to encode output, and trusting the data retrieved from a shared database. To protect your application against cross-site scripting attacks, assume that all input is malicious. Constrain and validate all input. Encode all output that could, potentially, include HTML characters. This includes data read from files and databases.

check out this link


How To Add Title Attribute To GridView Row



Let us suppose that you have a :Grid View with about seven rows across.One of the cells is a five-digit code, for a long name.and your requirement is that the user move the mouse over the code cell, and display this long name in a small popup window, to remind the user of which the code describes.Here is a simple solution without using JavaScript. Just add "Title" attribute to each row to display the information. It will have the same effect as mouse over and mouse out




<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Mouseover.aspx.cs"

Inherits="Mouseover" %>




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

head>

<body>

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

<div>

<asp:GridView ID="GridView1" AutoGenerateColumns="False" runat="server" OnRowDataBound="GridView1_RowDataBound">

<Columns>

<asp:BoundField DataField="id" HeaderText="ProductId" />

<asp:BoundField DataField="Name" HeaderText="Name" />

<asp:BoundField DataField="sellPrice" HeaderText="SalePrice" />

<asp:TemplateField HeaderText="LongName">

<ItemTemplate>

<asp:Label ID="LongName" runat="server" Text='<%#ShortDesc(Eval("Desc").ToString()) %>'>asp:Label>

ItemTemplate>

asp:TemplateField>

<asp:TemplateField HeaderText="LongAgencyName" Visible="False">

<ItemTemplate>

<asp:Label ID="LongName1" runat="server" Text='<%#Eval("Desc")%>'>asp:Label>

ItemTemplate>

asp:TemplateField>

Columns>

asp:GridView>

div>

form>

body>

html>



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;



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

{

protected void Page_Load(object sender, EventArgs e)

{

if (!IsPostBack)

{

GridView1.DataSource = GetData();

GridView1.DataBind();



}

}

public DataSet GetData()

{

DataSet ds = new DataSet();

DataTable dt = new DataTable("Movie");

DataRow dr;

dt.Columns.Add(new DataColumn("Id", typeof(Int32)));

dt.Columns.Add(new DataColumn("Name", typeof(string)));

dt.Columns.Add(new DataColumn("SellPrice", typeof(Int32)));

dt.Columns.Add(new DataColumn("Desc", typeof(string)));

for (int i = 1; i <= 10; i++)

{

dr = dt.NewRow();

dr[0] = i;

dr[1] = "Name" + i.ToString();

dr[2] = (i * 3)+i*i;

dr[3] = "Abcdefghijklmnopqwrstuvwxyz"+i.ToString();

dt.Rows.Add(dr);

}

ds.Tables.Add(dt);

Session["dt"] = dt;

return ds;

}

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)

{

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

{

Label lbl = (Label)e.Row.FindControl("LongName1");

e.Row.Attributes.Add("Title", lbl.Text);

e.Row.Attributes["style"] = "Cursor:hand";

}



}

public string ShortDesc(string strDesc)

{



return strDesc.Substring(0, 5);



}

}

Wednesday, October 1, 2008

Hidden Field Inside GridView


If you add Visible="False" to any control Such control is not rendered on the client side at all. It is accessible on server side only. If you want to get it invisible, but present in DOM and accessible using JavaScript change
Visible="False" to style="display:none"

How To Display data in marquee from database by using asp.net c#




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

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>Untitled Pagetitle>
head>
<body>
<form id="form1" runat="server">
<div>
<marquee id="ml" style="text-align: center" direction="up" width="195" height="170"
scrolldelay="20" scrollamount="1">
<asp:Repeater ID="Repeater1" runat="server">
<ItemTemplate>
<br />
<asp:HyperLink ID="HyperLink1" runat="server" NavigateUrl='<%# Eval("URL") %>'>
<asp:Label ID="Label1" runat="server" Text='<%# Eval("Desc") %>'>asp:Label>asp:HyperLink><br />
ItemTemplate>
asp:Repeater>
marquee>
div>
form>
body>
html>


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;

public partial class Marquee : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Repeater1.DataSource = GetData();
Repeater1.DataBind();
}

}
public DataSet GetData()
{
DataSet ds = new DataSet();
DataTable dt = new DataTable("News");
DataRow dr;
dt.Columns.Add(new DataColumn("Id", typeof(Int32)));
dt.Columns.Add(new DataColumn("Url", typeof(string)));

dt.Columns.Add(new DataColumn("Desc", typeof(string)));
for (int i = 1; i <= 10; i++)
{
dr = dt.NewRow();
dr[0] = i;
dr[1] = "URL" + i.ToString();

dr[2] = "Description " + i.ToString();
dt.Rows.Add(dr);
}
ds.Tables.Add(dt);
Session["dt"] = dt;
return ds;
}
}

FileUpload and Ajax UpdatePanel


All file upload controls (includes asp, telerik, componentart, component factory and others) does not working in any ajax update panel and upload control needs to full page postback. This means if your upload control located in an update panel, control does not post the file. If you look to the posted file property of the control, you will see it null. So, the control always have to post full page postback.

This is a limitation comes from the XmlHttpRequest component, used in all AJAX frameworks for asynchronous calls to the application. In order to upload a file you should perform a full page postback.

If you have automatically AJAX-enabled button or other control, which normally does postbacks, placed in UpdatePanel you could use one of following workarounds to make the button to perform postbacks again.

1 - You need to create a PostBackTrigger for the button which should initiate postback.



<asp:updatepanel runat="server" id="UpdatePanel1">
<contenttemplate>
<asp:FileUpload runat="server" id="Upload1" />
<asp:button runat="server" id="ButtonSubmit" text="Postback" />
contenttemplate>
<triggers>
<asp:postbacktrigger controlid="ButtonSubmit" />
triggers>
asp:updatepanel>

2 - You can register the page and control to do full page postback. To do this, you can use the script manager. (suggested by EtienneT)


ScriptManager.GetCurrent(Page).RegisterPostBackControl(Upload1);

3 - You can use the "iframe" html object to call upload webpage in frame. But this as you know iframe is not a XHTML object. But this can be smooth fix for you. (suggested by Justin Bozoiner)

Binding Data to a Web Forms DataList





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


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>Untitled Pagetitle>
head>
<body>
<form id="form1" runat="server">
<div>
<asp:DataList ID="dataList" Style="z-index: 102; left: 16px; position: absolute;
top: 56px"
runat="server" OnCancelCommand="dataList_CancelCommand" OnDeleteCommand="dataList_DeleteCommand"
OnEditCommand="dataList_EditCommand" OnItemCommand="dataList_ItemCommand" OnUpdateCommand="dataList_UpdateCommand">
<SelectedItemTemplate>
<asp:Button ID="editButton" runat="server" Text="Edit" CommandName="Edit">asp:Button>
<b>
<%# DataBinder.Eval(Container.DataItem, "Id") %>
;
<%# DataBinder.Eval(Container.DataItem, "IntField") %>
;
<%# DataBinder.Eval(Container.DataItem, "StringField") %>
b>
SelectedItemTemplate>
<ItemTemplate>
<asp:Button ID="selectButton" runat="server" Text="Select" CommandName="Select">asp:Button>
<%# DataBinder.Eval(Container.DataItem, "Id") %>
;
<%# DataBinder.Eval(Container.DataItem, "IntField") %>
;
<%# DataBinder.Eval(Container.DataItem, "StringField") %>
ItemTemplate>
<EditItemTemplate>
<asp:Button ID="updateButton" runat="server" Text="Update" CommandName="Update">asp:Button>
<asp:Button ID="deleteButton" runat="server" Text="Delete" CommandName="Delete">asp:Button>
<asp:Button ID="cancelButton" runat="server" Text="Cancel" CommandName="Cancel">asp:Button>
<br>
<asp:Label ID="Label1" runat="server">ID: asp:Label>
<asp:TextBox ID="idTextBox" runat="server" Width="96px" ReadOnly="True" Text='<%# DataBinder.Eval(Container.DataItem, "Id") %>'>
asp:TextBox>
<br>
<asp:Label ID="Label2" runat="server">IntField: asp:Label>
<asp:TextBox ID="intFieldTextBox" runat="server" Text='<%# DataBinder.Eval(Container.DataItem,
"IntField") %>'
>
asp:TextBox>
<br>
<asp:Label ID="Label3" runat="server">StringField: asp:Label>
<asp:TextBox ID="stringFieldTextBox" runat="server" Text='<%# DataBinder.Eval(Container.DataItem,
"StringField") %>'
>
asp:TextBox>
EditItemTemplate>
asp:DataList>
div>
form>
body>
html>


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;
public partial class DataListTest : System.Web.UI.Page
{


protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
BindList();

}

}

private void BindList()
{
if (Session["DataSource"] == null)
{
dataList.DataSource = GetDataSet();
dataList.DataKeyField = "Id";
}
else
{
dataList.DataSource = (DataTable)Session["DataSource"];
dataList.DataKeyField = "Id";
}
dataList.DataBind();
}
public DataTable GetDataSet()
{

DataTable dt = new DataTable("Company");
DataRow dr;
dt.Columns.Add(new DataColumn("Id", typeof(Int32)));
dt.Columns.Add(new DataColumn("IntField", typeof(Int32)));
dt.Columns.Add(new DataColumn("StringField", typeof(string)));
for (int i = 0; i <= 10; i++)
{
dr = dt.NewRow();
dr[0] = i;
dr[1] = i;
dr[2] = "Company" + i + Environment.NewLine + "Title" + i;
dt.Rows.Add(dr);
DataColumn[] Parent_PKColumns = new DataColumn[1];
Parent_PKColumns[0] = dt.Columns["ID"];
dt.PrimaryKey = Parent_PKColumns;
Session["DataSource"] = dt;
}

return dt;
}

protected void dataList_CancelCommand(object source, DataListCommandEventArgs e)
{
// Set the index of the item being edited out of range.
dataList.EditItemIndex = -1;

BindList();

}
protected void dataList_EditCommand(object source, DataListCommandEventArgs e)
{
// Set the index of the selected item out of range.
dataList.SelectedIndex = -1;
// Set the index of the item being edited to the current record.
dataList.EditItemIndex = e.Item.ItemIndex;
BindList();
}
protected void dataList_DeleteCommand(object source, DataListCommandEventArgs e)
{
// Get the data from the session variable.
DataTable dt = (DataTable)Session["DataSource"];

// Get the ID of the row to delete.
int id = (int)dataList.DataKeys[e.Item.ItemIndex];

// Delete the row from the table.
dt.Rows.Find(id).Delete();

// Update the data source with the changes to the table.
UpdateDataSource(dt);

// Set the index of the item being edited out of range.
dataList.EditItemIndex = -1;




BindList();

}

public void UpdateDataSource(DataTable dt)
{

dt.AcceptChanges();
Session["ds"] = dt;
}
protected void dataList_ItemCommand(object source, DataListCommandEventArgs e)
{
// Check if the "select" button is pressed.
if (e.CommandName == "Select")
{
// Set the index of the item being edited out of range.
dataList.EditItemIndex = -1;
// Set the index of the selected item to the current record.
dataList.SelectedIndex = e.Item.ItemIndex;

BindList();
}
}
protected void dataList_UpdateCommand(object source, DataListCommandEventArgs e)
{
// Get the data from the session variable.
DataTable dt = (DataTable)Session["DataSource"];

// Get the ID of the row to update.
int id = (int)dataList.DataKeys[e.Item.ItemIndex];

// Get the DataRow to update using the ID.
DataRow dr = dt.Rows.Find(id);

// Get the column values for the current record from the DataList.
dr["IntField"] =
Int32.Parse(((TextBox)e.Item.FindControl("intFieldTextBox")).Text);
dr["StringField"] =
((TextBox)e.Item.FindControl("stringFieldTextBox")).Text;

// Update the data source with the changes to the table.
UpdateDataSource(dt);

// Set the index of the item being edited out of range.
dataList.EditItemIndex = -1;

BindList();

}
}

How To Open div popup with a LightBox effect





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


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>Untitled Pagetitle>
<script type="text/javascript">

function showBox()
{
var width = document.documentElement.clientWidth + document.documentElement.scrollLeft;

var layer = document.createElement('div');
layer.style.zIndex = 2;
layer.id = 'layer';
layer.style.position = 'absolute';
layer.style.top = '0px';
layer.style.left = '0px';
layer.style.height = document.documentElement.scrollHeight + 'px';
layer.style.width = width + 'px';
layer.style.backgroundColor = 'black';
layer.style.opacity = '.6';
layer.style.filter += ("progid:DXImageTransform.Microsoft.Alpha(opacity=60)");
document.body.appendChild(layer);

var div = document.createElement('div');
div.style.zIndex = 3;
div.id = 'box';
div.style.position = (navigator.userAgent.indexOf('MSIE 6') > -1) ? 'absolute' : 'fixed';
div.style.top = '200px';
div.style.left = (width / 2) - (400 / 2) + 'px';
div.style.height = '50px';
div.style.width = '400px';
div.style.backgroundColor = 'white';
div.style.border = '2px solid silver';
div.style.padding = '20px';
document.body.appendChild(div);

var p = document.createElement('p');
p.innerHTML = 'Some text';
div.appendChild(p);

var a = document.createElement('a');
a.innerHTML = 'Close window';
a.href = 'javascript:void(0)';
a.onclick = function()
{
document.body.removeChild(document.getElementById('layer'));
document.body.removeChild(document.getElementById('box'));
};

div.appendChild(a);
}
script>
head>
<body style="height:2000px">
<form id="form1" runat="server">
<div>


<a href="javascript:void(showBox())">Toggle boxa>


div>
form>
body>
html>

Asynchronous GridView in 5 simple steps


A web page with a data bound GridView control can take a long time to load. The page is not rendered until all the controls are, and the GridView cannot render before data has been retrieved from the database. So, let’s load the GridView asynchronous and make the page load faster and the perceived speed greater.

This little trick is actually very simple and it involves the built-in client callback feature of ASP.NET. Even though I’m not a big fan of that particular feature, it can be quite handy from time to time. The best part of this is that you don’t have to change much to your existing code.

Web page

On the webpage that hosts the GridView control, you have to make 2 small changes.

Step 1. Encapsulate the GridView
The GridView control has to be encapsulated by an HTML control with an id attribute, so that it can be referenced by JavaScript. That is because the GridView does not render when no data is bound to it.

"grid">
Loading...
"Server" ID="gvAsync" />

Step 2. Add a JavaScript
Then a JavaScript is needed to load the rendered and data bound GridView to the HTML control we added in step 1. Place the JavaScript below the GridView’s surrounding div tag.



Code-behind

In the code-behind file there are three small steps to perform.

Step 3. Implement ICallbackEventHandler
We need to implement the interface to turn on the client callback feature.

public partial class asyncgridview : System.Web.UI.Page, ICallbackEventHandler

Step 4. Bind the call back reference
The literal control placed in the JavaScript function in step 2 has to contain the client callback reference. Add the following to the Page_Load.

if (!Page.IsCallback)
ltCallback.Text = ClientScript.GetCallbackEventReference(this, "'bindgrid'", "EndGetData", "'asyncgrid'", false);

Step 5. Bind the grid and return the rendered HTML
To finish the asynchronous loading we have to implement the two methods that are defined by the ICallbackEventHandler interface we implemented in step 3. One of the methods binds a DataTable to the GridView and renders the control. The second returns the rendered HTML to the JavaScript method we defined in step 2.

private string _Callback;

public string GetCallbackResult()
{
return _Callback;
}

public void RaiseCallbackEvent(string eventArgument)
{
DataTable table = RetrieveDataTableFromDatabase();
gvAsync.DataSource = table;
gvAsync.DataBind();

using (System.IO.StringWriter sw = new System.IO.StringWriter())
{
gvAsync.RenderControl(new HtmlTextWriter(sw));
_Callback = sw.ToString();
}
}

You can use your present data binding method to bind the GridView. The important part is that the GridView is data bound before the RaiseCallbackEvent method renders the control.

The same technique can be used for all the data control such as the Repeater, FormView and DataList.






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

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

head>

<body>

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



<div id="grid">

<span>Loading...span>

<asp:GridView runat="Server" ID="gvAsync" />

div>



<script type="text/javascript">

function EndGetData(arg)

{

document.getElementById("grid").innerHTML = arg;

}



setTimeout("server" id="ltCallback" />", 100);

script>



form>

body>

html>



using System;

using System.Data;

using System.Web;

using System.Web.UI;

using System.Web.UI.WebControls;



public partial class asyncgridview : System.Web.UI.Page, ICallbackEventHandler

{

protected void Page_Load(object sender, EventArgs e)

{

System.Threading.Thread.Sleep(5000);

if (!Page.IsCallback)

ltCallback.Text = ClientScript.GetCallbackEventReference(this, "'bindgrid'", "EndGetData", "'asyncgrid'", false);

}



private DataTable RetrieveDataTableFromDatabase()

{

DataTable table = new DataTable();

table.Columns.Add("Product", typeof(string));

table.Columns.Add("Price", typeof(float));



table.Rows.Add("Hat", 16);

table.Rows.Add("Jacket", 234);

table.Rows.Add("Socks", 35);



return table;

}



#region ICallbackEventHandler Members



private string _Callback;



public string GetCallbackResult()

{

return _Callback;

}



public void RaiseCallbackEvent(string eventArgument)

{

DataTable table = RetrieveDataTableFromDatabase();

gvAsync.DataSource = table;

gvAsync.DataBind();



using (System.IO.StringWriter sw = new System.IO.StringWriter())

{

gvAsync.RenderControl(new HtmlTextWriter(sw));

_Callback = sw.ToString();

}

}



#endregion

}

size of the viewstate in ASP.NET





When you are developing an ASP.NET web form, you want to make sure that the viewstate isn't larger than it has to be. The more viewstate you've got, the longer the page takes to render in the browser. I have often seen gigantic viewstates, larger than 50 kb in size. For obvious reasons, this is not desirable if it can be avoided without breaking any functionality.

To test the size of the viewstate, just view the source code and count the lines of the hidden input field where the viewstate resides. This is not a very accurate measure but the is an easier way. Before deploying the final website to the public, you can add this method to the page and it will print out the number of characters in the viewstate. This is a much faster way of testing it for optimization.



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

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>Untitled Pagetitle>
head>
<body>
<form id="form1" runat="server">
<div>

div>
form>
body>
html>




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.RegularExpressions;
public partial class ViewState : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{

}
protected override void Render(HtmlTextWriter writer)
{
System.IO.StringWriter sw = new System.IO.StringWriter();
HtmlTextWriter htmlWriter = new HtmlTextWriter(sw);
base.Render(htmlWriter);

string viewstate = GetViewstate(sw.ToString());
Response.Write(viewstate.Length);
writer.Write("Size Of View State");
writer.Write(sw.ToString());
}

private string GetViewstate(string html)
{
Regex regex = new Regex("()", RegexOptions.IgnoreCase);
Match match = regex.Match(html);

if (match.Success)
{
int start = match.Captures[0].Value.IndexOf("value=\"") + 7;
int stop = match.Captures[0].Value.LastIndexOf("\"");
return match.Captures[0].Value.Substring(start, stop - start);
}

return string.Empty;
}
}

How To Create a Value Type That Can Be Initialized to Null



You have a variable that is a numeric type, which will hold a numeric value obtained from a database. The database may return this value as a null. You need a simple clean way to store this numeric value, even if it is returned as a null.

Use a nullable value type. There are two ways of creating a nullable value type. The first way is to use the ? type modifier:

In addition, testing the nullable type can be done in

one of two ways. First, by using the HasValue property as shown here:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="NullableType.aspx.cs" Inherits="NullableType" %>

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>Untitled Pagetitle>
head>
<body>
<form id="form1" runat="server">
<div>
<table border="1">
<tr>
<td>
<asp:Label ID="Label1" runat="server" Text="Label">asp:Label>
td>
<td>
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Button" />td>
tr>
table>
div>
form>
body>
html>


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;

public partial class NullableType : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{

}
protected void Button1_Click(object sender, EventArgs e)
{
//Essentially both of the following statements are equivalent:
int? myDBInt = null;
Nullable<int> myDBInt = new Nullable<int>();


if (myDBInt.HasValue)
Label1.Text = "Has a value: " + myDBInt.Value;
else
Label1.Text = "Does not have a value (NULL)";

}
}

How To Add Programming Languages in the App_Code Folder


The source code in the App_Code folder is compiled into a single assembly, all the files in the App_Code folder must be in the same programming language. For example, the App_Code folder cannot include source code in both Visual Basic and C#.

However, you can configure your Web application to treat subfolders of the App_Code folder as separate compilable units. Each folder can then contain source code in a different programming language. The configuration is specified by creating a codeSubDirectories element in the compilation element of the Web.config file and adding a reference to the subfolder. The following example illustrates how you would configure subfolders named VBCode and CSCode to compile into separate assemblies:




compilation debug="false">
<codeSubDirectories>
<add directoryName="VBCode" />
<add directoryName="CSCode" />
codeSubDirectories>
compilation>

The references to the VBCode and CSCode subfolders do not need to include any
information about what programming language is contained in the subfolder.
with the App_Code folder itself, ASP.NET infers the compiler to use based on the
files in the subfolder.

How To Create A Filebrowser in ASP





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

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>Untitled Pagetitle>
head>
<body>
<form id="form1" runat="server">
<div>
<h1 class="boxes">
Files on the Server:
<asp:Literal ID="litLocation" runat="server" />
h1>
<asp:Panel ID="panFiles" runat="server" CssClass="boxes">
<asp:PlaceHolder ID="myPlaceHolder" runat="server" />
asp:Panel>
<asp:Panel ID="Panel1" runat="server" CssClass="boxes">
<asp:TextBox ID="txtFolder" runat="server">asp:TextBox>
<asp:Button ID="btnNewFolder" runat="server" Text="Create New Folder" OnClick="btnNewFolder_Click" />
asp:Panel>
<asp:Panel ID="panUpload" runat="server" CssClass="boxes">
Choose a file to upload to the server<br />
<asp:FileUpload ID="fupTest" runat="server" Width="400px" />
<br />
<asp:Button ID="btnUpload" runat="server" Text="Upload File" OnClick="btnUpload_Click" />
<p>
<asp:Label ID="labMessage" runat="server">asp:Label>
p>
asp:Panel>
div>
form>
body>
html>


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.IO;

public partial class FileBrowser : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string currentRoot = RetrievePathOfFolderToDisplay();
litLocation.Text = currentRoot;
GenerateListing(currentRoot);
}
///
/// Displays the content of the specified folder.
///

private void GenerateListing(string rootpath)
{
// First clear out the place holder
myPlaceHolder.Controls.Clear();
// Calculate the path to retrieve folders + files
string path = Server.MapPath("") + "/" + rootpath;
// Make the "go up a level" link if needed
MakeUpOneLevelLink(rootpath);
// Get a list of all folders
DirectoryInfo dirInfo = new DirectoryInfo(path);
DirectoryInfo[] folders = dirInfo.GetDirectories();
// Loop through each folder and display it
foreach (DirectoryInfo folder in folders)
{
DisplayFolder(folder, rootpath);
}
// Get a list of all the files in current path
FileInfo[] files = dirInfo.GetFiles();
// Loop through each file
foreach (FileInfo file in files)
{
DisplayFile(file, rootpath);
}
}
///
/// Retrieves the path of the folder to be displayed
///

///
private string RetrievePathOfFolderToDisplay()
{
string localpath = Request.QueryString["local"];
// If no query string, use uploads folder as the root
if (localpath == null)
return "uploads";
else
// Remove the URL encoding necessary for
// the querystring
return Server.UrlDecode(localpath);
}
///
/// Displays the appropriate controls for the passed folder
///

private void DisplayFolder(DirectoryInfo folder, string rootpath)
{
// Get the folder name without the path
string shortfolder = Path.GetFileName(folder.FullName);
// Add a folder icon
Image img = new Image();
img.ImageUrl = "images/mime_folder.png";
myPlaceHolder.Controls.Add(img);
// Add a nonbreakable space
LiteralControl space1 = new LiteralControl(" ");
myPlaceHolder.Controls.Add(space1);
// Add a link to the folder so user can display it
HyperLink lnk = new HyperLink();
lnk.Text = shortfolder;
// The link for the folder must pass the folder name.
// Because the folder name may contain characters that are
// not allowed in a querystring, we must URL encode it
lnk.NavigateUrl = "FileBrowser.aspx?local=" +
Server.UrlEncode(rootpath + "/" + shortfolder);
myPlaceHolder.Controls.Add(lnk);
// Add a line break
LiteralControl br1 = new LiteralControl("
"
);
myPlaceHolder.Controls.Add(br1);
}
///
/// Displays the appropriate controls for the passed file
///

private void DisplayFile(FileInfo file, string rootpath)
{// Get the filename without the path
string shortname = Path.GetFileName(file.FullName);
// Add a file icon
Image img = new Image();
img.ImageUrl = GetIconForExtension(file);
myPlaceHolder.Controls.Add(img);
// Add a nonbreakable space
LiteralControl space2 = new LiteralControl(" ");
myPlaceHolder.Controls.Add(space2);
// Add a link to the file so user can download/view it
HyperLink lnk = new HyperLink();
lnk.Text = shortname;
lnk.NavigateUrl = Server.UrlDecode(rootpath) + "/" +
shortname;
myPlaceHolder.Controls.Add(lnk);
// Add the file size in kb
long kb = file.Length / 1000;
LiteralControl size = new LiteralControl(" [" + kb +
" KB]");
myPlaceHolder.Controls.Add(size);
// Add a line break
LiteralControl br2 = new LiteralControl("
"
);
myPlaceHolder.Controls.Add(br2);
}
///
/// Returns the filename of the appropriate icon image file
/// based on the extension of the passed file
///

private string GetIconForExtension(FileInfo file)
{
string image = "images/";
string ext = Path.GetExtension(file.FullName).ToLower();
if (ext == ".txt")
image += "mime_text.png";
else if (ext == ".doc")
image += "mime_doc.png";
else if (ext == ".pdf")
image += "mime_pdf.png";
else if (ext == ".gif" || ext == ".jpg" || ext == ".wmf")
image += "mime_image.gif";
else if (ext == ".html" || ext == ".htm")

image += "mime_html.gif";
else
image += "mime_unknown.png";
return image;
}
///
/// Makes the "go up a level" link (if needed for the
/// current folder) and adds it to the place holder
///

private void MakeUpOneLevelLink(string currentFolder)
{
// Get the previous folder (the next one "up" in
// the hierarchy)
string previousFolder = GetPreviousFolder(currentFolder);
// If there is a previous path, add a link to
// place holder
if (previousFolder != "")
{
Image imgBack = new Image();
imgBack.ImageUrl = "images/mime_folder.gif";
myPlaceHolder.Controls.Add(imgBack);
HyperLink lnkBack = new HyperLink();
lnkBack.Text = "..";
lnkBack.NavigateUrl = "FileBrowser.aspx?local=" +
Server.UrlEncode(previousFolder);
myPlaceHolder.Controls.Add(lnkBack);
LiteralControl br = new LiteralControl("
"
);
myPlaceHolder.Controls.Add(br);
}
}
///
/// Gets the previous folder (the next one "up" in the file
/// system hierarchy) from the passed path.
/// If there was no previous folder, return an
/// empty string
///

private string GetPreviousFolder(string path)
{
int posOfLastSlash = path.LastIndexOf("/");
if (posOfLastSlash < 0)
return "";
string stripped = path.Remove(posOfLastSlash);
return stripped;
}
///
/// Event handler for the upload button for the FileUploader
///

protected void btnUpload_Click(object sender, EventArgs e)
{
// The location for the uploaded file is current path
string path = RetrievePathOfFolderToDisplay();
if (fupTest.HasFile)
{
string fullname = Server.MapPath(path + "/" +
fupTest.FileName);
if (System.IO.File.Exists(fullname))
{
labMessage.Text =
"File already exists - uploaded cancelled";
}
else
{
fupTest.SaveAs(fullname);
labMessage.Text = "File successfully uploaded";
// Recreate the file listing to show the
// uploaded file
GenerateListing(path);
}
}
else
{
labMessage.Text = "File was not specified";
}
}
///
/// Event handler for the create new folder button
///

protected void btnNewFolder_Click(object sender, EventArgs e)
{
// Get the location for the new folder
string folderLocation = RetrievePathOfFolderToDisplay();
string fullPath = Server.MapPath(folderLocation) + "/" +
txtFolder.Text;
// Create the folder on the server
Directory.CreateDirectory(fullPath);
// Recreate the file listing to show the new folder
GenerateListing(folderLocation);
}

}

How to add an RSS feed to your website






Many websites have RSS feeds, especially websites with blogs. An RSS feed identifies content on your website, including the publication date. Web browsers and blog readers use the RSS feed to notify users when content is updated.

The acronym RSS stands for "really simple syndication", and the "really simple" part is no exaggeration. Thanks to the simplicity of RSS it's very easy to add an RSS feed to your website. You can read about the RSS specification here.

Here's what my RSS feed looks like. Pretty simple, eh?

Step 1: Create an .aspx page (e.g. rss.aspx) that returns information about your content in RSS format. This .aspx page will return data in XML format, not HTML. I recommend using output caching on this page since it's likely to be retrieved frequently. I cache my rss feed for one minute:



<%@ OutputCache Duration="60" VaryByParam="none" %>

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

In the code-behind for the .aspx page, just build your RSS data and output it with Response.Write.

For example, here's my code-behind. The code first calls a dummy Data Method to get all the data about my blog. The data is stored in a dataset. Then the code iterates through each row in the dataset and builds the section of the RSS XML. Finally, the items are inserted into the XML and the XML is output using Response.Write():
Step 2: Now that you have a .aspx page that returns your RSS data, you need to notify web browsers and blog readers that the feed exists. Just add a tag to the section of your .aspx pages. For example, here's my tag:



<head runat="server">

<link rel="alternate" type="application/rss+xml" title="RSS" href="rss.aspx" runat="server" id="rss_link" visible="false" />



<title>Untitled Pagetitle>

head>

check out this complete code



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

<%@ OutputCache Duration="60" VaryByParam="none" %>



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

<link rel="alternate" type="application/rss+xml" title="RSS" href="rss.aspx" runat="server" id="rss_link" visible="false" />



<title>Untitled Pagetitle>

head>

<body>

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

<div>



div>

form>

body>

html>



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;



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

{

protected void Page_Load(object sender, EventArgs e)

{



rss_link.Visible = true;



if (!IsPostBack)

{

DataTable entriesDataSet = new DataTable();

entriesDataSet = Data();



const string itemFormat =

@"



{0}

{1}

{2}

{3}

"
;



string items = string.Empty;



foreach (DataRow row in entriesDataSet.Rows)

{

string url = string.Format("http://localhost/MyPractice/Rss.aspx?b={0}", row["ID"]);

DateTime pubDate = (DateTime)row["TimeStamp"];



string item = string.Format(itemFormat, row["Title"], url, row["Title"], pubDate.ToString("s"));



items = item + items;

}



const string rssFormatString =

@""2.0"">





xyz

http://aspdotnetcodebook.blogspot.com

by xyz

{1}



"
;



string result = string.Format(rssFormatString, DateTime.Now, items);



Response.Clear();

Response.BufferOutput = true;

Response.ContentType = "text/xml";

Response.StatusCode = 200;



Response.Write(result);

Response.End();

}

}



public DataTable Data()

{



DataTable dt = new DataTable();

dt.Columns.Add("Id", typeof(int));

dt.Columns.Add("Title", typeof(string));

dt.Columns.Add("link", typeof(string));

dt.Columns.Add("description", typeof(string));

dt.Columns.Add("TimeStamp", typeof(DateTime));



dt.Rows.Add(new object[] { "1", "test", "http://abc.com ", "test", "12/12/2008" });

dt.Rows.Add(new object[] { "2", "test", "http://abc.com ", "test", "12/12/2008" });

dt.Rows.Add(new object[] { "3", "test", "http://abc.com ", "test", "12/12/2008" });



return dt;

}

}

Export Html to Pdf using iTextSharp(GridView)







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

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>Untitled Pagetitle>
head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="GridView1" runat="server">
asp:GridView>
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Pdf" />div>
form>
body>
html>




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 iTextSharp.text;
using iTextSharp.text.pdf;
using System.IO;
using iTextSharp.text.html;

public partial class Pdf : MyPage
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
GridView1.DataSource = GetData();
GridView1.DataBind();
}

}
protected void Button1_Click(object sender, EventArgs e)
{
MyPage tmpPage = new MyPage();
HtmlForm form = new HtmlForm();
form.Controls.Add(GridView1);
tmpPage.Controls.Add(form);
StringWriter sw = new StringWriter();
HtmlTextWriter htmlWriter = new HtmlTextWriter(sw);
form.Controls[0].RenderControl(htmlWriter);
string htmlContent = sw.ToString();
Document document = new Document();
// step 2:
// we create a writer that listens to the document
// and directs a PDF-stream to a file
PdfWriter.GetInstance(document, new FileStream("c:\\Chap0101.pdf", FileMode.Create));

// step 3: we open the document
document.Open();

// step 4: we add a paragraph to the document
//document.Add(new Paragraph(htmlContent.ToString()));

System.Xml.XmlTextReader _xmlr = new System.Xml.XmlTextReader(new StringReader(htmlContent));

HtmlParser.Parse(document, _xmlr);

// step 5: we close the document
document.Close();

ShowPdf("c:\\Chap0101.pdf");

}

private void ShowPdf(string s)
{
Response.ClearContent();
Response.ClearHeaders();
Response.AddHeader("Content-Disposition", "inline;filename=" + s);
Response.ContentType = "application/pdf";
Response.WriteFile(s);
Response.Flush();
Response.Clear();
}
public DataSet GetData()
{
DataSet ds = new DataSet();
DataTable dt = new DataTable("Product");
DataRow dr;
dt.Columns.Add(new DataColumn("Price", typeof(Int32)));
dt.Columns.Add(new DataColumn("DisCount", typeof(Int32)));
dt.Columns.Add(new DataColumn("SellPrice", typeof(Int32)));
for (int i = 1; i <= 10; i++)
{
dr = dt.NewRow();
dr[0] = i;
dr[1] = i * 2;
dr[2] = 1 * 3;
dt.Rows.Add(dr);
}
ds.Tables.Add(dt);
Session["dt"] = dt;
return ds;
}
}


*Create a new clas Mypage.cs in app_code folder.

using System;
using System.Data;
using System.Configuration;
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;

///
/// Summary description for MyPage
///

public class MyPage : Page
{
public override void VerifyRenderingInServerForm(Control control)
{
GridView grid = control as GridView;
if (grid != null && grid.ID == "GridView1")
return;
else
base.VerifyRenderingInServerForm(control);

}
}

Archives