Você está na página 1de 181

ASP.

NET Code Books


Over the years I have collected some best asp.net code while
googling........I hope this information is as useful to you as it has
been for me

If you find my post contains a reference to a third party World


Wide Web site, I am providing this information as a
convenience to you.I cannot make any representations
regarding the quality,safety, or suitability of any software or
information found there.

BLOG A R C H I V E
• ▼ 2008 (261)
o ▼ April (58)
 GridView Tips and Trics
 How To get IP Address to Country/State using www....
 ModalPopupExtender Example for Editing Rows in a
G...
 How To Redirect into a new window using
Response.R...
 Exception Handling With Update Panel
 ASP.NET AJAX: How to call client-side Javascript o...
 How To Use ModalPopup
 ModalPopup With Textbox and Validator
 How To Trigger .net Function With Javascript
 How To Disable Right Click
 Accessing an array on the client that has been cre...
 How To Convert XMLNodeList To DataTable
 Send an e-mail with the content of a GridView
 IFrame in ASP.NET
 IFrame GoogleMAP and ModalPopup
 Client Side Validation for CheckBoxes,textbox ins...
 How To Convert a DataReader into a DataSet
 How To Create ASP.NET Control From XML using XSLT
 How To Add multiple dynamic onload events to body
...
 How to bind RSS feeds to a GridView
 How To Add Search Feature To GridView
 How To Add client side calculation for gridview co...
 Create new gridview row with javascript
 How To Read a DataSet object in Javascript
 How To Use XML Script in ASP.net 2.0
 Is text/xml-script working ?
 Passing arrayList to javascript function
 How To Call a WebService with ASP.Net Ajax
 When you use the UpdatePanel control you probably
...
 How To embedded resource file(like-flash,javascrip...
 GridView with DataTable as source with paging and ...
 How To Use Menu and Multiview Control
 How to read XML file using javascript
 How To Create Database Driven Menu in ASP.NET
(C#...
 How To -Cross page postbacks in ASP.NET 2.0
 Use ICallbackEventHandler in Asp.Net 2.0
 Modal Popup from Repeater
 Displaying vertical rows in a GridView
 How To populating DropDownList control from XML
d...
 How to bind selected node values in Gridview
 How To Load Web user control inside a GridView
 Search And Highlight word in Gridview
 How To Freez Header Of Gridview
 How To Use Multiview As a Tab Control
 Mark a GridView row, and move it with the up and
d...
 Function to get parent GridView for GridViewRow
 Validate DropDownlist or TextBox Inside GridView
 Data-Binding to Methods in ASP.NET(conditionally)
 Automatic Edit and save Action in a Html Table
 Bind GridView To Generics
 GridView Confirm When Delete.
 ASP.NET AJAX Tabs Control
 Maintain The State Of Checkbox After Postback (Ins...
 Showing data from multiple tables effectively us...
 How To Validate Calender Control in Asp.net 2.0
 How To Bing GridView with Custom Class
 passing data from javascript to asp.net cs code on...
 How To Add Client Side code to to select Checkbo...
o ► March (97)
o ► February (14)
o ► January (92)

• ► 2007 (3)
o ► December (2)
o ► January (1)
ABOUT ME
D O T NE T LOV E R
VIE W M Y C OM PL E TE P ROF IL E

Enter your search terms Submit search form


aspdotnetcodebook.blogspot.c
Web
om
fourms.asp.net

T H U R S D AY, A P R I L 2 4 , 2 0 0 8
GridView Tips and Trics

<%@ Page Language="C#" AutoEventWireup="true"


CodeFile="GridViewComplete.aspx.cs"
Inherits="GridViewComplete" %>

<!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>Grid View Add Update Delete</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="GridView1" runat="server"
AutoGenerateColumns="False" DataKeyNames="Id"
ShowFooter="true" AllowPaging="true"
PageSize="4"
AllowSorting="True"
OnRowCommand="GridView1_RowCommand"
OnPageIndexChanging="GridView1_PageIndexChang
ing"
OnRowDeleting="GridView1_RowDeleting"
OnRowEditing="GridView1_RowEditing"
OnRowUpdating="GridView1_RowUpdating"
OnSorting="GridView1_Sorting"
OnRowCancelingEdit="GridView1_RowCancelingEdi
t">
<Columns>
<asp:CommandField ShowDeleteButton="True"
ShowEditButton="True" />
<asp:TemplateField HeaderText="Id"
InsertVisible="False" SortExpression="Id">
<EditItemTemplate>
<asp:Label ID="Label1"
runat="server"
Text='<%# Eval("Id") %>'></asp:Label>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label1"
runat="server"
Text='<%# Bind("Id") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="Id"
ShowHeader="True"/>
<asp:TemplateField HeaderText="Name"
SortExpression="Name">
<EditItemTemplate>
<asp:TextBox ID="TextBox1"
runat="server"
Text='<%# Bind("Name") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label2"
runat="server"
Text='<%# Bind("Name") %>'></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="QuantityTextBox"
runat="server"></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField
HeaderText="Description" SortExpression="Description">
<EditItemTemplate>
<asp:TextBox ID="TextBox2"
runat="server"
Text='<%# Bind("Description") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label3"
runat="server"
Text='<%# Bind("Description") %>'></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox
ID="DescriptionTextBox" runat="server"></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField>
<FooterTemplate>
<asp:LinkButton ID="btnNew"
runat="server"
CommandName="New" Text="New" />
</FooterTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
<div style="color:Red">
<asp:Label ID="lblMsg" runat="server"></asp:Label>
</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 GridViewComplete : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{

if (!IsPostBack)
{
BindGrid();

}
}
public void BindGrid()
{

if (Session["dt"] == null)
{
GridView1.DataSource = CreateDGDataSource();
GridView1.DataBind();
}
else
{

GridView1.DataSource = Session["dt"] as
DataTable;
GridView1.DataBind();

}
public DataTable CreateDGDataSource()
{
// Create sample data for the DataList control.
DataTable dt = new DataTable();
DataRow dr;
int i;
int y;
// Define the columns of the table.
dt.Columns.Add(new DataColumn("ID", typeof(int)));
dt.Columns.Add(new DataColumn("Name",
typeof(string)));
dt.Columns.Add(new DataColumn("Description",
typeof(string)));
//Make some rows and put some sample data in
for (i = 1; i <= 5; i++)
{
dr = dt.NewRow();
dr[0] = i;
dr[1] = "Name" + "-" + i;
dr[2] = "Item " + "_" + i;
//add the row to the datatable
dt.Rows.Add(dr);
}

Session["y"] = i;
Session["dt"] = dt;

return dt;
}

public ICollection CreateDGDataSource(int CategoryID)


{
DataView dv = new DataView(CreateDGDataSource(),
"ID=" + CategoryID, null,
DataViewRowState.CurrentRows);
return dv;

}
protected void GridView1_RowCommand(object sender,
GridViewCommandEventArgs e)
{
try
{
if (e.CommandName.Equals("New"))
{
LinkButton btnNew = e.CommandSource as
LinkButton;
GridViewRow row = btnNew.NamingContainer as
GridViewRow;
if (row == null)
{
return;
}
TextBox txtCatName =
row.FindControl("QuantityTextBox") as TextBox;
TextBox txtDescription =
row.FindControl("DescriptionTextBox") as TextBox;
DataTable dt = Session["dt"] as DataTable;
DataRow dr;
int intId = (int)Session["y"];
dr = dt.NewRow();
dr["Id"] = intId++;
Session["y"] = intId;
dr["Name"] = txtCatName.Text;
dr["Description"] = txtDescription.Text;
dt.Rows.Add(dr);
dt.AcceptChanges();
Session["dt"] = dt;

GridView1.DataSource = Session["dt"] as
DataTable;
GridView1.DataBind();

}
catch (Exception ex)
{

protected void GridView1_PageIndexChanging(object


sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
BindGrid();
}
protected void GridView1_Sorting(object sender,
GridViewSortEventArgs e)
{
DataTable dataTable = Session["dt"] as DataTable;
if (dataTable != null)
{
DataView dataView = new DataView(dataTable);
dataView.Sort = e.SortExpression + " " +
ConvertSortDirectionToSql(e.SortDirection);
GridView1.DataSource = dataView;
GridView1.DataBind();
}
}
private string ConvertSortDirectionToSql(SortDirection
sortDireciton)
{
string newSortDirection = String.Empty;
switch (sortDireciton)
{
case SortDirection.Ascending:
newSortDirection = "ASC";
break;
case SortDirection.Descending:
newSortDirection = "DESC";
break;
}
return newSortDirection;
}
protected void GridView1_RowDeleting(object sender,
GridViewDeleteEventArgs e)
{
int ID = (int)GridView1.DataKeys[e.RowIndex].Value;
// Query the database and get the values based on
the ID and delete it.
lblMsg.Text = "Deleted Record Id" +ID.ToString();

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

// Retrieve the row being edited.


int index = GridView1.EditIndex;
GridViewRow row = GridView1.Rows[index];
TextBox t1 = row.FindControl("TextBox1") as TextBox;
TextBox t2 = row.FindControl("TextBox2") as TextBox;
string t3 =
GridView1.DataKeys[e.RowIndex].Value.ToString();

lblMsg.Text = "Updated record " + t1.Text + "," +


t2.Text + "Value From Bound Field" + t3;
}
protected void GridView1_RowCancelingEdit(object
sender, GridViewCancelEditEventArgs e)
{
GridView1.EditIndex = -1;
BindGrid();
}
}
P OSTE D BY D OT NE T LOVE R AT 2 :46 PM 0 C OMM E N TS

How To get IP Address to Country/State using


www.hostip.info

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.Net;
using System.Text;

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


{
protected void Page_Load(object sender, EventArgs e)
{
string ipUrl =
"http://www.hostip.info/api/get.html?ip=" +
Request.UserHostAddress;

WebClient webClient = new WebClient();


Byte[] ipInfoBytes = webClient.DownloadData(ipUrl);
UTF8Encoding encoding = new UTF8Encoding();
string ipInfo = encoding.GetString(ipInfoBytes);

Response.Write(ipInfo);

}
}

P OSTE D BY D OT NE T LOVE R AT 8 :56 AM 0 C OM M E N TS

ModalPopupExtender Example for Editing Rows in a


GridView (Master/Detail Scenario)
<%@ Page Language="C#" AutoEventWireup="true"
CodeFile="MasterDetail.aspx.cs"
Inherits="MasterDetail" %>

<%@ Register Assembly="AjaxControlToolkit"


Namespace="AjaxControlToolkit" TagPrefix="ajaxtoolkit" %>
<!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 Page</title>
</head>
<body>
<form id="form" runat="server">
<asp:ScriptManager ID="scriptManager" runat="server"
/>
<div>
<asp:UpdatePanel ID="updatePanel" runat="server"
UpdateMode="Conditional">
<ContentTemplate>
<asp:Label ID="lblTitle" runat="server"
Text="Customers" BackColor="lightblue" Width="95%" />
<asp:GridView ID="gvCustomers"
runat="server" DataKeyNames="Id" AutoGenerateColumns="false"
AllowPaging="true"
AllowSorting="true" PageSize="10" Width="95%">
<AlternatingRowStyle
BackColor="aliceBlue" />
<HeaderStyle HorizontalAlign="Left"
/>
<Columns>
<asp:TemplateField ControlStyle-
Width="50px" HeaderStyle-Width="60px">
<ItemTemplate>
<asp:Button
ID="btnViewDetails" runat="server" Text="Details"
OnClick="BtnViewDetails_Click" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="Id"
HeaderText="ID" SortExpression="Id" ReadOnly="true" />
<asp:BoundField DataField="Name"
HeaderText="Name" SortExpression="contactname"
ReadOnly="true" />
</Columns>
</asp:GridView>
</ContentTemplate>
</asp:UpdatePanel>
<asp:Button ID="btnShowPopup" runat="server"
Style="display: none" />
<ajaxtoolkit:ModalPopupExtender ID="mdlPopup"
runat="server" TargetControlID="btnShowPopup"
PopupControlID="pnlPopup"
CancelControlID="btnClose"
BackgroundCssClass="modalBackground" />
<asp:Panel ID="pnlPopup" runat="server"
Width="500px" Style="display: none">
<asp:UpdatePanel ID="updPnlCustomerDetail"
runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:Label ID="lblCustomerDetail"
runat="server" Text="Customer Detail" BackColor="lightblue"
Width="95%" />
<asp:DetailsView
ID="dvCustomerDetail" runat="server" DefaultMode="Edit"
Width="95%"
BackColor="white" />
</ContentTemplate>
</asp:UpdatePanel>
<div align="right" style="width: 95%">
<asp:Button ID="btnSave" runat="server"
Text="Save"
OnClientClick="alert('Sorry, but I didnt implement save ');
return false;"
Width="50px" />
<asp:Button ID="btnClose" runat="server"
Text="Close" Width="50px" />
</div>
</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;

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


{
DataSet ds;
protected void Page_Load(object sender, EventArgs e)
{

ds = Data();
if (!this.IsPostBack)
{
if (Session["parent"] == null)
{
gvCustomers.DataSource =
ds.Tables["Parent"];
gvCustomers.DataBind();
}
else
{
gvCustomers.DataSource = Session["Parent"]
as DataTable;
gvCustomers.DataBind();

}
}

}
private DataSet Data()
{

DataTable dt = new DataTable();


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

dt.Rows.Add(new object[] { 1, "aaaa" });


dt.Rows.Add(new object[] { 2, "bbbb" });
dt.Rows.Add(new object[] { 3, "cccc" });
dt.TableName = "Parent";

DataTable dtc = new DataTable();


dtc.Columns.Add("Id", typeof(int));
dtc.Columns.Add("Qul", typeof(string));
dtc.Rows.Add(new object[] { 1, "aaaa" });
dtc.Rows.Add(new object[] { 2, "bbbb" });
dtc.Rows.Add(new object[] { 3, "bbbb" });
dtc.TableName = "Child";

DataSet ds = new DataSet();

ds.Tables.Add(dt);
ds.Tables.Add(dtc);
Session["Parent"] = dt;

return ds;

}
protected void BtnViewDetails_Click(object sender,
EventArgs e)
{
// get the gridviewrow from the sender so we can
get the datakey we need
Button btnDetails = sender as Button;
GridViewRow row =
(GridViewRow)btnDetails.NamingContainer;

// extract the id from the row whose details


button originated the postback.
// grab the customerid and feed it to the customer
details datasource
// finally, rebind the detailview
DataView dv = new DataView(ds.Tables["Child"]);

dv.RowFilter = "Id=" +
Convert.ToString(this.gvCustomers.DataKeys[row.RowIndex].Va
lue);
dvCustomerDetail.DataSource = dv;
dvCustomerDetail.DataBind();

// update the contents in the detail panel


this.updPnlCustomerDetail.Update();
// show the modal popup
this.mdlPopup.Show();
}
}

P OSTE D BY D OT NE T LOVE R AT 7 :57 AM 0 C OM M E N TS


W E D N E S D AY, A P R I L 2 3 , 2 0 0 8
How To Redirect into a new window using
Response.Redirect

<%@ Page Language="C#" AutoEventWireup="true"


CodeFile="RedirectToAnotherPage.aspx.cs"
Inherits="RedirectToAnotherPage" %>

<!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 Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<h1>Main Window</h1>
<asp:Button ID="btn" runat="server" Text="Redirect"
OnClick="btn_Click" />
</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 RedirectToAnotherPage :


System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{

}
public static class ResponseHelper
{

public static void Redirect(string url, string target,


string windowFeatures)
{
HttpContext context = HttpContext.Current;

if ((String.IsNullOrEmpty(target) ||

target.Equals("_self",
StringComparison.OrdinalIgnoreCase)) &&
String.IsNullOrEmpty(windowFeatures))
{

context.Response.Redirect(url);
}
else
{
Page page = (Page)context.Handler;
if (page == null)
{
throw new InvalidOperationException(
"Cannot redirect to new window outside
Page context.");
}
url = page.ResolveClientUrl(url);

string script;

if (!String.IsNullOrEmpty(windowFeatures))
{
script = @"window.open(""{0}"", ""{1}"",
""{2}"");";
}
else
{

script = @"window.open(""{0}"", ""{1}"");";

script = String.Format(script, url, target,


windowFeatures);
ScriptManager.RegisterStartupScript(page,

typeof(Page),

"Redirect",

script,

true);

}
protected void btn_Click(object sender, EventArgs e)
{
ResponseHelper.Redirect("popup.aspx", "_blank",
"menubar=0,width=100,height=100");
}
}

P OSTE D BY D OT NE T LOVE R AT 3 :26 PM 0 C OMM E N TS

Exception Handling With Update Panel


If you don't do anything, when you get an error during partial postback
you'll get a simple alert message box showing you the error message
associated with the exception you had in the server. As we all agree,
this is not the best info to show to our users; it's also not a good idea
to show a standard error message. If we don't mind showing an alert
message in the client, then we can start by handling the
AsyncPostBackError event generated by the ScriptManager control in
order to customize the error message returned from the server. Here's
a simple page that shows this approach:

<%@ Page Language="C#" AutoEventWireup="true"


CodeFile="AjaxErrorHandling.aspx.cs"
Inherits="AjaxErrorHandling" %>

<!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 Page</title>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager runat="server" ID="manager"
OnAsyncPostBackError="HandleError">
</asp:ScriptManager>
<asp:UpdatePanel runat="server" ID="panel">
<ContentTemplate>
<asp:Button runat="server" ID="bt" Text="gerar
erro no servidor"
OnClick="handleClick" />
</ContentTemplate>
</asp:UpdatePanel>
<div id="err"></div>
<!--Uncomment this for client side --->
<%--<script type="text/javascript">
Sys.WebForms.PageRequestManager.getInstance().add_endReq
uest( endRequest );
function endRequest( sender, e ) {
if( e.get_error() ){
document.getElementById("err").innerText =
e.get_error().description;
e.set_errorHandled( true );
}
}
</script>--%>

</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 AjaxErrorHandling : System.Web.UI.Page


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

}
protected void handleClick(object sender, EventArgs e)
{
int a = 0;
int res = 10 / a;
}
protected void HandleError(object sender,
AsyncPostBackErrorEventArgs e)
{
//here we could log the error, and see which
exception we're getting in order to set a specific error
message
//in this case, I'm just returning the current
date/hour back
manager.AsyncPostBackErrorMessage = "Ooops...error
occurred: " +
DateTime.Now.ToString();
}

P OSTE D BY D OT NE T LOVE R AT 1 :51 PM 0 C OMM E N TS

ASP.NET AJAX: How to call client-side Javascript


once an UpdatePanel request is over

If you are using AJAX then the only way i have found yet to give an alert to a user on
return to the Asynchronous post back is to add an “end request” handler to the
PageRequestManager.

In this way you can tell the request manager to run a javascript function on returning
from a Asynchronous post back event of AJAX.

Code for doing this is

function load() {
Sys.WebForms.PageRequestManager.getInstance().add_endReque
st(EndRequestHandler);
}
<%@ Page Language="C#" AutoEventWireup="true"
CodeFile="JavascriptCallAfterAsync.aspx.cs"
Inherits="JavascriptCallAfterAsync" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0


Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script runat="server">
protected void txtDataOnChange(object sender, EventArgs
e)
{
txtLength.Text = txtData.Text.Length.ToString();
}
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>Client-side Javascript call after an UpdatePanel
asychronous request</title>
</head>

<script type="text/javascript">
function EndRequestHandler(sender, args) {
if (args.get_error() == undefined)
alert("Your text has: " +
document.getElementById("txtLength").value + "
character(s)");
else
alert("There was an error" +
args.get_error().message);
}
function load() {
Sys.WebForms.PageRequestManager.getInstance().add_endRequ
est(EndRequestHandler);
}
</script>

<body onload="load()">
<form id="form1" runat="server">
<asp:ScriptManager ID="_scriptManager" runat="server"
/>
<div>
<asp:UpdatePanel ID="UpdatePanel1"
runat="server">
<ContentTemplate>
Write something:
<asp:TextBox ID="txtData" runat="server"
AutoPostBack="true"
OnTextChanged="txtDataOnChange" /><br />
Server says the length is:
<asp:TextBox ID="txtLength"
runat="server" AutoPostBack="true" />
</ContentTemplate>
</asp:UpdatePanel>
</div>
</form>
</body>
</html>

P OSTE D BY D OT NE T LOVE R AT 1 :34 PM 0 C OMM E N TS

How To Use ModalPopup

<%@ Page Language="C#" AutoEventWireup="true"


CodeFile="Login.aspx.cs"
Inherits="Login"
EnableEventValidation="false" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"


"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>Untitled Page</title>
<style type="text/css">
.watermark {
background: #FFAAFF;
}

.popupControl {
background-color:#AAD4FF;
position:absolute;
visibility:hidden;
border-style:solid;
border-color: Black;
border-width: 2px;
}

.modalBackground {
background-color:Gray;
filter:alpha(opacity=70);
opacity:0.7;
}

.modalPopup {
background-color:#EEEEEE;
border-width:3px;
border-style:solid;
border-color:Gray;
font-family:Verdana;
font-size:medium;
padding:3px;
width:250px;
}

.modalSignUp {
background-color:#FFFFFF;
border-width:3px;
border-style:solid;
border-color:Gray;
font-family:Verdana;
font-size:medium;
padding:3px;
width:250px;
}
.sampleStyleA {
background-color:#FFF;
}

.sampleStyleB {
background-color:#FFF;
font-family:monospace;
font-size:10pt;
font-weight:bold;
}

.sampleStyleC {
background-color:#ddffdd;
font-family:sans-serif;
font-size:10pt;
font-style:italic;
}

.sampleStyleD {
background-color:Blue;
color:White;
font-family:Arial;
font-size:10pt;
}
</style>

<script type="text/javascript">

function ok(sender, e)
{
$find('ModalPopupExtenderLogin').hide();
__doPostBack('LoginBtn', e);
}

function OnKeyPress(args)
{
if(args.keyCode == Sys.UI.Key.esc)
{
$find("ModalPopupExtenderLogin").hide();
}
}
function body_onkeydown()
{
if(event.keyCode==13 || event.keyCode==27)
{
var _defaultButtonName=getDefautButtonName(
event.keyCode==13 ? "submitButton" : "cancelButton");
var frm=document.forms[0];
if(frm && document.all(_defaultButtonName))
{
document.all(_defaultButtonName).click();
}
}
}

function getDefautButtonName(className)
{
var _defaultButtonName="";
var children =
document.getElementsByTagName("input");
for (var i = 0; i < children.length; i++)
{
var child = children[i];
var btnAction = child.buttonAction;
if(btnAction == className)
{
_defaultButtonName = child.id;
break;
}
}
return _defaultButtonName;
}

</script>

</head>
<body onkeydown="body_onkeydown()">
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
&nbsp;
<br />
<table style="width: 297px">
<tr>
<td style="width: 36px">
<asp:LinkButton ID="Loginlnk"
runat="server"
Width="47px">Login</asp:LinkButton></td>
</tr>
<tr>
<td colspan="2">
<asp:Label ID="successLabel"
runat="server"
Width="273px" Visible="False"></asp:Label></td>
</tr>
</table>
<br />
<div>
<ajaxToolkit:ModalPopupExtender
ID="ModalPopupExtenderLogin"
runat="server" TargetControlID="Loginlnk"
PopupControlID="LoginPanel"
BackgroundCssClass="modalBackground" DropShadow="true"
OkControlID="LoginBtn" OnOkScript="ok()"
CancelControlID="CancelBtn" />
&nbsp;
<br />
<br />
<asp:Panel ID="LoginPanel" runat="server"
CssClass="modalPopup" Style="display: none"
Width="278px" Font-Names="@MS PGothic">
<table style="width: 270px">
<tr>
<td style="width: 30%" align="right">
<asp:Label ID="Label10"
runat="server" Height="23px"
Text="UserName :"></asp:Label>
</td>
<td style="width: 179px">
<asp:TextBox ID="loginId"
runat="server" Width="75%"></asp:TextBox></td>
</tr>
<tr>
<td style="width: 30%" align="right">
<asp:Label ID="Label9"
runat="server" Height="23px"
Text="Password :"></asp:Label>
</td>
<td style="width: 179px">
<asp:TextBox ID="pwd"
runat="server" Width="75%"></asp:TextBox></td>
</tr>
<tr>
<td style="width: 94px">
</td>
<td style="width: 179px">
&nbsp; &nbsp; &nbsp;
<asp:Button ID="CancelBtn"
runat="server" Text="Cancel" Width="52px"
buttonAction="submitButton" />
<asp:Button ID="LoginBtn"
runat="server" Text="Log In" OnClick="LoginBtn_Click"
buttonAction="cancelButton" /></td>
</tr>
</table>
<br />
</asp:Panel>
&nbsp;<br />
</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 Login : System.Web.UI.Page


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

}
protected void LoginBtn_Click(object sender, EventArgs e)
{
//Add your DB Authentication Module here....
//This is just for testing
if (loginId.Text.Equals("user") &&
pwd.Text.Equals("user"))
successLabel.Text = "Welcome User";
else
successLabel.Text = "Authentication
Failed...Retry";
successLabel.Visible = true;
Loginlnk.Visible = false;

P OSTE D BY D OT NE T LOVE R AT 9 :51 AM 0 C OM M E N TS


ModalPopup With Textbox and Validator

<%@ Page Language="C#" AutoEventWireup="true"


CodeFile="ModalPopuuandValidation.aspx.cs"
Inherits="ModalPopupasLoader" %>

<%@ Register Assembly="AjaxControlToolkit"


Namespace="AjaxControlToolkit"
TagPrefix="ajaxToolkit" %>
<!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 Page</title>
<style type="text/css">

.modalBackground
{
background-color: Gray;
filter: alpha(opacity=50);
opacity: 0.50;

.updateProgress
{
border-width: 1px;
border-style: solid;
background-color: #FFFFFF;
position: absolute;
width: 180px;
height: 65px;
}

</style>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager runat="server" ID="Scriptmanager1">
<Scripts>
<asp:ScriptReference
Assembly="Microsoft.Web.Preview"
Name="PreviewScript.js" />
</Scripts>
</asp:ScriptManager>

<script type="text/javascript">
function postbackFromJS(sender, e) {
var postBack = new Sys.Preview.PostBackAction();
postBack.set_target(sender);
postBack.set_eventArgument(e);
postBack.performAction();
}
</script>

<asp:Button ID="Button3" runat="server" Text="Decline"


CausesValidation="false" />
<asp:Panel ID="Panel1" runat="server" Style="display:
none" CssClass="modalPopup">
<fieldset>
<asp:Panel ID="Panel3" runat="server"
CssClass="modalPanel">
Please comment.
</asp:Panel>
<br />
<asp:TextBox ID="TextBox1"
TextMode="MultiLine"
runat="server" Rows="5" Width="98%" /><br />
<asp:RequiredFieldValidator
EnableClientScript="true" ID="RequiredFieldValidator3"
runat="server" ValidationGroup="modal"
ControlToValidate="TextBox1"
ErrorMessage="Please enter a reason"
Display="Dynamic" />
<div style="text-align: center;">
<br />
<asp:Button ID="OkButton" runat="server"
Text="Decline"
ValidationGroup="modal" CausesValidation="true"
OnClick="OKButton_Click" />
<asp:Button ID="CancelButton"
runat="server" CausesValidation="false" Text="Cancel" />
</div>
</fieldset>
</asp:Panel>
<ajaxToolkit:ModalPopupExtender
ID="ModalPopupExtender" runat="server"
TargetControlID="Button3"
PopupControlID="Panel1"
BackgroundCssClass="modalBackground" OkControlID="OkButton"
CancelControlID="CancelButton" DropShadow="true"
PopupDragHandleControlID="Panel3" />
</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 ModalPopupasLoader : System.Web.UI.Page


{
protected void Page_Load(object sender, EventArgs e)
{
OkButton.OnClientClick =
String.Format("postbackFromJS('{0}',
'{1}')",OkButton.UniqueID, "");

}
protected void OKButton_Click(object sender, EventArgs e)
{
if (IsValid)
{
//do
}
else
{
ModalPopupExtender.Show();
}
}
}

P OSTE D BY D OT NE T LOVE R AT 9 :24 AM 0 C OM M E N TS

T U E S D AY, A P R I L 2 2 , 2 0 0 8
How To Trigger .net Function With Javascript

<%@ Page Language="C#" AutoEventWireup="true"


CodeFile="Trigger.aspx.cs"
Inherits="Trigger" %>

<!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 Page</title>
<script type="text/javascript">
function MyFunction1()
{
var valueToSetTo = 'abc'
__doPostBack('MyServerSideFunction1', valueToSetTo);
}
function MyFunction2()
{
var valueToSetTo = 'xyz'
__doPostBack('MyServerSideFunction2', valueToSetTo);
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Button ID="Button1" OnClientClick="MyFunction1() ;
return false;" runat="server"
Text="Button1" />
<asp:Button ID="Button2" OnClientClick="MyFunction2() ;
return false;" runat="server"
Text="Button2" />

</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 Trigger : System.Web.UI.Page


{
protected void Page_Load(object sender, System.EventArgs
e)
{
//Insure that the __doPostBack() JavaScript method
is created...
this.ClientScript.GetPostBackEventReference(this,
string.Empty);
if (this.Page.IsPostBack)
{
string eventTarget =
(this.Request["__EVENTTARGET"] == null ? string.Empty :
this.Request["__EVENTTARGET"]);
string eventArgument =
(this.Request["__EVENTARGUMENT"] == null ? string.Empty :
this.Request["__EVENTARGUMENT"]);
if (eventTarget == "MyServerSideFunction1")
{
Fun1(eventArgument);
}
else if (eventTarget == "MyServerSideFunction2")
{
Fun2(eventArgument);
}
}
}

private void Fun1(string arg)


{
Response.Write(arg);
}

private void Fun2(string arg)


{
Response.Write(arg);
}
}

P OSTE D BY D OT NE T LOVE R AT 3 :49 PM 0 C OMM E N TS

How To Disable Right Click

<%@ Page Language="C#" AutoEventWireup="true"


CodeFile="RightClickDisable.aspx.cs"
Inherits="RightClickDisable" %>

<!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 Page</title>
<script language=JavaScript>
<!--
var message="Function Disabled!";

function clickIE4(){
if (event.button==2){
alert(message);
return false;
}
}
function clickNS4(e){
if (document.layers||
document.getElementById&&!document.all){
if (e.which==2||e.which==3){
alert(message);
return false;
}
}
}

if (document.layers){
document.captureEvents(Event.MOUSEDOWN);
document.onmousedown=clickNS4;
}
else if (document.all&&!document.getElementById){
document.onmousedown=clickIE4;
}

document.oncontextmenu=new Function("alert(message);return
false")

// -->
</script>

</head>
<body>
<form id="form1" runat="server">
<div>

</div>
</form>
</body>
</html>

P OSTE D BY D OT NE T LOVE R AT 3 :39 PM 0 C OMM E N TS

Accessing an array on the client that has been created


on the server

<%@ Page Language="C#" AutoEventWireup="true"


CodeFile="ServerSideArrayOnClient.aspx.cs"
Inherits="ServerSideArrayOnClient" %>
<!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 Page</title>
</head>
<body>
<form id="Form1" runat="server">
<div>
<asp:TextBox ID="Message"
runat="server"></asp:TextBox>
<input type="button" value="get value"
onclick="DoClick()" />
</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 ServerSideArrayOnClient :


System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
String arrName = "MyArray";
String arrValue = "11, 3, 7";
ClientScriptManager cs = Page.ClientScript;
cs.RegisterArrayDeclaration(arrName, arrValue);
StringBuilder cstext = new StringBuilder();
cstext.Append("<script type=\"text/javascript\">
function DoClick() {");
cstext.Append("document.getElementById('"+Message.C
lientID+"').value=");
cstext.Append("(parseInt(" + arrName + "[1]));}</");

cstext.Append("script>");
String csname = "ConcatScript";
Type cstype = typeof(Page);
cs.RegisterClientScriptBlock(cstype, csname,
cstext.ToString(), false);
}
}

P OSTE D BY D OT NE T LOVE R AT 2 :58 PM 0 C OMM E N TS

How To Convert XMLNodeList To DataTable

<%@ Page Language="C#" AutoEventWireup="true"


CodeFile="XmlNodeListToDataTable.aspx.cs"
Inherits="XmlNodeListToDataTable" %>

<!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 Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="GridView1"
runat="server"></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;
using System.Xml;

public partial class XmlNodeListToDataTable :


System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{

XmlDocument doc = new XmlDocument();


doc.Load(Server.MapPath("Category.xml"));

//Get and display all the book titles.


XmlElement root = doc.DocumentElement;
XmlNodeList elemList =
root.GetElementsByTagName("Category");

GridView1.DataSource =
ConvertXmlNodeListToDataTable(elemList);
GridView1.DataBind();

public static DataTable


ConvertXmlNodeListToDataTable(XmlNodeList xnl)
{

DataTable dt = new DataTable();

int TempColumn = 0;

foreach (XmlNode node in xnl.Item(0).ChildNodes)


{

TempColumn++;

DataColumn dc = new DataColumn(node.Name,


System.Type.GetType("System.String"));
if (dt.Columns.Contains(node.Name))
{

dt.Columns.Add(dc.ColumnName =
dc.ColumnName + TempColumn.ToString());

else
{

dt.Columns.Add(dc);

int ColumnsCount = dt.Columns.Count;


for (int i = 0; i < xnl.Count; i++)
{

DataRow dr = dt.NewRow();

for (int j = 0; j < ColumnsCount; j++)


{

dr[j] = xnl.Item(i).ChildNodes[j].InnerText;

dt.Rows.Add(dr);

return dt;

<?xml version="1.0" encoding="utf-8"?>


<CategoryList>
<Category>
<MainCategory ID="1">XML</MainCategory>
<SubCategory>Basic</SubCategory>
<Description>List of XML articles.</Description>
<Active>Yes</Active>
</Category>
<Category>
<MainCategory ID="2">XML1</MainCategory>
<SubCategory>Basic1</SubCategory>
<Description>List of XML articles1.</Description>
<Active>Yes</Active>
</Category>
</CategoryList>

P OSTE D BY D OT NE T LOVE R AT 12 :2 1 PM 0 C OM M E N TS

Send an e-mail with the content of a GridView

<%@ Page Language="C#" AutoEventWireup="true"


CodeFile="GridViewEmail.aspx.cs"
Inherits="GridViewEmail" %>

<!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 Page</title>
</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="Send Email" /></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.Net.Mail;
using System.IO;

public partial class GridViewEmail : MyPage


{
protected void Page_Load(object sender, EventArgs e)
{
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();
// MailMessage mailMessage = new MailMessage();
MailMessage mailMessage = new
MailMessage("from@from.com", "to@to.com");

mailMessage.Subject = "My Exported GridView";


mailMessage.Body = htmlContent;
mailMessage.IsBodyHtml = true;
SmtpClient smtpClient = new SmtpClient("your smtp
server address");

smtpClient.Send(mailMessage);

}
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;
}
}

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

/// <summary>
/// Summary description for MyPage
/// </summary>
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);

}
}

P OSTE D BY D OT NE T LOVE R AT 9 :02 AM 0 C OM M E N TS

M O N D AY, A P R I L 2 1 , 2 0 0 8
IFrame in ASP.NET

<%@ Page Language="C#" AutoEventWireup="true"


CodeFile="Iframe.aspx.cs"
Inherits="Iframe" %>

<!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 Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Panel ID="Panel1" runat="server">
<asp:TextBox ID="URL" runat="server"
Text="http://" />
<asp:Button ID="Button1" Text="Go"
OnClick="GetURL" runat="server" />
<iframe id="Iframe1" src="<%# TheURL %>"
runat="server" frameborder="0" marginwidth="1"
style="position:
absolute;top:100px;width:800px;height:400px;border:solid 1
px"></iframe>
</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;

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


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

}
public string TheURL = "";

public void GetURL(object Src, EventArgs Args)


{
if (!(URL.Text == "http://"))
{
TheURL = URL.Text;
Page.DataBind();
}
}

P OSTE D BY D OT NE T LOVE R AT 12 :3 8 PM 0 C OM M E N TS

IFrame GoogleMAP and ModalPopup


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

<%@ Register TagPrefix="ajaxToolkit"


Assembly="AjaxControlToolkit"
Namespace="AjaxControlToolkit" %>
<!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 Page</title>

<script type="text/javascript">
function showDialog()
{
var modalPopupBehaviorCtrl = $find('<%=
mpeMap.ClientID %>');
modalPopupBehaviorCtrl.show();
document.getElementById('divMap').innerHTML
= '<iframe runat="server" id="mm" width="600" height="450"
frameborder="0"
scrolling="no" marginheight="0" marginwidth="0"
src="DisplayGoogleMap.aspx?lat=39.86887222271858&long=-
75.35767078399658&desc=just%26a%26sample"><
/iframe><br />';
}
</script>

</head>
<body>
<form id="Form1" runat="server" action="">
<asp:ScriptManager ID="ScriptManager1" runat="server" />
<a id="showModalPopupClientButton" href="#"
runat="server" onclick="showDialog();">Click
Me</a><br />
<br />
<br />
<asp:LinkButton ID="LinkButton1"
runat="server">LinkButton</asp:LinkButton>
<asp:Panel runat="server" ID="Panel1" Style="display:
none; width: 600px; height: 475px;"
CssClass="modalPopup">
<div id="divMap">
</div>
<asp:Button runat="server" ID="cmdClose"
Text="Close" />
</asp:Panel>
<iframe width="600" height="450" frameborder="0"
scrolling="no" marginheight="0"
marginwidth="0"
src="DisplayGoogleMap.aspx?lat=39.86887222271858&long=-
75.35767078399658&desc=just%26a%26sample">
</iframe>
<br />
<ajaxToolkit:ModalPopupExtender ID="mpeMap"
runat="server" TargetControlID="LinkButton1"
PopupControlID="Panel1"
BackgroundCssClass="modalBackground" DropShadow="true"
CancelControlID="cmdClose" OkControlID="cmdClose" />
</form>
</body>
</html>
DisplayGoogleMap.aspx

<%@ Page Language="C#" AutoEventWireup="true"


CodeFile="DisplayGoogleMap.aspx.cs" Inherits="minimap2" %>

<!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 Document</title>

<script
src="http://maps.google.com/maps?file=api&v=2&key=ABQIAAAA6
TRHbwQ
EdJQJYJodaur9XhTJQa0g3IQ9GZqIMmInSLzwtGDKaBQN9ma6JnCY1kf4R6
Q-HCj5397ddA"
type="text/javascript"></script>

<script type="text/javascript">
var map;
var icon0;
var newpoints = new Array();

function addLoadEvent(func) {
var oldonload = window.onload;
if (typeof window.onload != 'function'){
window.onload = func
} else {
window.onload = function() {
oldonload();
func();
}
}
}

addLoadEvent(loadMap);
addLoadEvent(addPoints);

function loadMap()
{
var dLat =
Number(document.getElementById('<%= hdLat.ClientID
%>').value);
var dLong =
Number(document.getElementById('<%= hdLong.ClientID
%>').value);
var sCaption =
document.getElementById('<%= hdCaption.ClientID %>').value;

map = new
GMap2(document.getElementById("map"));
map.addControl(new GLargeMapControl());
map.addControl(new GMapTypeControl());
map.setCenter(new GLatLng( dLat, dLong), 13);
map.setMapType(G_MAP_TYPE);
//G_MAP_TYPE, G_SATELLITE_TYPE, or G_HYBRID_TYPE
icon0 = new GIcon();
icon0.image =
"http://www.google.com/mapfiles/marker.png";
icon0.shadow =
"http://www.google.com/mapfiles/shadow50.png";
icon0.iconSize = new GSize(20, 34);
icon0.shadowSize = new GSize(37, 34);
icon0.iconAnchor = new GPoint(9, 34);
icon0.infoWindowAnchor = new GPoint(9, 2);
icon0.infoShadowAnchor = new GPoint(18, 25);
}

function addPoints()
{

var dLat =
Number(document.getElementById('<%= hdLat.ClientID
%>').value);
var dLong =
Number(document.getElementById('<%= hdLong.ClientID
%>').value);
var sCaption =
document.getElementById('<%= hdCaption.ClientID %>').value;

newpoints[0] = new Array(dLat, dLong, icon0,


'Picture', sCaption);

for(var i = 0; i < newpoints.length; i++) {


var point = new
GPoint(newpoints[i][1],newpoints[i][0]);
var popuphtml = newpoints[i][4] ;
var marker =
createMarker(point,newpoints[i][2],popuphtml);
map.addOverlay(marker);
}
}

function createMarker(point, icon, popuphtml)


{
var popuphtml = "<div id=\"popup\">" +
popuphtml + "<\/div>";
var marker = new GMarker(point, icon);
GEvent.addListener(marker, "click",
function() {
marker.openInfoWindowHtml(popuphtml);
});
return marker;
}
</script>

<style type="text/css">
div#popup
{
background:#EFEFEF;
border:1px solid #999999;
margin:0px;
padding:7px;
width:270px;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<asp:HiddenField runat="server"
Value="39.869053382069" ID="hdLat" />
<asp:HiddenField runat="server"
Value="-75.35773515701294" ID="hdLong" />
<asp:HiddenField runat="server" Value="Test"
ID="hdCaption" />
<div id="map" style="width: 600px; height: 450px">
</div>
</form>
</body>
</html>

P OSTE D BY D OT NE T LOVE R AT 12 :1 8 PM 0 C OM M E N TS

Client Side Validation for CheckBoxes,textbox inside the


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

<!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 Page</title>
</head>

<script type="text/javascript">
function ValidateCheckBox()
{ validateTextBox();
//get target base & child control.
var TargetBaseControl =
document.getElementById('<%=this.GridView1.ClientID%>');
var TargetChildControl = "chkBxSelect";

//get all the control of the type INPUT in the base control.
var Inputs =
TargetBaseControl.getElementsByTagName("input");

for(var n = 0; n < Inputs.length; ++n)


if(Inputs[n].type == 'checkbox' &&
Inputs[n].id.indexOf(TargetChildControl,0) >= 0)
if(Inputs[n].checked) return true;
alert('Select at least one checkbox!');
return false;
}

function validateTextBox()
{
//get target base & child control.
var TargetBaseControl =
document.getElementById('<%=this.GridView1.ClientID%>');
var TargetChildControl1 = "txtInput";

//get all the control of the type INPUT in the base control.
var Inputs =
TargetBaseControl.getElementsByTagName("input");

for(var n = 0; n < Inputs.length; ++n)


if(Inputs[n].type == 'text' &&
Inputs[n].id.indexOf(TargetChildControl1,0) >= 0)
if(Inputs[n].value!="") return true;

alert('Enter some value in textbox!');


return false;
}
</script>

<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="GridView1" runat="server"
AutoGenerateColumns="False">
<Columns>
<asp:BoundField HeaderText="n"
DataField="accountno">
<HeaderStyle HorizontalAlign="Center"
VerticalAlign="Middle" Width="50px" />
<ItemStyle HorizontalAlign="Center"
VerticalAlign="Middle" />
</asp:BoundField>
<asp:TemplateField HeaderText="Select">
<ItemTemplate>
<asp:CheckBox ID="chkBxSelect"
runat="server" />
</ItemTemplate>
<HeaderStyle HorizontalAlign="Center"
VerticalAlign="Middle" />
<ItemStyle HorizontalAlign="Center"
VerticalAlign="Middle" />
</asp:TemplateField>
<asp:TemplateField HeaderText="Name">
<ItemTemplate>
<asp:TextBox ID="txtInput"
runat="server"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:Button ID="btnPost" runat="server" Text="Post"
OnClientClick="javascript:return ValidateCheckBox();"
OnClick="btnPost_Click" />
<asp:Label ID="lblMsg" runat="server"></asp:Label>
</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 GridViewClientSide : System.Web.UI.Page


{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
GridView1.DataSource = c();
GridView1.DataBind();
}
}
public DataSet c()
{
DataSet ds = new DataSet();
DataTable dt = new DataTable("Company");
DataRow dr;
dt.Columns.Add(new DataColumn("accountNo",
typeof(Int32)));
dt.Columns.Add(new DataColumn("CompanyName",
typeof(string)));
dt.Columns.Add(new DataColumn("Address",
typeof(string)));
for (int i = 0; i <= 10; i++)
{
dr = dt.NewRow();
dr[0] = i;
dr[1] = "Company" + i + Environment.NewLine +
"Title" + i;
dr[2] = "Address" + i + Environment.NewLine +
"Title" + i;
dt.Rows.Add(dr);
}
ds.Tables.Add(dt);
return ds;
}
protected void btnPost_Click(object sender, EventArgs e)
{
lblMsg.Text = "Form is posted!";
}

P OSTE D BY D OT NE T LOVE R AT 8 :56 AM 0 C OM M E N TS

F R I D AY, A P R I L 1 8 , 2 0 0 8
How To Convert a DataReader into a DataSet

static DataSet DataReaderToDataSet(IDataReader reader)


{
DataTable table = new DataTable();
int fieldCount = reader.FieldCount;
for (int i = 0; i < fieldCount; i++)
{
table.Columns.Add(reader.GetName(i),
reader.GetFieldType(i));
}
table.BeginLoadData();
object[] values = new object[fieldCount];
while (reader.Read())
{
reader.GetValues(values);
table.LoadDataRow(values, true);
}
table.EndLoadData();
DataSet ds = new DataSet();
ds.Tables.Add(table);
return ds;
}
public static DataSet DataReaderToDataSet2()
{
using (SqlConnection connection = new
SqlConnection(ConfigurationManager.ConnectionStrings["Conne
ctionString"].ConnectionString))
{

string Query = @"SELECT * From addressbook";


SqlCommand command = new SqlCommand(Query,
connection);
command.CommandType = CommandType.Text;
connection.Open();
SqlDataReader reader = command.ExecuteReader();
DataTable myTable = new DataTable("myTable");
myTable.Columns.Add("FirstName", typeof(string));
myTable.Columns.Add("LastName", typeof(string));
myTable.Columns.Add("Email", typeof(string));
while (reader.Read())
{
myTable.Rows.Add(new object[]
{reader["FirstName"].ToString(),
reader["LastName"].ToString(),
reader["Email"].ToString()});

}
myTable.AcceptChanges();
DataSet ds = new DataSet();
ds.Tables.Add(myTable);
ds.AcceptChanges();
return ds;
}
}

public static DataTable DataReaderToDataSet3(IDataReader


reader)
{
DataTable orders = new DataTable("Orders");
orders.Load(reader);

P OSTE D BY D OT NE T LOVE R AT 3 :18 PM 0 C OMM E N TS

How To Create ASP.NET Control From XML using XSLT

<%@ Page Language="C#" AutoEventWireup="true"


CodeFile="XMLControl.aspx.cs"
Inherits="XMLControl" %>

<!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 Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:PlaceHolder ID="survey"
runat="server"></asp:PlaceHolder>
<asp:Label ID="ThankYouLabel" runat="server"
Visible="true" Text="Thank You"></asp:Label>
</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.Xml;
using System.Xml.Xsl;
using System.Xml.XPath;
using System.IO;

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


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

}
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
CreateControl();
}
// called from Page's Init event handler
private void CreateControl()
{
// Load the data source
XPathDocument surveyDoc = new
XPathDocument(Server.MapPath("Control.xml"));

// Load the xslt to do the transformations


XslTransform transform = new XslTransform();
transform.Load(Server.MapPath("Control.xsl"));
// Get the transformed result
StringWriter sw = new StringWriter();
transform.Transform(surveyDoc, null, sw);
string result = sw.ToString();

// remove the namespace attribute


result = result.Replace("xmlns:asp=\"remove\"", "");

// parse the control(s) and add it to the page


Control ctrl = Page.ParseControl(result);
survey.Controls.Add(ctrl);
}

Control.XSL
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:asp="remove">
<xsl:output method="xml" indent="yes" encoding="utf-8"
omit-xml-declaration="yes"></xsl:output>
<xsl:template match="/">
<table>
<xsl:for-each select="//question">
<tr>
<td valign="top">
<xsl:value-of select="@name" />
<xsl:if test="@required = 'yes'">
<asp:RequiredFieldValidator
ErrorMessage="Required
Field" runat="server" ControlToValidate="{@name}" />
</xsl:if>
</td>
<td>
<xsl:if test="@type='text'">
<asp:TextBox id="{@name}"
runat="server" />
</xsl:if>
<xsl:if test="@type='radio'">
<asp:RadioButtonList id="{@name}"
runat="server">
<xsl:for-each select="choice">
<asp:ListItem
Value="{@value}" Text="{@value}">
<xsl:value-of
select="current()"/>
</asp:ListItem>
</xsl:for-each>
</asp:RadioButtonList>
</xsl:if>
<xsl:if test="@type='select'">
<asp:DropDownList id="{@name}"
runat="server">
<xsl:for-each select="choice">
<asp:ListItem
Value="{@value}" Text="{@value}">
<xsl:value-of
select="current()"/>
</asp:ListItem>
</xsl:for-each>
</asp:DropDownList>
</xsl:if>
</td>
</tr>
</xsl:for-each>
</table>
<asp:button id="submit" runat="server" Text="Submit"
/>
</xsl:template>
</xsl:stylesheet>
Control.XML

<survey name="Example Survey">


<question type="text" name="Title" required="yes"/>
<question type="text" name="Industry"/>
<question type="radio" name="Education">
<choice>High school</choice>
<choice>Some college</choice>
<choice>College</choice>
</question>
<question type="select" name="Country">
<choice>India</choice>
<choice>UK</choice>
</question>
</survey>

P OSTE D BY D OT NE T LOVE R AT 12 :5 0 PM 0 C OM M E N TS

How To Add multiple dynamic onload events to body tag


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

<!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 Page</title>
</head>
<body runat="server" id="body">
<form id="form1" runat="server">
<div>
How To Add multiple dynamic onload events to
body tag
</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 MultipleEvent : System.Web.UI.Page


{
protected void Page_Load(object sender, EventArgs e)
{
body.Attributes["onload"] =
"javascript:alert('Onload Event1');";
if (body.Attributes["onload"] != null)
{
body.Attributes["onload"] +=
"javascript:alert('Onload Event2');";
}
else
{
body.Attributes.Add("onload",
"javascript:alert('bye')");
}

}
}

P OSTE D BY D OT NE T LOVE R AT 8 :51 AM 0 C OM M E N TS

T H U R S D AY, A P R I L 1 7 , 2 0 0 8
How to bind RSS feeds to a GridView

<%@ Page Language="C#" AutoEventWireup="true"


CodeFile="ReadRSS.aspx.cs"
Inherits="ReadRSS" %>

<!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 Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="GridView1" runat="server"
AutoGenerateColumns="False">
<Columns>
<asp:TemplateField HeaderText="Title">
<ItemTemplate>
<a href='<%# Eval("link") %>'
target="_blank">
<%# Eval("title") %>
</a>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="description"
HeaderText="Description" />
</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 ReadRSS : System.Web.UI.Page


{
protected void Page_Load(object sender, EventArgs e)
{
BindGrid("http://aspalliance.com/rss.aspx",
GridView1,2);

}
public void BindGrid(string strRss, GridView oGrid, int
iTable)
{
DataSet oDs = new DataSet();
oDs.ReadXml(strRss);
oGrid.DataSource = oDs.Tables[iTable];
oGrid.DataBind();
}

P OSTE D BY D OT NE T LOVE R AT 3 :48 PM 0 C OMM E N TS

How To Add Search Feature To GridView

<%@ Page Language="C#" AutoEventWireup="true"


CodeFile="GridViewAndUpdatePanel.aspx.cs"
Inherits="GridViewAndUpdatePanel" %>

<!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 Page</title>
</head>
<body>
<form id="form1" runat="server">
<!-- You need to add this ScriptManager -->
<asp:ScriptManager ID="scriptMgr" runat="server" />
<div style="height: 190px">
<!-- Only this area is updated on PostBack -->
<asp:UpdatePanel ID="updatePnl" runat="server"
UpdateMode="Conditional">
<ContentTemplate>
<asp:GridView ID="gridViewPersons"
runat="server"
AutoGenerateColumns="False"
CellPadding="4"
ForeColor="#333333" GridLines="None"
Width="460px">
<FooterStyle BackColor="#507CD1" Font-
Bold="True"
ForeColor="White" />
<Columns>
<asp:BoundField DataField="Surname"
HeaderText="Surname" InsertVisible="False" ReadOnly="True">
<HeaderStyle
HorizontalAlign="Left" />
</asp:BoundField>
<asp:BoundField DataField="Name"
HeaderText="Name"
InsertVisible="False" ReadOnly="True">
<HeaderStyle
HorizontalAlign="Left" />
</asp:BoundField>
<asp:BoundField DataField="Street"
HeaderText="Street"
InsertVisible="False" ReadOnly="True">
<HeaderStyle
HorizontalAlign="Left" />
</asp:BoundField>
</Columns>
<RowStyle BackColor="#EFF3FB" />
<EditRowStyle BackColor="#2461BF" />
<SelectedRowStyle BackColor="#D1DDF1"
Font-Bold="True"
ForeColor="#333333" />
<PagerStyle BackColor="#2461BF"
ForeColor="White"
HorizontalAlign="Center" />
<HeaderStyle BackColor="#507CD1" Font-
Bold="True"
ForeColor="White" />
<AlternatingRowStyle BackColor="White"
/>
</asp:GridView>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger
ControlID="lbFilter" />
</Triggers>
</asp:UpdatePanel>
<br />
<asp:UpdateProgress ID="udProgress" runat="server"
DisplayAfter="100" Visible="true"
DynamicLayout="true">
<ProgressTemplate>
<div style="color:Red">Loading.....</div>
</ProgressTemplate>
</asp:UpdateProgress>
</div>
<!-- Update is initiated here, outside the UpdatePanel
-->
<div style="background: url('img/background.png')
repeat-x;
width: 450px; height: 25px;
border: solid 1px #cccccc; padding: 5px; color:
#666666">
Filter Name (first letters):
<asp:TextBox CssClass="MainFont" ID="txtName"
runat="server"></asp:TextBox>
<asp:LinkButton ID="lbFilter" runat="server"
OnClick="lbFilter_Click">Apply filter</asp:LinkButton></div>
<br />
</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.Collections.Generic;

public partial class GridViewAndUpdatePanel :


System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
FillGridView("");
}

private void FillGridView(string filter)


{
System.Threading.Thread.Sleep(1000);
List<Person> persons = Helper.GeneratePersons(filter);
gridViewPersons.DataSource = persons;
gridViewPersons.DataBind();
}

protected void lbFilter_Click(object sender, EventArgs e)


{
FillGridView(txtName.Text);
}
}

public class Person


{
public Person(string surname, string name, string street)
{
_street = street;
_name = name;
_surname = surname;
}

private string _street;


public string Street
{
get { return _street; }
set { _street = value; }
}

private string _name;


public string Name
{
get { return _name; }
set { _name = value; }
}

private string _surname;


public string SurName
{
get { return _surname; }
set { _surname = value; }
}
}
public class Helper
{
public static List<Person> GeneratePersons(string filter)
{
List<Person> persons = new List<Person>();

persons.Add(new Person("Hunter S.", "Thompson",


"Bakerstreet"));
persons.Add(new Person("Chris", "Byron",
"Williamsstreet"));
persons.Add(new Person("Paul", "Stanley",
"Hunterstreet"));
persons.Add(new Person("Charly", "Bukowski",
"Mainstreet"));
persons.Add(new Person("Will", "Burroughs",
"Lurkerstreet"));

if (filter.Trim() == "")
return persons;

List<Person> filteredPersons = new List<Person>();


foreach (Person person in persons)
{
if (person.Name.StartsWith(filter))
filteredPersons.Add(person);

return filteredPersons;

}
}

P OSTE D BY D OT NE T LOVE R AT 2 :09 PM 0 C OMM E N TS

How To Add client side calculation for gridview column


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

<!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></title>

<script type="text/javascript">
function CalcSellPrice2(CurrentPrice, DiscountCtrlID,
CustomerCtrlID)
{
var Discount=
parseFloat(document.getElementById(DiscountCtrlID).value);
var SellPrice=document.getElementById(CustomerCtrlID);
var SellPriceValue = parseFloat(CurrentPrice -
((CurrentPrice*Discount)/100));
//var SellPriceValueRound = Math.round(SellPriceValue,4);
var SellPriceValueRound = SellPriceValue;
SellPrice.innerHTML= SellPriceValueRound ;

</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="GridView1" runat="server"
AutoGenerateColumns="False"
OnRowDataBound="GridView1_RowDataBound">
<Columns>
<asp:TemplateField HeaderText="List Price"
Visible="True">
<ItemTemplate>
<asp:Label ID="lblCurrentListPrice"
runat="server"
Text='<%# Eval("Price") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Discount">
<ItemTemplate>
<asp:TextBox ID="txtDiscountOnItem"
Width="100px"
runat="Server" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Sell Price">
<ItemTemplate>
<asp:Label ID="lblSellPrice"
runat="Server" />
</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 GridViewClientSideCalculation :


System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
GridView1.DataSource = GetData();
GridView1.DataBind();

}
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;
}
protected void GridView1_RowDataBound(object sender,
GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{

Label lblCurrentListPrice =
(Label)e.Row.FindControl("lblCurrentListPrice");
Double CurPr =
Convert.ToDouble(lblCurrentListPrice.Text);
TextBox txtDiscountOnItem =
(TextBox)e.Row.FindControl("txtDiscountOnItem");
Label lblSellPrice =
(Label)e.Row.FindControl("lblSellPrice");
txtDiscountOnItem.Attributes.Add("onchange",
"CalcSellPrice2(" + CurPr + ", '" +
txtDiscountOnItem.ClientID + "','"
+ lblSellPrice.ClientID + "')");

}
}

P OSTE D BY D OT NE T LOVE R AT 12 :5 1 PM 0 C OM M E N TS

Create new gridview row with javascript

<%@ Page Language="C#" AutoEventWireup="true"


CodeFile="GridViewNewRowJavascript.aspx.cs"
Inherits="GridViewNewRowJavascript"
EnableEventValidation="False"%>

<!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 Page</title>

<script language="javascript" type="text/javascript">

function AddNewProfession()
{
var DropDownList
var txtBox
var NewtxtBox
var GridView
var NewDropDownList
var count=document.getElementById('<%=hdValue.ClientID
%>').value;
DropDownList
=document.getElementById("gvProfessions_ctl03_ddlProfession
s");
txtBox
=document.getElementById("gvProfessions_ctl02_txtBox");
GridView =
document.getElementById('<%=gvProfessions.ClientID%>');
NewDropDownList = DropDownList.cloneNode(true);
NewtxtBox=txtBox.cloneNode(true);
NewtxtBox.id = "gvProfessions_ctl05_ddlProfessions";
NewtxtBox.name = "gvProfessions$ctl05$ddlProfessions";
NewDropDownList.id = "gvProfessions_ctl04_ddlProfessions";
NewDropDownList.name = "gvProfessions$ctl04$ddlProfessions";
var newGridViewRow =
GridView.insertRow(GridView.rows.length);
var cellLeft = newGridViewRow.insertCell(0);
var cellRight=newGridViewRow.insertCell(1);
cellRight.appendChild(NewtxtBox);
cellLeft.appendChild(NewDropDownList);
count++;
document.getElementById('<%=hdValue.ClientID
%>').value=count;
return false;

}
</script>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManger1" runat="server">
</asp:ScriptManager>
<asp:UpdatePanel ID="u" runat="server">
<ContentTemplate>
<div>
<a href="#" onclick="return AddNewProfession()">Add
new profession</a>
<asp:GridView ID="gvProfessions"
runat="Server" AutoGenerateColumns="false"
OnRowDataBound="gvProfessions_RowDataBound"
EnableViewState="false">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:DropDownList
ID="ddlProfessions" runat="server">
<asp:ListItem Text="A"
Value="A"></asp:ListItem>
<asp:ListItem Text="B"
Value="B"></asp:ListItem>
<asp:ListItem Text="C"
Value="C">
</asp:ListItem>
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:TextBox ID="txtBox"
runat="server"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:HiddenField ID="hdValue"
runat="server" Value="2" />

<asp:Button ID="Button2" runat="server"


OnClick="Button2_Click" Text="Read GridView Value" />
<asp:Button ID="btnPost" runat="server"
OnClick="btnPost_Click" Text="RecreateGrid" /></div>
<asp:TextBox ID="txtValue"
runat="server"></asp:TextBox>
</ContentTemplate>
</asp:UpdatePanel>
</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 GridViewNewRowJavascript :


System.Web.UI.Page
{
DataTable dtTest = new DataTable();
string strText = string.Empty;
protected void Page_Load(object sender, EventArgs e)
{

gvProfessions.DataSource = CreateDS();
gvProfessions.DataBind();

//Fetch Value From Hidden Field(it's store number


of new row added)
//
int intNewRow = int.Parse(hdValue.Value);

if (intNewRow > 3)
{

ReBind();
}
}
protected void gvProfessions_RowDataBound(object
sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
}

private DataTable CreateDS()


{
DataTable dt = new DataTable("Company");
if (Session["DataList_ParentChild"] == null)
{
DataRow dr;
dt.Columns.Add(new DataColumn("ID",
typeof(Int32)));
for (int i = 1; i < 4; i++)
{
dr = dt.NewRow();
dr[0] = i;
dt.Rows.Add(dr);
}

Session["dsTemp"] = dt;
}
else
{
dt = (DataTable)Session["dsTemp"];
}
return dt;
}
public void ReBind()
{
DataRow dr;
int j = int.Parse(hdValue.Value);
DataTable dtTest = CreateDS() as DataTable;
for (int i = 3; i <= j; i++)
{
dr = dtTest.NewRow();
dr["ID"] = i;
dtTest.Rows.Add(dr);
Session["dsTemp"] = dtTest;
gvProfessions.DataSource = dtTest;
gvProfessions.DataBind();
}
}

protected void Button2_Click(object sender, EventArgs e)


{
foreach (GridViewRow gvRow in gvProfessions.Rows)
{
DropDownList ddl =
gvRow.FindControl("ddlProfessions") as DropDownList;

strText += ddl.SelectedItem.Text;

}
txtValue.Text = strText+",";

}
protected void btnPost_Click(object sender, EventArgs e)
{
//as GridView will disappear if the page does a
PostBack. You would need
//to persist them so that they could be added to
the Grid's data source
//and then re-bind the Grid.So That i have used
AJAX enabled Grid controls

}
}

P OSTE D BY D OT NE T LOVE R AT 12 :2 1 PM 0 C OM M E N TS

W E D N E S D AY, A P R I L 1 6 , 2 0 0 8
How To Read a DataSet object in Javascript

Suppose that you have to read the records of DataTable in the DataSet
that was sent as a response value from an Ajaxed Web Service using
javascript.

<%@ Page Language="C#" %>

<%@ Import Namespace="System.Data" %>

<script runat="server">
[System.Web.Services.WebMethod]

[System.Web.Script.Services.ScriptMethod]
public static System.Data.DataTable MyMethod(int value)
{
return GetDataSet(value);
}

public static System.Data.DataTable GetDataSet(int value)


{

DataTable dt = new DataTable("Author");


DataRow dr;
dt.Columns.Add(new DataColumn("Id", typeof(Int32)));
dt.Columns.Add(new DataColumn("Author",
typeof(string)));
for (int i = 0; i <= 10; i++)
{
dr = dt.NewRow();
dr[0] = i;
dr[1] = "Author" + i.ToString();
dt.Rows.Add(dr);
}
for (int i = 20; i <= 40; i++)
{
dr = dt.NewRow();
dr[0] = i;
dr[1] = "Author" + i.ToString();
dt.Rows.Add(dr);
}

DataView dv = new DataView(dt);


dv.RowFilter = "Id='" + value + "'";

return dv.Table;
}

</script>

<!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 Page</title>

<script language="javascript" type="text/javascript">


function CallMyWebService()
{
WebService.MyMethod(1,OnRequestComplete);
}
function OnRequestComplete(result)
{
var str="";
for(var i = 0; i < result.rows.length; i++)

{
str+=result.rows[i].Author +"<br>";

}
document.getElementById('result').innerHTML=str;
}
</script>

</head>
<body>
<form id="form1" runat="server">
<div>
<asp:ScriptManager ID="scriptManger1" runat="server"
EnablePageMethods="true">
<Services>
<asp:ServiceReference
Path="~/WebService.asmx" />
</Services>
</asp:ScriptManager>
<div id="result">
</div>
<input type="button" onclick="CallMyWebService();"
id="myButton"
value="Call MyWebService" />
</div>
</form>
</body>
</html>
if you tried, you likely received some sort of circular reference
serialization error to take advantage of this, you will need to add the
following to your web.config:

<system.web.extensions>
<scripting>
<webServices>
<jsonSerialization>
<converters>
<add name="DataSetConverter"
type="Microsoft.Web.Preview.Script.Serialization.Converters
.DataSetConverter,
Microsoft.Web.Preview"/>
<add name="DataRowConverter"
type="Microsoft.Web.Preview.Script.Serialization.Converters
.DataRowConverter,
Microsoft.Web.Preview"/>
<add name="DataTableConverter"
type="Microsoft.Web.Preview.Script.Serialization.Converters
.DataTableConverter,
Microsoft.Web.Preview"/>
</converters>
</jsonSerialization>
</webServices>
</scripting>
</system.web.extensions>

P OSTE D BY D OT NE T LOVE R AT 3 :02 PM 0 C OMM E N TS

How To Use XML Script in ASP.net 2.0

<%@ Page Language="C#" %>

<%@ Import Namespace="System.Data" %>


<%@ Import Namespace="System.Web.Services" %>
<!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>Hello XML-script</title>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="TheScriptManager"
runat="server">
<Scripts>
<asp:ScriptReference
Assembly="Microsoft.Web.Preview"
Name="PreviewScript.js" />
</Scripts>
</asp:ScriptManager>

<script type="text/xml-script">
<page>
<components>
<application init="pageInit" />
</components>
</page>
</script>
<script type="text/javascript">
<!--
function pageInit() {
alert("Hello XML Script!");
}
//-->
</script>

</form>
</body>
</html>

P OSTE D BY D OT NE T LOVE R AT 2 :52 PM 0 C OMM E N TS

Is text/xml-script working ?

XML-script has been moved to Preview component. You have to add


reference to Microsoft.Web.Preview.dll and add scriptmanager as
followed:

<asp:ScriptManager ID="TheScriptManager" runat="server">


<Scripts>
<asp:ScriptReference
Assembly="Microsoft.Web.Preview"
Name="PreviewScript.js" />
</Scripts>
</asp:ScriptManager>

P OSTE D BY D OT NE T LOVE R AT 2 :24 PM 0 C OMM E N TS

Passing arrayList to javascript function


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

<!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 Page</title>

<script language="javascript" type="text/javascript">


function Test() {
var listString =
document.getElementById('HiddenField1').value;
var listArray = listString.split('~');

// Now you have an array in javascript of each


value

for(var i = 0; i < listArray.length; i++) {


alert(listArray[i]);
}

}
</script>

</head>
<body>
<form id="form1" runat="server">
<div>
<asp:HiddenField ID="HiddenField1" runat="server"
/>
<input type="button" onclick="Test();"
value="Get Value From ArrayList" />
</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 Arraylistjavascript :


System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
ArrayList list = new ArrayList();
list.Add("test1");
list.Add("test2");
HiddenField1.Value = ArrayListToString(ref list);

}
private string ArrayListToString(ref ArrayList
_ArrayList)
{
int intCount;
string strFinal = "";

for (intCount = 0; intCount <= _ArrayList.Count - 1;


intCount++)
{
if (intCount > 0)
{
strFinal += "~";
}

strFinal += _ArrayList[intCount].ToString();
}

return strFinal;
}

P OSTE D BY D OT NE T LOVE R AT 12 :0 9 PM 0 C OM M E N TS

How To Call a WebService with ASP.Net Ajax

When we will use ASP.Net Ajax on our pages we need to add the element. The
ScriptManager will automatically add the references to the required JavaScript files
that provide

asp.net ajax functionality. So it’s required on every page where we will use the
ASP.Net Ajax features.
When we want to add a reference to our WebService we use the Service child
element of the ScriptManager:

<%@ Page Language="C#" AutoEventWireup="true"


CodeFile="CallWebService.aspx.cs"
Inherits="CallWebService" %>
<!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 Page</title>

<script language="javascript" type="text/javascript">


function CallMyWebService()
{
WebService.MyMethod("ASP dot net code book",
OnRequestComplete);
}
function OnRequestComplete(result)
{
alert(result);
}
</script>

</head>
<body>
<form id="form1" runat="server">
<div>
<asp:ScriptManager ID="scriptManger1"
runat="server">
<Services>
<asp:ServiceReference
Path="~/WebService.asmx" />
</Services>
</asp:ScriptManager>
<input type="button" onclick="CallMyWebService();"
id="myButton" value="Call MyWebService" />
</div>
</form>
</body>
</html>

using System;
using System.Web;
using System.Collections;
using System.Web.Services;
using System.Web.Services.Protocols;

/// <summary>
/// Summary description for WebService
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo =
WsiProfiles.BasicProfile1_1)]
[System.Web.Script.Services.ScriptService]
public class WebService : System.Web.Services.WebService
{

public WebService()
{

//Uncomment the following line if using designed


components
//InitializeComponent();
}

[System.Web.Services.WebMethod]
[System.Web.Script.Services.ScriptMethod]
public string MyMethod(string value)
{
return value;
}

P OSTE D BY D OT NE T LOVE R AT 11 :3 2 AM 0 C OMM E N TS


When you use the UpdatePanel control you probably also want to display some kind
of progress bar to the user so they can see when the async. postback starts and
when it’s done, at least something that indicate that some work are being done and
they need to wait until it’s done. This can be done by using the UpdateProgress
control shipped with ASP.Net Ajax 1.0 Extension. If you use the UpdatePanel control
and specify an AsyncPostBackTrigger and also associate the UpdateProgress to an
UpdaetPanel, the UpdateProgress control will not be displayed.Below is the solution

<%@ Page Language="C#" AutoEventWireup="true"


CodeFile="PleaseWait.aspx.cs" Inherits="GridViewasInsert" %>

<!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 Page</title>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="s" runat="server">
</asp:ScriptManager>
<div>
<asp:Button ID="Button1" runat="server" Text="AA"
OnClick="Button1_Click" />
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
gfdgdg
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger
ControlID="Button1" EventName="Click" />
</Triggers>
</asp:UpdatePanel>
<asp:UpdateProgress
AssociatedUpdatePanelID="UpdatePanel1" ID="UpdateProgress1"
runat="server">
<ProgressTemplate>
Please wait, update in progress
</ProgressTemplate>
</asp:UpdateProgress>
</div>
</form>

<script language="javascript" type="text/javascript">


var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_initializeRequest(InitializeRequest);
prm.add_endRequest(EndRequest);
var postBackElement;
function InitializeRequest(sender, args)
{
if (prm.get_isInAsyncPostBack())
args.set_cancel(true);
postBackElement = args.get_postBackElement();
if (postBackElement.id == 'Button1')

$get('UpdateProgress1').style.display = 'block';

}
function EndRequest(sender, args)
{
if (postBackElement.id == 'Button1')
$get('UpdateProgress1').style.display = 'none';
}
</script>

</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 GridViewasInsert : System.Web.UI.Page


{
protected void Page_Load(object sender, EventArgs e)
{
//Replace This when using on live server
System.Threading.Thread.Sleep(3000);

}
protected void Button1_Click(object sender, EventArgs e)
{
Response.Redirect("AnotherPage.aspx");
}
}

P OSTE D BY D OT NE T LOVE R AT 11 :0 7 AM 0 C OMM E N TS

How To embedded resource file(like-flash,javascript....)


in Assembly

..
.
.
.

[assembly: WebResource("FlashPlayer.swfobject.js",
"text/javascript")]

[assembly: WebResource("FlashPlayer.mediaplayer.swf",
"application/x-shockwave-flash")]

private string CreateAttributes()


{

flashUrl =
Page.ClientScript.GetWebResourceUrl(this.GetType(),
"FlashPlayer.mediaplayer.swf");
StringBuilder sb = new StringBuilder();

sb.Append("<script language=\"javascript\">");
sb.Append("var s1 =new SWFObject(");

sb.Append("'" +flashUrl +"'" + ",");

...
.
.
.
.
.

protected override void OnPreRender(EventArgs e)


{
base.OnPreRender(e);

if
(!Page.ClientScript.IsClientScriptBlockRegistered(GetType()
, "FlashPlayer"))
{
Page.ClientScript.RegisterClientScriptResource(G
etType(),
"FlashPlayer.swfobject.js");
Page.ClientScript.RegisterStartupScript(this.Get
Type(),
"SWFObject", CreateAttributes());
}
}

P OSTE D BY D OT NE T LOVE R AT 9 :19 AM 0 C OM M E N TS

T U E S D AY, A P R I L 1 5 , 2 0 0 8
GridView with DataTable as source with paging and
sorting

<%@ Page Language="C#" AutoEventWireup="true"


CodeFile="GridViewSortingPaging.aspx.cs"
Inherits="GridViewClientSideSum" %>

<!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 Page</title>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="SM1" runat="server">
</asp:ScriptManager>
<div>
<asp:GridView ID="gv" runat="server"
OnPageIndexChanging="gv_PageIndexChanging"
OnSorting="gv_Sorting"
AllowSorting="true" AllowPaging="True" />
</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 GridViewClientSideSum :


System.Web.UI.Page
{

protected void Page_Load(object sender, EventArgs e)


{
DataTable dataTable = new DataTable();

// fill datatable with data


gv.DataSource = GetSortedData(dataTable,
gvSortExpression, gvSortDirection);
gv.DataBind();

}
public String gvSortDirection
{
get { return ViewState["SortDirection"] as
String ?? "ASC"; }
set { ViewState["SortDirection"] = value; }
}
public String gvSortExpression
{
get { return ViewState["SortExpression"] as
String ?? ""; }
set { ViewState["SortExpression"] = value; }
}

protected void gv_PageIndexChanging(object sender,


GridViewPageEventArgs e)
{
GridView gv = (GridView)sender;
DataView dv = gv.DataSource as DataView;
DataTable dataTable = dv.Table;

gv.DataSource = GetSortedData(dataTable,
gvSortExpression, gvSortDirection);
gv.PageIndex = e.NewPageIndex;
gv.DataBind();
}
protected void gv_Sorting(object sender,
GridViewSortEventArgs e)
{
GridView gv = (GridView)sender;
DataView dv = gv.DataSource as DataView;
DataTable dataTable = dv.Table;
String sortdir = "";
if (e.SortExpression != "" & e.SortExpression !=
null)
{
if (gvSortExpression == e.SortExpression)
gvSortDirection = GetSortDirection();
else
gvSortDirection = "ASC";
gvSortExpression = e.SortExpression;
gv.EditIndex = -1;
}
gv.DataSource = GetSortedData(dataTable,
e.SortExpression, gvSortDirection);
gv.DataBind();
}
private String GetSortDirection()
{
String newSortDirection = String.Empty;
switch (gvSortDirection)
{
case "DESC":
newSortDirection = "ASC";
break;
case "ASC":
newSortDirection = "DESC";
break;
}
return newSortDirection;
}
private DataView GetSortedData(DataTable dataTable,
String SortExpression, String SortDirection)
{
dataTable = GetDataSet();
if (dataTable != null)
{
DataView dataView = new DataView(dataTable);

if (SortExpression != "" && SortExpression !=


null)
dataView.Sort = SortExpression + " " +
SortDirection;

// Add filter - You may add filter here


return dataView;
}
return null;
}
protected void gvUsers_RowEditing(object sender,
GridViewEditEventArgs e)
{
GridView gv = (GridView)sender;
DataView dv = gv.DataSource as DataView;
DataTable dataTable = dv.Table;
gv.DataSource = GetSortedData(dataTable,
gvSortExpression, gvSortDirection);
gv.EditIndex = e.NewEditIndex;
gv.DataBind();
}
public DataTable GetDataSet()
{

DataTable dt = new DataTable("Company");


DataRow dr;
dt.Columns.Add(new DataColumn("accountNo",
typeof(Int32)));
dt.Columns.Add(new DataColumn("CompanyName",
typeof(string)));
dt.Columns.Add(new DataColumn("Address",
typeof(Int32)));
for (int i = 0; i <= 10; i++)
{
dr = dt.NewRow();
dr[0] = i;
dr[1] = "Company" + i + Environment.NewLine +
"Title" + i;
dr[2] = i;
dt.Rows.Add(dr);
}

return dt;
}
}

P OSTE D BY D OT NE T LOVE R AT 3 :26 PM 0 C OMM E N TS

How To Use Menu and Multiview Control


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

<!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 Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<table>
<tr>
<td style="background-color: Fuchsia">
<asp:Menu ID="Menu1" runat="server"
Orientation="vertical"
OnMenuItemClick="Menu1_MenuItemClick">
<Items>
<asp:MenuItem
Text="Add"></asp:MenuItem>
<asp:MenuItem
Text="Delete"></asp:MenuItem>
<asp:MenuItem
Text="Search"></asp:MenuItem>
</Items>
</asp:Menu>
</td>
<td>
<asp:MultiView ID="MultiView1"
runat="server" ActiveViewIndex="0">
<asp:View ID="View1"
runat="server">
<table>
<tr>
<td>
<asp:TextBox
ID="TextBox1" runat="server">Add</asp:TextBox>
</td>
</tr>
<tr>
<td>
<asp:TextBox
ID="TextBox2" runat="server"></asp:TextBox></td>
</tr>
<tr>
<td>
<asp:TextBox
ID="TextBox3" runat="server"></asp:TextBox>
</td>
</tr>
</table>
</asp:View>
<asp:View ID="View2"
runat="server">
<table>
<tr>
<td>
<asp:TextBox
ID="TextBox4" runat="server">Delete</asp:TextBox>
</td>
</tr>
<tr>
<td>
<asp:TextBox
ID="TextBox5" runat="server"></asp:TextBox></td>
</tr>
<tr>
<td>
<asp:TextBox
ID="TextBox6" runat="server"></asp:TextBox>
</td>
</tr>
</table>
</asp:View>
<asp:View ID="View3"
runat="server">
<table>
<tr>
<td>
<asp:TextBox
ID="TextBox7" runat="server">Search</asp:TextBox>
</td>
</tr>
<tr>
<td>
<asp:TextBox
ID="TextBox8" runat="server"></asp:TextBox></td>
</tr>
<tr>
<td>
<asp:TextBox
ID="TextBox9" runat="server"></asp:TextBox>
</td>
</tr>
</table>
</asp:View>
</asp:MultiView>
</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 FormViewTest : System.Web.UI.Page


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

}
protected void Menu1_MenuItemClick(object sender,
MenuEventArgs e)
{
switch (e.Item.Text)
{

case "Add":

MultiView1.ActiveViewIndex = 0;
break;
case "Delete":
MultiView1.ActiveViewIndex = 1;
break;
case "Search":
MultiView1.ActiveViewIndex = 2;
break;

}
}

P OSTE D BY D OT NE T LOVE R AT 2 :04 PM 0 C OMM E N TS

How to read XML file using javascript

Supoose you have the follwing XML file . If I want to retrieve game1
moves , how would I do it using the the simplest way in javascript ?

<?xml version="1.0" encoding="utf-8" ?>


<playMoves>
<game id="game1" >
<move>
<pieceType>black</pieceType>
<pieceName>pawn</pieceName>
<moveFrom>82</moveFrom>
<moveTo>84</moveTo>
</move>
<move>
<pieceType>white</pieceType>
<pieceName>pawn</pieceName>
<moveFrom>87</moveFrom>
<moveTo>85</moveTo>
</move>
</game>
<game id = "game2" >
<move>
<pieceType>white</pieceType>
<pieceName>pawn</pieceName>
<moveFrom>87</moveFrom>
<moveTo>85</moveTo>
</move>
<move>
<pieceType>black</pieceType>
<pieceName>pawn</pieceName>
<moveFrom>82</moveFrom>
<moveTo>84</moveTo>
</move>
</game>
</playMoves>

<%@ Page Language="C#" AutoEventWireup="true"


CodeFile="ReadXMLfile.aspx.cs"
Inherits="ReadXMLfile" %>

<!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 Page</title>
<script type="text/javascript">

// predeclare to prevent strict js error.


var xmlDoc;

// For IE based browsers:


if (window.ActiveXObject) {
xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
}

// For Mozilla based (standards compliant) browsers:


else if (document.implementation &&
document.implementation.createDocument) {
xmlDoc =
document.implementation.createDocument("","doc",null);
}

// Turn off asynchronus download.


// In other words, load the entire file before trying to do
anything with it.
xmlDoc.async=false;

xmlDoc.load("Java.xml");

// Run onload of body.


function ProcessXML()
{
var game = xmlDoc.getElementsByTagName("game")[0]; //
First game.
var moves = game.getElementsByTagName("move"); // All
moves in game.

var results = '';

for (var i=0; moves.length > i; i++)


{
var pieceType =
moves[i].getElementsByTagName("pieceType");
var pieceName =
moves[i].getElementsByTagName("pieceName");
results += i+1 + '. ' +
pieceType[0].firstChild.nodeValue +
' moved a ' +
pieceName[0].firstChild.nodeValue + "\n\r";
}

document.getElementById("displayresults").firstChild.n
odeValue = results;
}

</script>
</head>
<body onload="ProcessXML();">
<form id="form1" runat="server">
<div id="displayresults">

</div>
</form>
</body>
</html>

P OSTE D BY D OT NE T LOVE R AT 11 :2 3 AM 0 C OMM E N TS

T H U R S D AY, A P R I L 1 0 , 2 0 0 8
How To Create Database Driven Menu in ASP.NET (C#)
This Post will show you how to binding a Menu Control to SQL Server
database using C#. By this sample, you can create a database driven
menu in ASP.Net.

<%@ Page Language="C#" AutoEventWireup="true"


CodeFile="DynamiCMenu.aspx.cs" Inherits="DynamiCMenu" %>

<!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 Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Menu ID="Menu1" Orientation="Horizontal"
runat="Server">
<StaticMenuStyle
BackColor="#eeeeee"
BorderStyle="solid"
BorderColor="Black"
BorderWidth="1" />
<DynamicMenuStyle
BackColor="#eeeeee"
BorderStyle="solid"
BorderColor="Black"
BorderWidth="1"/>
</asp:Menu>
</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 DynamiCMenu : System.Web.UI.Page


{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
PopulateMenu();

}
public void PopulateMenu()
{
DataSet dst = CreateDS();
foreach (DataRow masterRow in
dst.Tables["Company"].Rows)
{
MenuItem masterItem = new
MenuItem((string)masterRow["CompanyName"]);
Menu1.Items.Add(masterItem);
foreach (DataRow childRow in
masterRow.GetChildRows("ParentChild"))
{
MenuItem childItem = new
MenuItem((string)childRow["Name"]);
masterItem.ChildItems.Add(childItem);
}
}
}
private DataSet CreateDS()
{
DataSet ds;
if (Session["DataList_ParentChild"] == null)
{
ds = new DataSet();
DataTable dt = new DataTable("Company");
DataRow dr;
dt.Columns.Add(new DataColumn("ID",
typeof(Int32)));
dt.Columns.Add(new DataColumn("CompanyName",
typeof(string)));
dt.Columns.Add(new DataColumn("Address",
typeof(string)));
dt.Columns.Add(new DataColumn("Name",
typeof(string)));
dt.Columns.Add(new DataColumn("Dept",
typeof(string)));
for (int i = 1; i < 10; i++)
{
dr = dt.NewRow();
dr[0] = i;
dr[1] = "Company " + i;
dr[2] = "Address " + i;
dr[3] = "Manager name";
dr[4] = "Adminstration";
dt.Rows.Add(dr);
}
ds.Tables.Add(dt);
DataColumn[] Parent_PKColumns = new
DataColumn[1];
Parent_PKColumns[0] = dt.Columns["ID"];
dt.PrimaryKey = Parent_PKColumns;

dt = new DataTable("Employees");
dt.Columns.Add(new DataColumn("ID",
typeof(Int32)));
dt.Columns.Add(new DataColumn("CompanyID",
typeof(Int32)));
dt.Columns.Add(new DataColumn("Name",
typeof(string)));
dt.Columns.Add(new DataColumn("Dept",
typeof(string)));
for (int i = 1; i < 10; i++)
{
int imax = 0;
if (i % 2 == 0) imax = 5;
else imax = 4;
for (int y = 2; y < imax; y++) //3
emplyees for each company
{
dr = dt.NewRow();
dr[0] = y + i * 5;
dr[1] = i;
dr[2] = "Employee # " + dr[0];
dr[3] = "Dept # " + (y + i);
dt.Rows.Add(dr);
}
}
DataColumn[] Child_PKColumns = new
DataColumn[1];
Child_PKColumns[0] = dt.Columns["ID"];
dt.PrimaryKey = Child_PKColumns;
ds.Tables.Add(dt);
DataColumn[] Child_FKColumns = new
DataColumn[1];
Child_FKColumns[0] = dt.Columns["CompanyID"];

ds.Relations.Add("ParentChild",
Parent_PKColumns, Child_FKColumns);
Session["DataList_ParentChild"] = ds;
}
else
{
ds = (DataSet)Session["DataList_ParentChild"];
}
return ds;

}
}

P OSTE D BY D OT NE T LOVE R AT 5 :42 PM 0 C OMM E N TS

How To -Cross page postbacks in ASP.NET 2.0

ASP.NET 2.0 introduces the ability to have an ASPX page postback to a


different ASPX page with cross page postbacks. This was done all the
time in ASP but wasn't supported in ASP.NET 1.x. This wasn't directly
supported because on the server you need the same page to be
recreated upon postback so the same controls could be repopulated
with the post data. Since the model is to work at a higher level with
server side controls and their properties, posting back to a different
page would force you to access Request.Form to fetch the data a user
had entered, which is a lower level than the control model wants.

So, in v2.0 they came up with a way to support cross page postbacks.
This is enabled by a button on the first page setting PostBackUrl
property to the page that will handle the postback. Once in the second
page you can access the controls from the previous page by accessing
the Page.PreviousPage property. Here's a sample
CrossPagePostBackSource.aspx

<%@ Page Language="C#" AutoEventWireup="true"


CodeFile="CrossPagePostBackSource.aspx.cs"
Inherits="CrossPagePostBackSource" %>

<!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 Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:TextBox runat="server"
ID="_tb1"></asp:TextBox>
+
<asp:TextBox runat="server"
ID="_tb2"></asp:TextBox>
*
<asp:TextBox runat="server"
ID="_tb3"></asp:TextBox>
<asp:Button runat="server" ID="_button"
PostBackUrl="~/TargetPage.aspx" Text=" = " />
</div>
</form>
</body>
</html>

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

public partial class CrossPagePostBackSource :


System.Web.UI.Page
{
private int sum;
protected void Page_Load(object sender, EventArgs e)
{

}
public int Sum
{
get
{
return ((Int32.Parse(_tb1.Text) +
Int32.Parse(_tb2.Text)) * Int32.Parse(_tb3.Text));
}
}
}

TargetPage.aspx

<%@ Page Language="C#" AutoEventWireup="true"


CodeFile="TargetPage.aspx.cs" Inherits="TargetPage" %>

<%@ PreviousPageType
VirtualPath="~/CrossPagePostBackSource.aspx" %>
<!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 Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
Answer is:
<asp:Label runat="server"
ID="_result"></asp:Label>
</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 TargetPage : System.Web.UI.Page


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

_result.Text = PreviousPage.Sum.ToString();

}
}

P OSTE D BY D OT NE T LOVE R AT 8 :57 AM 0 C OM M E N TS

Use ICallbackEventHandler in Asp.Net 2.0

Steps to Implement ICallbackEventHanler:

1. First define string variable in Common section of your code behind


(.cs) file.

string _CallBackString;
2. Inherit ICallbackEventHandler in your page.

public partial class IcallBack : System.Web.UI.Page,


ICallbackEventHandler

3. Now, write this code in your Page_Load() Event

protected void Page_Load(object sender, EventArgs e)


{
ClientScriptManager cs = Page.ClientScript;
string cbRef = cs.GetCallbackEventReference(this,
"arg", "ShowPop", "context");
string cbScript = "function CallPopBack(arg,
context){" + cbRef + ";}";
cs.RegisterClientScriptBlock(this.GetType(),
"CallPopBack", cbScript, true);

4. Now, Write some javascript code, in your design section of your


page.

<script type="text/javascript">
function GetPop()
{
var justExample = 'Hi..All..';

CallPopBack(justExample)
}
function ShowPop(result, context)
{

var strResult = new String();


strResult = result;

document.getElementById("txt").value=result;

}
</script>

5.Now, In your code behind (.cs) file, write code for your EventHandle
Method.

public string GetCallbackResult()


{
return _CallBackString;
}

public void RaiseCallbackEvent(string eventArgument)


{
_CallBackString = eventArgument + " " +
DateTime.Now.ToShortTimeString();
}

<%@ Page Language="C#" AutoEventWireup="true"


CodeFile="IcallBack.aspx.cs" Inherits="IcallBack" %>

<!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 Page</title>

<script type="text/javascript">
function GetPop()
{
var justExample = 'Hi..All..';

CallPopBack(justExample)
}
function ShowPop(result, context)
{

var strResult = new String();


strResult = result;

document.getElementById("txt").value=result;

</script>

</head>
<body>
<form id="form1" runat="server">
<div>
<input type="button" value="Text ICallBack"
onclick="return GetPop()"/>
<input type="text" name="txt" id="txt"/>

</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 IcallBack : System.Web.UI.Page,


ICallbackEventHandler
{
string _CallBackString;
protected void Page_Load(object sender, EventArgs e)
{
ClientScriptManager cs = Page.ClientScript;
string cbRef = cs.GetCallbackEventReference(this,
"arg", "ShowPop", "context");
string cbScript = "function CallPopBack(arg,
context){" + cbRef + ";}";
cs.RegisterClientScriptBlock(this.GetType(),
"CallPopBack", cbScript, true);

}
public string GetCallbackResult()
{
return _CallBackString;
}

public void RaiseCallbackEvent(string eventArgument)


{
_CallBackString = eventArgument + " " +
DateTime.Now.ToShortTimeString();
}
}

P OSTE D BY D OT NE T LOVE R AT 7 :05 AM 0 C OM M E N TS

W E D N E S D AY, A P R I L 9 , 2 0 0 8
Modal Popup from Repeater

<%@ Page Language="C#" AutoEventWireup="true"


CodeFile="RepeaterModalPopup.aspx.cs"
Inherits="RepeaterModalPopup" %>

<!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 Page</title>

<script type="text/jscript">
function ShowModalWindow(Id)
{
window.showModalDialog("Details.aspx?accountNo="+ Id +"","",
"status:no;dialogWidth:800px;
dialogHeight:570px;help:no;center:yes;resizable:no;scroll:y
es;status:no;");
}

</script>

</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Repeater ID="Repeater1" runat="server">
<HeaderTemplate>
<table border="1" width="100%">
<tr>
<th>
COL1</th>
<th>
COL2</th>
<th>
COL3</th>
<th>
COL4</th>
</tr>
</HeaderTemplate>
<ItemTemplate>
<tr>
<td>
<a
href='Details.aspx?FrromTest=true
&accountno=<%#
DataBinder.Eval(Container.DataItem,"accountNo")
%>&TypeDesc=<%#
DataBinder.Eval(Container.DataItem,"CompanyName") %>'>
<%#
DataBinder.Eval(Container.DataItem, "CompanyName")%>
</a>
</td>
<td>
<a href='#'
onclick="ShowModalWindow('<%#
DataBinder.Eval(Container.DataItem,"accountNo") %>');">
<%#
DataBinder.Eval(Container.DataItem, "CompanyName")%>
</a>
</td>
<td>
<%#
DataBinder.Eval(Container.DataItem,"Address") %>
</td>
<td>
This is a free column</td>
</tr>
</ItemTemplate>
<FooterTemplate>
</table>
</FooterTemplate>
</asp:Repeater>
</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 RepeaterModalPopup : System.Web.UI.Page


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

Repeater1.DataSource = GetDataSet();
Repeater1.DataBind();
}
public DataSet GetDataSet()
{
DataSet ds = new DataSet();
DataTable dt = new DataTable("Company");
DataRow dr;
dt.Columns.Add(new DataColumn("accountNo",
typeof(Int32)));
dt.Columns.Add(new DataColumn("CompanyName",
typeof(string)));
dt.Columns.Add(new DataColumn("Address",
typeof(string)));
for (int i = 0; i <= 10; i++)
{
dr = dt.NewRow();
dr[0] = i;
dr[1] = "Company" + i + Environment.NewLine +
"Title" + i;
dr[2] = "Address" + i + Environment.NewLine +
"Title" + i;
dt.Rows.Add(dr);
}
ds.Tables.Add(dt);
return ds;
}
}

Details.aspx

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


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

DataView dv = new DataView(GetDataSet().Tables[0]);


dv.RowFilter = "accountno='" +
Request.QueryString["accountno"].ToString() + "'";
GridView1.DataSource = dv;
GridView1.DataBind();

}
}
P OSTE D BY D OT NE T LOVE R AT 3 :05 PM 0 C OMM E N TS

Displaying vertical rows in a GridView

<%@ Page Language="C#" AutoEventWireup="true"


CodeFile="FlipGridView.aspx.cs" Inherits="XmlPostData" %>

<!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 Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="GridView1" runat="server"
ShowHeader="false" AllowSorting="true">
</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;
using System.Net;
using System.Text;
using System.IO;

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


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

GridView1.DataSource = FlipDataSet(c());
GridView1.DataBind();

public DataSet c()


{
DataSet ds = new DataSet();
DataTable dt = new DataTable("Company");
DataRow dr;
dt.Columns.Add(new DataColumn("accountNo",
typeof(Int32)));
dt.Columns.Add(new DataColumn("CompanyName",
typeof(string)));
dt.Columns.Add(new DataColumn("Address",
typeof(string)));
for (int i = 0; i <= 10; i++)
{
dr = dt.NewRow();
dr[0] = i;
dr[1] = "Company" + i + Environment.NewLine +
"Title" + i;
dr[2] = "Address" + i + Environment.NewLine +
"Title" + i;
dt.Rows.Add(dr);
}
ds.Tables.Add(dt);
return ds;
}
public DataSet FlipDataSet(DataSet my_DataSet)
{
DataSet ds = new DataSet();
foreach (DataTable dt in my_DataSet.Tables)
{
DataTable table = new DataTable();
for (int i = 0; i <= dt.Rows.Count; i++)
{
table.Columns.Add(Convert.ToString(i));
}
DataRow r = null;
for (int k = 0; k < dt.Columns.Count; k++)
{
r = table.NewRow();
r[0] = dt.Columns[k].ToString();
for (int j = 1; j <= dt.Rows.Count; j++)
r[j] = dt.Rows[j - 1][k];
table.Rows.Add(r);
}
ds.Tables.Add(table);
}

return ds;
}
}

P OSTE D BY D OT NE T LOVE R AT 2 :44 PM 0 C OMM E N TS

How To populating DropDownList control from XML data


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

<!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 Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:DropDownList ID="ddlXml" runat="server">
</asp:DropDownList>
</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.Xml;

public partial class PopulateDropDwonListWithXML :


System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{

XmlDocument doc = new XmlDocument();


doc.Load(Server.MapPath("DropDown.xml"));
XmlNodeList nodeList =
doc.SelectNodes("//DESTINATIONS/DESTINATION");

foreach (XmlNode node in nodeList)


{
ddlXml.Items.Add(new
ListItem(node.SelectSingleNode("NAME").InnerText));
}
}

DropDown.XML
<?xml version="1.0" encoding="utf-8" ?>

<GATEWAYS>
<GATEWAY>
<CODE>YXX</CODE>
<NAME>Abbotsford</NAME>
<DESTINATIONS>
<DESTINATION>
<CODE>PVR</CODE>
<NAME>Puerto Vallarta</NAME>
</DESTINATION>
</DESTINATIONS>
</GATEWAY>

<GATEWAY>
<CODE>YKF</CODE>
<NAME>Kitchener</NAME>
<DESTINATIONS>
<DESTINATION>
<CODE>CUN</CODE>
<NAME>Cancun</NAME>
</DESTINATION>
<DESTINATION>
<CODE>X24</CODE>
<NAME>Cancun (Mayan Riviera)</NAME>
</DESTINATION>
<DESTINATION>
<CODE>POP</CODE>
<NAME>Puerto Plata</NAME>
</DESTINATION>
<DESTINATION>
<CODE>PUJ</CODE>
<NAME>Punta Cana</NAME>
</DESTINATION>
</DESTINATIONS>
</GATEWAY>
<GATEWAY>
<CODE>YQL</CODE>
<NAME>Lethbridge</NAME>
<DESTINATIONS>
<DESTINATION>
<CODE>PVR</CODE>
<NAME>Puerto Vallarta</NAME>
</DESTINATION>
</DESTINATIONS>
</GATEWAY>
</GATEWAYS>

P OSTE D BY D OT NE T LOVE R AT 7 :49 AM 0 C OM M E N TS

T U E S D AY, A P R I L 8 , 2 0 0 8
How to bind selected node values in Gridview
<%@ Page Language="C#" AutoEventWireup="true"
CodeFile="ConditionalBinding.aspx.cs"
Inherits="ConditionalBinding" %>

<!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 Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="GridView1" runat="server">
</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;
using System.Xml;

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


{
protected void Page_Load(object sender, EventArgs e)
{
XmlDocument doc = new XmlDocument();
doc.Load(Server.MapPath("Class.xml"));

XmlNodeList lst =
doc.SelectNodes("//student[class='class2']");
IList datasource = new ArrayList();

foreach (XmlNode stu in lst)


{
Stu s = new Stu();
s.Name =
stu.SelectSingleNode("name").InnerText;
s.Stuclass =
stu.SelectSingleNode("class").InnerText;
datasource.Add(s);
}

this.GridView1.DataSource = datasource;
GridView1.DataBind();

}
public class Stu
{
private string name;

public string Name


{
get { return name; }
set { name = value; }
}
private string stuclass;

public string Stuclass


{
get { return stuclass; }
set { stuclass = value; }
}

}
}

<?xml version="1.0" encoding="utf-8" ?>


<root>
<student>
<class>class1</class>
<name>ss</name>
</student>
<student>
<class>class1</class>
<name>ss</name>
</student>
<student>
<class>class1</class>
<name>ss</name>
</student>
<student>
<class>class1</class>
<name>ss</name>
</student>
<student>
<class>class2</class>
<name>ss</name>
</student>
</root>

P OSTE D BY D OT NE T LOVE R AT 4 :49 PM 0 C OMM E N TS

How To Load Web user control inside a GridView


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

<%@ Register Src="Data.ascx" TagName="Data" TagPrefix="uc1"


%>
<!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 Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="Gridview2" runat="server"
Width="600px"
AutoGenerateColumns="false" DataKeyNames="EmployeeId">
<Columns>
<asp:BoundField DataField="EmployeeId"
HeaderText="Id" />
<asp:TemplateField>
<ItemTemplate>
<uc1:Data ID="Data1"
runat="server"
EmployeeId='<%#Eval("EmployeeId")%>'></uc1:Data>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
</form>
</body>
</html>
CodeBehind

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 LoadUserControlDynamicallyinRepeater :


System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{

BindGrid();

}
public DataTable GetCustomMadeDataTable()
{
//Create a new DataTable object
System.Data.DataTable objDataTable = new
System.Data.DataTable();
//Create three columns with string as their type
objDataTable.Columns.Add("EmployeeId", typeof(int));
objDataTable.Columns.Add("Department",
typeof(string));
//Adding some data in the rows of this DataTable
DataRow dr;
for (int i = 1; i <= 10; i++)
{

dr = objDataTable.NewRow();
dr[0] = i;
dr[1] = "Department" + i.ToString();

objDataTable.Rows.Add(dr);

}
DataColumn[] dcPk = new DataColumn[1];
dcPk[0] = objDataTable.Columns["EmployeeId"];
objDataTable.PrimaryKey = dcPk;
Session["strTemp"] = objDataTable;
return objDataTable;
}

public void BindGrid()


{
if (Session["strTemp"] != null)
{
Gridview2.DataSource = Session["strTemp"] as
DataTable;
Gridview2.DataBind();

}
else
{
Gridview2.DataSource = GetCustomMadeDataTable();
Gridview2.DataBind();
}

}
}

WebUserControl

<%@ Control Language="C#" AutoEventWireup="true"


CodeFile="Data.ascx.cs" Inherits="Data" %>
<asp:GridView ID="GridView1" runat="server"
ShowHeader="False" Width="600px"
AutoGenerateColumns="False">
<Columns>
<asp:BoundField DataField="Address" />
<asp:BoundField DataField="City" />
</Columns>
</asp:GridView>

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 Data : System.Web.UI.UserControl


{
protected void Page_Load(object sender, EventArgs e)
{
BindGrid();

private int _employeeid;

public int EmployeeId


{

get
{
return _employeeid;
}
set
{
_employeeid = value;
}

public DataView GetCustomMadeDataTable(int id)


{

//Create a new DataTable object


System.Data.DataTable objDataTable = new
System.Data.DataTable();
//Create three columns with string as their type
objDataTable.Columns.Add("Id", typeof(int));
objDataTable.Columns.Add("Address", typeof(string));
objDataTable.Columns.Add("City", typeof(string));
objDataTable.Columns.Add("Postalcode",
typeof(string));
//Adding some data in the rows of this DataTable
DataRow dr;
int intIndex = 900;
for (int i = 1; i <= 200; i++)
{

dr = objDataTable.NewRow();
dr[0] = i;
dr[1] = "Address" + i.ToString();
dr[2] = "City" + i.ToString();
dr[3] = "Postalcode" + intIndex.ToString();
objDataTable.Rows.Add(dr);
intIndex++;

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

dr = objDataTable.NewRow();
dr[0] = 1;
dr[1] = "Address" + i.ToString();
dr[2] = "City" + i.ToString();
dr[3] = "Postalcode" + intIndex.ToString();
objDataTable.Rows.Add(dr);
intIndex++;

DataView dv = new DataView(objDataTable);


dv.RowFilter = "Id=" + EmployeeId;

return dv;
}

public void BindGrid()


{

GridView1.DataSource =
GetCustomMadeDataTable(EmployeeId);
GridView1.DataBind();

P OSTE D BY D OT NE T LOVE R AT 2 :13 PM 0 C OMM E N TS

Search And Highlight word in Gridview


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

<!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 Page</title>
<style type="text/css">
.highlight{
background-color: red;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="s" runat="server">
</asp:ScriptManager>
<div>
<asp:UpdatePanel ID="UpdatePanel1" runat="server"
UpdateMode="Conditional">
<ContentTemplate>
<div>
Filter selected column:
<asp:TextBox ID="FilterText"
runat="server"
OnTextChanged="FilterText_TextChanged" />
</div>
<asp:GridView ID="GridView1"
runat="server" AutoGenerateColumns="false"
AllowPaging="True"
AllowSorting="True"
OnRowDataBound="GridView1_RowDataBound"
OnPageIndexChanged="GridView1_PageIndexChanged"
OnSorted="GridView1_Sorted">
<Columns>
<asp:BoundField DataField="Id"
HeaderText="Id"
SortExpression="Id" />
<asp:BoundField
DataField="Address" HeaderText="Address"
SortExpression="Address" />
<asp:BoundField DataField="City"
HeaderText="Address"
SortExpression="City" />
</Columns>
</asp:GridView>
</ContentTemplate>
</asp:UpdatePanel>
</div>
</form>

<script type="text/javascript">
Sys.Application.add_load(page_load);
Sys.Application.add_unload(page_unload);
function page_load(){
$addHandler($get('FilterText'),
'keydown', onFilterTextChanged);
}
function page_unload(){
$removeHandler($get('FilterText'), 'keydown',
onFilterTextChanged);
}
var timeoutID = 0;
function onFilterTextChanged(e){
if (timeoutID){
window.clearTimeout(timeoutID);
}
timeoutID = window.setTimeout(updateFilterText, 1000);
}
function updateFilterText(){
__doPostBack('FilterText', '');
}
</script>

</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 GridViewSearchHeighlight :


System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{

if (!IsPostBack)
{

BindGrid();
}
}
public DataTable GetCustomMadeDataTable()
{

//Create a new DataTable object


System.Data.DataTable objDataTable = new
System.Data.DataTable();
//Create three columns with string as their type
objDataTable.Columns.Add("Id", typeof(int));
objDataTable.Columns.Add("Address", typeof(string));
objDataTable.Columns.Add("City", typeof(string));
objDataTable.Columns.Add("Postalcode",
typeof(string));
//Adding some data in the rows of this DataTable
DataRow dr;
int intIndex = 900;
for (int i = 1; i <10; i++)
{

dr = objDataTable.NewRow();
dr[0] = i;
dr[1] = "Address" + i.ToString();
dr[2] = "City" + i.ToString();
dr[3] = "Postalcode" + intIndex.ToString();
objDataTable.Rows.Add(dr);
intIndex++;

}
for (int i = 10; i < 20; i++)
{

dr = objDataTable.NewRow();
dr[0] = i;
dr[1] = "bbb" + i.ToString();
dr[2] = "City" + i.ToString();
dr[3] = "Postalcode" + intIndex.ToString();
objDataTable.Rows.Add(dr);
intIndex++;

}
for (int i = 20; i <30; i++)
{

dr = objDataTable.NewRow();
dr[0] = i;
dr[1] = "cde" + i.ToString();
dr[2] = "City" + i.ToString();
dr[3] = "Postalcode" + intIndex.ToString();
objDataTable.Rows.Add(dr);
intIndex++;

DataColumn[] dcPk = new DataColumn[1];


dcPk[0] = objDataTable.Columns["Id"];
objDataTable.PrimaryKey = dcPk;
Session["strTemp"] = objDataTable;
return objDataTable;
}

public void BindGrid()


{
if (Session["strTemp"] != null)
{

GridView1.DataSource = Session["strTemp"] as
DataTable;
GridView1.DataBind();

}
else
{
GridView1.DataSource = GetCustomMadeDataTable();
GridView1.DataBind();
}

protected void GridView1_Sorted(object sender, EventArgs


e)
{
UpdateFilter();
}
protected void GridView1_PageIndexChanged(object sender,
EventArgs e)
{
UpdateFilter();
}
protected void Filter_Click(object sender, EventArgs e)
{
UpdateFilter();
}
protected void GridView1_RowDataBound(object sender,
GridViewRowEventArgs e)
{
if (e.Row.RowType != DataControlRowType.DataRow)

return;
int colIndex = GetColumnIndex("Address");
TableCell cell = e.Row.Cells[colIndex];

string cellText = cell.Text;


int leftIndex = cellText.IndexOf(FilterText.Text,
StringComparison.OrdinalIgnoreCase);
int rightIndex = leftIndex + FilterText.Text.Length;
StringBuilder builder = new StringBuilder();
builder.Append(cellText, 0, leftIndex);
builder.Append("<span class=\"highlight\">");
builder.Append(cellText, leftIndex, rightIndex -
leftIndex);
builder.Append("</span>");
builder.Append(cellText, rightIndex,
cellText.Length - rightIndex);
cell.Text = builder.ToString();

}
protected void FilterText_TextChanged(object sender,
EventArgs e)
{
UpdateFilter();
}
private void UpdateFilter()
{
DataTable dt = Session["strTemp"] as DataTable;
DataView dv = new DataView(dt);

string filterExpression = null;


if (!String.IsNullOrEmpty(FilterText.Text))
filterExpression = string.Format("{0} '%{1}%'",
GridView1.SortExpression, FilterText.Text);

dv.RowFilter = "Address like" + filterExpression;


GridView1.DataSource = dv;
GridView1.DataBind();
//SqlDataSource1.FilterExpression = filterExpression;
}
private int GetColumnIndex(string columnName)
{
for (int i = 0; i < GridView1.Columns.Count; i++)
{
BoundField field = GridView1.Columns[i] as
BoundField;
if (field != null && field.DataField ==
columnName)
return i;
}
return -1;
}
}

P OSTE D BY D OT NE T LOVE R AT 11 :1 3 AM 0 C OMM E N TS

How To Freez Header Of Gridview

<%@ Page Language="C#" AutoEventWireup="true"


CodeFile="MoveUpDOwnGridview.aspx.cs"
Inherits="MoveUpDOwnGridview" %>

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

</head>
<body>
<form id="form1" runat="server">
<table style="border: 1px solid black; width: 600px"
cellpadding="0" cellspacing="0">
<tr>
<td width="193px" nowrap style="border-right:
1px solid black">
&nbsp;ID</td>
<td width="195px" nowrap style="border-right:
1px solid black">
&nbsp;Address</td>
<td width="212px" nowrap>
&nbsp;City</td>
</tr>
<tr>
<td colspan="3" width="600px" style="border-
top: 1px solid black">
<asp:Panel ID="Panel1" runat="server"
Height="250px"
ScrollBars="Vertical" Width="600px">
<asp:GridView ID="GridView1"
ShowHeader="false" runat="server"
AutoGenerateColumns="false"
OnRowDataBound="GridView1_RowData
Bound">
<Columns>
<asp:BoundField DataField="Id"
HeaderText="Id"
ItemStyle-Width="200px" />
<asp:BoundField
DataField="Address" HeaderText="Address"
ItemStyle-Width="200px" />
<asp:BoundField
DataField="City" HeaderText="City"
ItemStyle-Width="200px" />
</Columns>
</asp:GridView>
</asp:Panel>
</td>
</tr>
</table>
</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 MoveUpDOwnGridview : System.Web.UI.Page


{
private int _i = 0;
protected void Page_Load(object sender, EventArgs e)
{
BindGrid();

public DataTable GetCustomMadeDataTable()


{

//Create a new DataTable object


System.Data.DataTable objDataTable = new
System.Data.DataTable();
//Create three columns with string as their type
objDataTable.Columns.Add("Id", typeof(int));
objDataTable.Columns.Add("Address", typeof(string));
objDataTable.Columns.Add("City", typeof(string));
objDataTable.Columns.Add("Postalcode",
typeof(string));
//Adding some data in the rows of this DataTable
DataRow dr;
int intIndex = 900;
for (int i = 1; i <= 101; i++)
{

dr = objDataTable.NewRow();
dr[0] = i;
dr[1] = "Address" + i.ToString();
dr[2] = "City" + i.ToString();
dr[3] = "Postalcode" + intIndex.ToString();
objDataTable.Rows.Add(dr);
intIndex++;

DataColumn[] dcPk = new DataColumn[1];


dcPk[0] = objDataTable.Columns["Id"];
objDataTable.PrimaryKey = dcPk;
Session["strTemp"] = objDataTable;

return objDataTable;
}

public void BindGrid()


{
if (Session["strTemp"] != null)
{

GridView1.DataSource = Session["strTemp"] as
DataTable;
GridView1.DataBind();

}
else
{
GridView1.DataSource = GetCustomMadeDataTable();
GridView1.DataBind();
}
}
}

Note-The
GridView in this post don’t support sorting (But could easy be added if
you rebind the data source to the Grid with server side code). You also
need to specify the header manually; it will not get the header from
the data source associated to the GridView. To add a scroller to the
Panel, you can use the Panel control’s ScrollBars property.

P OSTE D BY D OT NE T LOVE R AT 7 :44 AM 0 C OM M E N TS

How To Use Multiview As a Tab Control

<%@ Page Language="C#" AutoEventWireup="true"


CodeFile="MultiViewTab.aspx.cs"
Inherits="MultiViewTab" %>

<!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 Page</title>
<style>
.MenuCell
{

border-color: Black;

border-width: 1px;

border-style:solid;

background-color: WhiteSmoke;

color: Black;

text-align: center;

height:25px;
font-size: x-small;

}
.MenuCellSelected

border-top-color:Black;

border-left-color:Black;

border-right-color:Black;

border-bottom-color:Gainsboro;

border-width:1px;

background-color:Gainsboro;

font-weight:bold;

font-size: x-small;

.MenuCellHover

background-color: LightSteelBlue;

font-size: x-small;

.Canvas

background-color: Gainsboro;

font-size: x-small;

border-left: 1px solid black;

border-bottom: 1px solid black;


border-right: 1px solid black;

</style>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Menu ID="Menu1" Width="300px" runat="server"
Orientation="Horizontal"
StaticEnableDefaultPopOutImage="False"
OnMenuItemClick="Menu1_MenuItemClick">
<StaticMenuItemStyle CssClass="MenuCell"
ItemSpacing="0px" />
<StaticHoverStyle CssClass="MenuCellHover" />
<StaticSelectedStyle
CssClass="MenuCellSelected" ItemSpacing="0px" />
</asp:Menu>
<asp:MultiView ID="MultiView1" runat="server"
ActiveViewIndex="0">
<asp:View ID="View1" runat="server">
<table width="600px" height="400px"
cellpadding="0" cellspacing="0">
<tr>
<td class="Canvas">
<asp:TextBox ID="TextBox2"
runat="server"></asp:TextBox>
</td>
</tr>
</table>
</asp:View>
<asp:View ID="View2" runat="server">
<table width="600px" height="400px"
cellpadding="0" cellspacing="0">
<tr>
<td class="Canvas">
<asp:Button ID="Button2"
runat="server" Text="Button" />
</td>
</tr>
</table>
</asp:View>
<asp:View ID="View3" runat="server">
<table width="600px" height="400px"
cellpadding="0" cellspacing="0">
<tr>
<td class="Canvas">
<asp:DropDownList
ID="DropDownList1" runat="server">
</asp:DropDownList>
</td>
</tr>
</table>
</asp:View>
</asp:MultiView></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 MultiViewTab : System.Web.UI.Page


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

if (!Page.IsPostBack)
{

for (int index = 0; index <


MultiView1.Views.Count; index++)
{

Menu1.Items.Add(new
MenuItem(MultiView1.Views[index].ID, index.ToString()));

Menu1.Items[0].Selected = true;

}
}

protected void Menu1_MenuItemClick(object sender,


MenuEventArgs e)
{

MultiView1.ActiveViewIndex =
Int32.Parse(e.Item.Value);

P OSTE D BY D OT NE T LOVE R AT 7 :37 AM 0 C OM M E N TS

Mark a GridView row, and move it with the up and down


key

<%@ Page Language="C#" AutoEventWireup="true"


CodeFile="MoveUpDOwnGridview.aspx.cs"
Inherits="MoveUpDOwnGridview" %>

<!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 Page</title>

<script type="text/javascript">
var currentRowId = 0;
function SelectRow()
{
if (event.keyCode == 40)
MarkRow(currentRowId+1);
else if (event.keyCode == 38)
MarkRow(currentRowId-1);

}
function MarkRow(rowId)
{
if (document.getElementById(rowId) == null)
return;
if (document.getElementById(currentRowId) != null
)

document.getElementById(currentRowId).style.
backgroundColor = '#ffffff';

currentRowId = rowId;
document.getElementById(rowId).style.backgroundC
olor = '#ff0000';

</script>

</head>
<body>
<form id="form1" runat="server">
<asp:GridView ID="GridView1" runat="server"
AutoGenerateColumns="true"
OnRowDataBound="GridView1_RowDataBound">
</asp:GridView>
</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 MoveUpDOwnGridview : System.Web.UI.Page


{
private int _i = 0;
protected void Page_Load(object sender, EventArgs e)
{
BindGrid();

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

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


(e.Row.RowState == DataControlRowState.Alternate ||
e.Row.RowState == DataControlRowState.Normal))
{

e.Row.Attributes.Add("id", _i.ToString());

e.Row.Attributes.Add("onKeyDown",
"SelectRow();");

e.Row.Attributes.Add("onClick", "MarkRow(" +
_i.ToString() + ");");

_i++;

}
public DataTable GetCustomMadeDataTable()
{

//Create a new DataTable object


System.Data.DataTable objDataTable = new
System.Data.DataTable();
//Create three columns with string as their type
objDataTable.Columns.Add("Id", typeof(int));
objDataTable.Columns.Add("Address", typeof(string));
objDataTable.Columns.Add("City", typeof(string));
objDataTable.Columns.Add("Postalcode",
typeof(string));
//Adding some data in the rows of this DataTable
DataRow dr;
int intIndex = 900;
for (int i = 1; i <= 10; i++)
{

dr = objDataTable.NewRow();
dr[0] = i;
dr[1] = "Address" + i.ToString();
dr[2] = "City" + i.ToString();
dr[3] = "Postalcode" + intIndex.ToString();
objDataTable.Rows.Add(dr);
intIndex++;

DataColumn[] dcPk = new DataColumn[1];


dcPk[0] = objDataTable.Columns["Id"];
objDataTable.PrimaryKey = dcPk;
Session["strTemp"] = objDataTable;

return objDataTable;
}

public void BindGrid()


{
if (Session["strTemp"] != null)
{

GridView1.DataSource = Session["strTemp"] as
DataTable;
GridView1.DataBind();

}
else
{
GridView1.DataSource = GetCustomMadeDataTable();
GridView1.DataBind();
}

}
}

P OSTE D BY D OT NE T LOVE R AT 7 :27 AM 0 C OM M E N TS

M O N D AY, A P R I L 7 , 2 0 0 8
Function to get parent GridView for GridViewRow
A reference to the GridView can be obtained by using
gridViewRow.Parent.Parent or (GridView) gridViewRow.NamingContainer

So I've created the static function:

public static GridView GetParentGridView(GridViewRow row)


{
//NOTE row.Parent doesn't return GridView
GridView gridView = (GridView)row.NamingContainer;
return gridView;
}

P OSTE D BY D OT NE T LOVE R AT 9 :13 AM 0 C OM M E N TS

Validate DropDownlist or TextBox Inside GridView

supoose you have a gridview in asp.net that each row in the


gridview has a dropdown(or textbox).You need to check that at least 1
row of the gridiew has a dropdown selected before submitting.

<%@ Page Language="C#" AutoEventWireup="true"


CodeFile="GridDropDown.aspx.cs"
Inherits="GridDropDown" %>

<!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 Page</title>

<script language="javascript" type="text/javascript">


//var text="firsttext";
function Submit()
{
var txtNamefirst = "GridView1_ctl";
var txtNameLast = "_txtNameChk";

var chkNamefirst = "GridView1_ctl";


var chkNameLast = "_dropselect";

var temptxtobj= document.getElementById(txtNamefirst+"02"


+ txtNameLast) ;
var tempchkobj= document.getElementById(chkNamefirst+"02"
+ chkNameLast) ;
var i=1;
var txtFlag=false;
var drpFlag=false;
var id;
while(temptxtobj != null && tempchkobj!=null )
{
if( !txtFlag && temptxtobj.value!="")
txtFlag=true;

if( !drpFlag && tempchkobj.selectedIndex>=0)


drpFlag=true;
i++;
if (i< 10)
id="0" + i;
else
id= i;
temptxtobj= document.getElementById(txtNamefirst+ id +
txtNameLast) ;
tempchkobj= document.getElementById(chkNamefirst+ id +
chkNameLast) ;
}
if (!(txtFlag && drpFlag))
alert("select");

return txtFlag && drpFlag;

}
</script>

</head>
<body>
<form id="form1" runat="server" onsubmit="return
Submit();">
<div>
<asp:GridView ID="GridView1" runat="server"
AutoGenerateColumns="False" Height="80px"
Width="224px">
<Columns>
<asp:TemplateField HeaderText="Select
Txt">
<ItemTemplate>
<asp:DropDownList ID="dropselect"
runat="server">
<asp:ListItem>
</asp:ListItem>
<asp:ListItem>aaa</asp:ListI
tem>
<asp:ListItem>bbbb</asp:List
Item>
<asp:ListItem></asp:ListItem>
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Enter
Text">
<ItemTemplate>
<asp:TextBox ID="txtNameChk"
runat="server">
</asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Name">
<ItemTemplate>
<asp:TextBox ID="txtName"
runat="server"
Text='<%# DataBinder.Eval(Container.DataItem, "Name")%>'>
</asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Age">
<ItemTemplate>
<asp:Label ID="ibiage"
runat="server"
Text='<%# DataBinder.Eval(Container.DataItem,
"Age")%>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:Button ID="Button1" runat="server"
Text="Submit" /></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 GridDropDown : System.Web.UI.Page


{
private DataTable Data()
{

DataTable dt = new DataTable();


dt.Columns.Add("Name", typeof(string));
dt.Columns.Add("Age", typeof(int));

dt.Rows.Add(new object[] { "aaaa", 1 });


dt.Rows.Add(new object[] { "bbbb", 2 });
dt.Rows.Add(new object[] { "cccc", 3 });
dt.Rows.Add(new object[] { "aaaa", 1 });
dt.Rows.Add(new object[] { "bbbb", 2 });
dt.Rows.Add(new object[] { "cccc", 3 });
dt.Rows.Add(new object[] { "aaaa", 1 });
dt.Rows.Add(new object[] { "bbbb", 2 });
dt.Rows.Add(new object[] { "cccc", 3 });
dt.Rows.Add(new object[] { "aaaa", 1 });
dt.Rows.Add(new object[] { "bbbb", 2 });
dt.Rows.Add(new object[] { "cccc", 3 });

return dt;

protected void Page_Load(object sender,


System.EventArgs e)
{
if (!this.IsPostBack)
{
this.GridView1.DataSource = Data();
this.GridView1.DataBind();
}
}
}

P OSTE D BY D OT NE T LOVE R AT 7 :16 AM 0 C OM M E N TS

F R I D AY, A P R I L 4 , 2 0 0 8
Data-Binding to Methods in ASP.NET(conditionally)

Sometimes I need some to bind a thing conditionally.Now, let’s say


that you would really like to highlight all addresses where the zip code
starts with "902". Let's take the AddressPanel in the ItemTemplate and
bind its CssClass property like this:

<%@ Page Language="C#" AutoEventWireup="true"


CodeFile="ColorGrid.aspx.cs"
Inherits="ColorGrid" %>

<!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 Page</title>
<style type="text/css">
.highlight-address
{
color:red;

}
.normal-address
{
color:green;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:DataList ID="DataList1" runat="server">
<ItemTemplate>
<asp:Panel ID="AddressPanel" runat="server"
CssClass='<%#GetCssForPostalCode(Container.Da
taItem)%>'>
<asp:Label ID="Address" runat="server"
Text='<%# Eval("Address") %>' /><br />
<asp:Label ID="City" runat="server"
Text='<%# Eval("City") %>' /><br />
<asp:Label ID="PostalCode" runat="server"
Text='<%# Eval("Postalcode") %>' />
</asp:Panel>
</ItemTemplate>
</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;

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


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

BindGrid();

}
protected string GetCssForPostalCode(object dataItem)
{
DataRowView row = dataItem as DataRowView;

if (row["PostalCode"].ToString().EndsWith("902"))
return "highlight-address";

return "normal-address";

public void BindGrid()


{
if (Session["strTemp"] != null)
{

DataList1.DataSource = Session["strTemp"] as
DataTable;
DataList1.DataBind();

}
else
{
DataList1.DataSource = GetCustomMadeDataTable();
DataList1.DataBind();
}

}
public DataTable GetCustomMadeDataTable()
{

//Create a new DataTable object


System.Data.DataTable objDataTable = new
System.Data.DataTable();
//Create three columns with string as their type
objDataTable.Columns.Add("Id", typeof(int));
objDataTable.Columns.Add("Address", typeof(string));
objDataTable.Columns.Add("City", typeof(string));
objDataTable.Columns.Add("Postalcode",
typeof(string));
//Adding some data in the rows of this DataTable
DataRow dr;
int intIndex = 900;
for (int i = 1; i <= 20; i++)
{
dr = objDataTable.NewRow();
dr[0] = i;
dr[1] = "Address" + i.ToString();
dr[2] = "City" + i.ToString();
dr[3] = "Postalcode" + intIndex.ToString();
objDataTable.Rows.Add(dr);
intIndex++;

DataColumn[] dcPk = new DataColumn[1];


dcPk[0] = objDataTable.Columns["Id"];
objDataTable.PrimaryKey = dcPk;
Session["strTemp"] = objDataTable;

return objDataTable;
}

P OSTE D BY D OT NE T LOVE R AT 3 :51 PM 0 C OMM E N TS

Automatic Edit and save Action in a Html Table

<%@ Page Language="C#" AutoEventWireup="true"


CodeFile="Inlineedit.aspx.cs"
Inherits="Inlineedit" %>

<!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 Page</title>

<script language='javascript'>

function editCell(C)
{
document.getElementById("txt" + C).style.display="block";
document.getElementById("txt" + C).value =
document.getElementById("span" + C).value;
document.getElementById("span" + C).style.display="none";
}

function updateCell(C)
{
document.getElementById("span" + C).style.display="block";
document.getElementById("span" + C).value =
document.getElementById("txt" + C).value;
document.getElementById("span" + C).innerText=
document.getElementById("span" + C).value;
document.getElementById("txt" + C).style.display="none";
}

</script>

</head>
<body>
<form id="form1" runat="server">
<div>
<table>
<tr>
<td>
<span id='span1' onclick='editCell("1");'
value='This is some value'>This is some value</span>
<input type='text' id='txt1'
onblur='updateCell("1");'
value='' style='display: none;'>
</td>
</tr>
</table>
</div>
</form>
</body>
</html>

P OSTE D BY D OT NE T LOVE R AT 2 :33 PM 0 C OMM E N TS

T H U R S D AY, A P R I L 3 , 2 0 0 8
Bind GridView To Generics

<%@ Page Language="C#" AutoEventWireup="true"


CodeFile="GenericsBindGridview.aspx.cs"
Inherits="GenericsBindGridview" %>

<!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 Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="GridView1" runat="server"
DataSourceID="ObjectDataSource1" BorderColor="#CC9966"
BorderStyle="None" BorderWidth="1px"
BackColor="White"
CellPadding="4">
<HeaderStyle ForeColor="#FFFFCC"
BackColor="#990000" Font-Italic="False"
Font-Bold="True">
</HeaderStyle>
</asp:GridView>
<asp:ObjectDataSource ID="ObjectDataSource1"
runat="server"
TypeName="OrderSystem"
SelectMethod="GetOrders"></asp:ObjectDataSource
>
</div>
</form>
</body>
</html>
Ordersytem.cs

using System;
using System.Collections.Generic;

public class Order


{
private int _orderId;
private string _productName;

public Order(int orderId, string productName)


{
_orderId = orderId;
_productName = productName;
}

public string ProductName


{
get
{
return _productName;
}
}

public int OrderId


{
get
{
return _orderId;
}
}
}

public class OrderSystem


{
public List<Order> GetOrders()
{
List<Order> orders = new List<Order>();
orders.Add(new Order(123, "Dell"));
orders.Add(new Order(345, "Toshiba"));
orders.Add(new Order(567, "Compaq"));
return orders;
}
}

P OSTE D BY D OT NE T LOVE R AT 12 :4 4 PM 0 C OM M E N TS

GridView Confirm When Delete.

<%@ Page Language="C#" AutoEventWireup="true"


CodeFile="Default1.aspx.cs"
Inherits="_Default" %>

<%@ Register Assembly="AjaxControlToolkit"


Namespace="AjaxControlToolkit"
TagPrefix="ajaxToolkit" %>
<!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="head" runat="server">
<title>Delete Confirm Example</title>
<script type="text/javascript">

// keeps track of the delete button for the row

// that is going to be removed

var _source;

// keep track of the popup div

var _popup;
function showConfirm(source){

this._source = source;

this._popup = $find('mdlPopup');

// find the confirm ModalPopup and show it

this._popup.show();

function okClick(){

// find the confirm ModalPopup and hide it

this._popup.hide();

// use the cached button as the postback source

__doPostBack(this._source.name, '');

function cancelClick(){

// find the confirm ModalPopup and hide it


this._popup.hide();

// clear the event source

this._source = null;

this._popup = null;

</script>

<style>

.modalBackground {

background-color:Gray;

filter:alpha(opacity=70);

opacity:0.7;

.confirm{

background-color:White;

padding:10px;

width:370px;

</style>
</head>
<body>
<form id="form" runat="server" style="font-family:
Trebuchet MS;">
<asp:ScriptManager ID="scriptManager" runat="server"
/>
<div>
<asp:UpdatePanel ID="updatePanel" runat="server"
UpdateMode="Conditional">
<ContentTemplate>
<asp:Label ID="lblTitle" runat="server"
Text="User List"
BackColor="lightblue" Width="95%" />
<asp:GridView ID="gvUsers" runat="server"
AutoGenerateColumns="false" Width="95%">
<AlternatingRowStyle
BackColor="aliceBlue" />
<HeaderStyle HorizontalAlign="Left"
/>
<Columns>
<asp:BoundField DataField="ID"
HeaderText="ID" />
<asp:BoundField
DataField="FirstName"
HeaderText="FirstName" />
<asp:BoundField
DataField="LastName"
HeaderText="LastName" />
<asp:BoundField
DataField="Address" HeaderText="Address" />
<asp:TemplateField ControlStyle-
Width="50px"
HeaderStyle-Width="60px"
ItemStyle-
HorizontalAlign="Center">
<ItemTemplate>
<asp:Button
ID="btnDelete" runat="server"
OnClientClick="showConfi
rm(this); return false;"
OnClick="BtnDelete_C
lick" Text="Delete" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</ContentTemplate>
</asp:UpdatePanel>

<ajaxToolkit:ModalPopupExtender
ID="ModalPopupExtender1"
BehaviorID="mdlPopup" runat="server"
TargetControlID="div" PopupControlID="div"
OkControlID="btnOk"
OnOkScript="okClick();"
CancelControlID="btnNo"
OnCancelScript="cancelClick();"
BackgroundCssClass="modalBackground" />
<div id="div" runat="server" align="center"
class="confirm"
style="display: none">
<img align="absmiddle" src="Img/warning.jpg"
/>
Are you sure you want to delete this
item?
<asp:Button ID="btnOk" runat="server"
Text="Yes" Width="50px" />
<asp:Button ID="btnNo" runat="server"
Text="No" Width="50px" />
</div>
</div>
</form>
</body>
</html>

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 (!this.IsPostBack)
{

this.gvUsers.DataSource = this.Users;

this.gvUsers.DataBind();

}
public class User
{
private int _id;
private string _firstName;
private string _lastName;
private string _Address;
// private bool _isCompleted;

public User(int id, string firstname, string


lastname, string address)
{

this._id = id;

this._firstName = firstname;
this._lastName = lastname;
this._Address = address;

}
public int ID
{

get { return this._id; }

public string FirstName


{

get { return this._firstName; }

public string LastName


{

get { return this._lastName; }

}
public string Address
{

get { return this._Address; }

private System.Collections.Generic.List<User> Users


{
get
{

System.Collections.Generic.List<User> item =
this.Session["Users"] as
System.Collections.Generic.List<User>;

if (item == null)
{

item = new
System.Collections.Generic.List<User>();

item.Add(new User(1, "santosh", "kumar",


"Chandigarh"));

item.Add(new User(2, "Vinod", "kumar",


"HP"));

item.Add(new User(3, "Ajay", "Chawla",


"PB"));

item.Add(new User(4, "MandeepInder",


"Singh", "Chandigarh"));
item.Add(new User(4, "Harpreet", "Singh",
"Chandigarh"));

this.Session["Users"] = item;

return item;

protected void BtnDelete_Click(object sender, EventArgs


e)
{

// get the gridviewrow from the sender so we can


get the datakey we need
Button btnDelete = sender as Button;

GridViewRow row =
(GridViewRow)btnDelete.NamingContainer;

// find the item and remove it

User itemToRemove = this.Users[row.RowIndex];

this.Users.Remove(itemToRemove);

// rebind the datasource

this.gvUsers.DataSource = this.Users;

this.gvUsers.DataBind();

P OSTE D BY D OT NE T LOVE R AT 9 :18 AM 0 C OM M E N TS

W E D N E S D AY, A P R I L 2 , 2 0 0 8
ASP.NET AJAX Tabs Control
The Tabs control allows you to create the Tabs very quickly. The tabs
can be changed without causing a postback. This tabs based on the
data from the Categories and Products table in the Northwind
database(i this example i have used dummy data simmilar to
northwind database)

<%@ Page Language="C#" AutoEventWireup="true"


CodeFile="DynamicTabPanelGridViewGuy.aspx.cs"
Inherits="DynamicTabPanelGridViewGuy" %>

<%@ Register Assembly="AjaxControlToolkit"


TagPrefix="ajaxToolkit"
Namespace="AjaxControlToolkit" %>
<!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 Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:ScriptManager ID="ScriptManager1"
runat="server" />
<ajaxToolkit:TabContainer ID="TabContainer1"
runat="server"
ActiveTabIndex="0">
</ajaxToolkit:TabContainer>
</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 AjaxControlToolkit;
using System.Collections.Generic;

public partial class DynamicTabPanelGridViewGuy :


System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{

List<Category> categories =
Category.GetCategories();

foreach (Category category in categories)


{

GridView gv = new GridView();


gv.BackColor = System.Drawing.Color.Wheat;

gv.DataSource = category.Products;

gv.DataBind();

AjaxControlToolkit.TabPanel tab = new


AjaxControlToolkit.TabPanel();

tab.Controls.Add(gv);
tab.HeaderText = category.CategoryName;

TabContainer1.Tabs.Add(tab);

}
public class Category
{

private int categoryID;

private string categoryName;

private List<Product> products;

public int CategoryID


{

get { return this.categoryID; }

set { this.categoryID = value; }

public string CategoryName


{

get { return this.categoryName; }

set { this.categoryName = value; }

public List<Product> Products


{

get { return this.products; }

set { this.products = value; }

}
public static List<Category> GetCategories()
{
List<Category> categories = new List<Category>();

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


{

Category category = new Category();

category.CategoryID = i;

category.CategoryName = "Column1Data" +
i.ToString();

categories.Add(category);

// get the products

foreach (Category category in categories)


{

category.Products =
GetProducts(category.CategoryID);

return categories;

public static List<Product> GetProducts(int


categoryID)
{

List<Product> products = new List<Product>();

if (categoryID == 1)
{
for (int i = 1; i <= 20; i++)
{

Product product = new Product();

product.ProductID = i;

product.ProductName = "Product1";
products.Add(product);

}
if (categoryID == 2)
{
for (int i = 1; i <= 20; i++)
{

Product product = new Product();

product.ProductID = i;

product.ProductName = "Product2";

products.Add(product);

}
if (categoryID == 5)
{
for (int i = 1; i <= 20; i++)
{

Product product = new Product();

product.ProductID = i;

product.ProductName = "product5";

products.Add(product);

return products;

}
public class Product
{

private int productID;

private string productName;

public int ProductID


{

get { return this.productID; }

set { this.productID = value; }

public string ProductName


{

get { return this.productName; }

set { this.productName = value; }

public Product()
{

}
}

P OSTE D BY D OT NE T LOVE R AT 12 :1 2 PM 0 C OM M E N TS

Maintain The State Of Checkbox After Postback (Inside


GridView)

<%@ Page Language="C#" AutoEventWireup="true"


CodeFile="Assembly.aspx.cs"
Inherits="Assembly" %>

<%@ Assembly Src="MyAddFunctionClass.cs" %>


<!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 Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="GridView1" runat="server"
DataKeyNames="Id"
AutoGenerateColumns="False"
OnRowUpdating="GridView1_RowUpdating"
OnRowEditing="GridView1_RowEditing"
OnRowCancelingEdit="GridView1_RowCancelingEdit"
>
<Columns>
<asp:BoundField DataField="Id" HeaderText="Id"
ReadOnly="True" />
<asp:BoundField DataField="Column1"
HeaderText="Column1" />
<asp:BoundField DataField="Column2"
HeaderText="Column2" />
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="CheckBox1"
runat="server"
OnCheckedChanged="CheckBox1_CheckedChanged"
OnDataBinding="CheckBox1_DataBindin
g" />
</ItemTemplate>
</asp:TemplateField>
<asp:CommandField ShowEditButton="True"
ShowCancelButton="true"
ButtonType="Link"/>
</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 Assembly : System.Web.UI.Page


{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindGrid();
}

public void BindGrid()


{
if (Session["strTemp"] != null)
{

GridView1.DataSource = Session["strTemp"] as
DataTable;
GridView1.DataBind();

}
else
{
GridView1.DataSource = GetCustomMadeDataTable();
GridView1.DataBind();
}

}
public DataTable GetCustomMadeDataTable()
{

//Create a new DataTable object


System.Data.DataTable objDataTable = new
System.Data.DataTable();
//Create three columns with string as their type
objDataTable.Columns.Add("Id", typeof(int));
objDataTable.Columns.Add("Column1", typeof(string));
objDataTable.Columns.Add("Column2", typeof(string));
objDataTable.Columns.Add("Column3", typeof(string));
//Adding some data in the rows of this DataTable
DataRow dr;
for (int i = 1; i <= 20; i++)
{

dr = objDataTable.NewRow();
dr[0] = i;
dr[1] = "Column1Data" + i.ToString();
dr[2] = "Column2Data" + i.ToString();
dr[3] = "Column3Data" + i.ToString();
objDataTable.Rows.Add(dr);

}
DataColumn[] dcPk = new DataColumn[1];
dcPk[0] = objDataTable.Columns["Id"];
objDataTable.PrimaryKey = dcPk;
Session["strTemp"] = objDataTable;

return objDataTable;
}
protected void CheckBox1_CheckedChanged(object sender,
EventArgs e)
{
CheckBox checkbox = (CheckBox)sender;
if (checkbox.Checked)
{
ViewState[checkbox.UniqueID] = true;
}
else
{
ViewState.Remove(checkbox.UniqueID);
}
}

protected void CheckBox1_DataBinding(object sender,


EventArgs e)
{
CheckBox checkbox = (CheckBox)sender;
checkbox.Checked = ViewState[checkbox.UniqueID] != null;
}
protected void GridView1_RowUpdating(object sender,
GridViewUpdateEventArgs e)
{
int productID =
(int)((DataKey)GridView1.DataKeys[e.RowIndex]).Value;
string str1 =
((TextBox)(GridView1.Rows[e.RowIndex].Cells[1].Controls[0])
).Text;
string str2 =
((TextBox)(GridView1.Rows[e.RowIndex].Cells[2].Controls[0])
).Text;
DataTable dt = Session["strTemp"] as DataTable;

DataRow[] rows = dt.Select("ID = " + productID);


rows[0]["Column1"] = str1;
rows[0]["Column2"] = str2;
GridView1.EditIndex = -1;
BindGrid();

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

}
protected void GridView1_RowCancelingEdit(object sender,
GridViewCancelEditEventArgs e)
{
GridView1.EditIndex = -1;
GridView1.DataSource = GetCustomMadeDataTable();
BindGrid();

P OSTE D BY D OT NE T LOVE R AT 10 :0 9 AM 0 C OMM E N TS

T U E S D AY, A P R I L 1 , 2 0 0 8
Showing data from multiple tables effectively using
GridView
<%@ Page Language="C#" AutoEventWireup="true"
CodeFile="HireUsingCodeBhindGrid.aspx.cs"
Inherits="HireUsingCodeBhindGrid" %>

<!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 Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="GridView1" runat="server"
AutoGenerateColumns="False"
OnRowDataBound="GridView1_RowDataBound">
<Columns>
<asp:BoundField DataField="CompanyName"
HeaderText="CompanyName" />
<asp:TemplateField>
<ItemTemplate>
<asp:GridView ID="GridView2"
runat="server" AutoGenerateColumns="False">
<Columns>
<asp:BoundField
DataField="Dept" HeaderText="Department" />
<asp:BoundField
DataField="name" HeaderText="Name" />
</Columns>
</asp:GridView>
</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 HireUsingCodeBhindGrid :


System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
GridView1.DataSource =
CreateDS().Tables["Company"];
GridView1.DataBind();
}

}
private DataSet CreateDS()
{
DataSet ds;
if (Session["DataList_ParentChild"] == null)
{
ds = new DataSet();
DataTable dt = new DataTable("Company");
DataRow dr;
dt.Columns.Add(new DataColumn("ID",
typeof(Int32)));
dt.Columns.Add(new DataColumn("CompanyName",
typeof(string)));
dt.Columns.Add(new DataColumn("Address",
typeof(string)));
dt.Columns.Add(new DataColumn("Name",
typeof(string)));
dt.Columns.Add(new DataColumn("Dept",
typeof(string)));
for (int i = 1; i < 10; i++)
{
dr = dt.NewRow();
dr[0] = i;
dr[1] = "Company " + i;
dr[2] = "Address " + i;
dr[3] = "Manager name";
dr[4] = "Adminstration";
dt.Rows.Add(dr);
}
ds.Tables.Add(dt);
DataColumn[] Parent_PKColumns = new
DataColumn[1];
Parent_PKColumns[0] = dt.Columns["ID"];
dt.PrimaryKey = Parent_PKColumns;

dt = new DataTable("Employees");
dt.Columns.Add(new DataColumn("ID",
typeof(Int32)));
dt.Columns.Add(new DataColumn("CompanyID",
typeof(Int32)));
dt.Columns.Add(new DataColumn("Name",
typeof(string)));
dt.Columns.Add(new DataColumn("Dept",
typeof(string)));
for (int i = 1; i < 10; i++)
{
int imax = 0;
if (i % 2 == 0) imax = 5;
else imax = 4;
for (int y = 2; y < imax; y++) //3
emplyees for each company
{
dr = dt.NewRow();
dr[0] = y + i * 5;
dr[1] = i;
dr[2] = "Employee # " + dr[0];
dr[3] = "Dept # " + (y + i);
dt.Rows.Add(dr);
}
}
DataColumn[] Child_PKColumns = new
DataColumn[1];
Child_PKColumns[0] = dt.Columns["ID"];
dt.PrimaryKey = Child_PKColumns;
ds.Tables.Add(dt);
DataColumn[] Child_FKColumns = new
DataColumn[1];
Child_FKColumns[0] = dt.Columns["CompanyID"];

ds.Relations.Add("ParentChild",
Parent_PKColumns, Child_FKColumns);
Session["DataList_ParentChild"] = ds;
}
else
{
ds = (DataSet)Session["DataList_ParentChild"];
}
return ds;

}
protected void GridView1_RowDataBound(object sender,
GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
//Just cast the current DataItem to a
DataRowView and then
//use the method CreateChildView to get a view
of the related
//rows

((GridView)e.Row.FindControl("GridView2")).Data
Source
=
((DataRowView)e.Row.DataItem).CreateChildView("ParentChild"
);
((GridView)e.Row.FindControl("GridView2")).Data
Bind();

}
}
}

P OSTE D BY D OT NE T LOVE R AT 3 :41 PM 0 C OMM E N TS

How To Validate Calender Control in Asp.net 2.0

create a textbox and default all colors to white (or whatever you need
to hide it) create a event for OnSelectionChange on the calendar
control.

<%@ Page Language="C#" AutoEventWireup="true"


CodeFile="ValidateCalControl.aspx.cs"
Inherits="ValidateCalControl" %>

<!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 Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Calendar ID="Cal1" runat="server"
OnSelectionChanged="Cal1_SelectionChanged"></asp:Calendar>
<asp:TextBox ID="txtCal" runat="server" BackColor="White"
BorderColor="white"
ForeColor="white"></asp:TextBox>
<asp:RequiredFieldValidator ID="Req1" runat="server"
ControlToValidate="txtCal" ErrorMessage="Select
Date"></asp:RequiredFieldValidator>
<asp:Button ID="btnTest" runat="server" Text="Test" />
</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 ValidateCalControl : System.Web.UI.Page


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

}
protected void Cal1_SelectionChanged(object sender,
EventArgs e)
{
txtCal.Text = Cal1.SelectedDate.ToShortDateString();
Req1.Validate();

}
}
P OSTE D BY D OT NE T LOVE R AT 12 :2 7 PM 0 C OM M E N TS

How To Bing GridView with Custom Class

<%@ Page Language="C#" AutoEventWireup="true"


CodeFile="CustomGridView.aspx.cs"
Inherits="CustomGridView" %>

<!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 Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="GridView1" runat="server">
</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 CustomGridView : System.Web.UI.Page


{
protected void Page_Load(object sender, EventArgs e)
{
Person[] personList = new Person[5];
for (int i = 0; i < 5; i++)
{
personList[i] = new Person(i + 1, "test",
"test", "India");
}

GridView1.DataSource = personList;
GridView1.DataBind();

}
public class Person
{
private int m_id;
public string _FirstName;
public string _LastName;
public string _Address;

public string Address


{
get
{
return _Address;

}
public int ID
{
get { return m_id; }
}
public string FullName
{
get { return _FirstName + " " + _LastName; }
}

public Person(int id, string firstName, string


lastName, string address)
{
m_id = id;
_FirstName = firstName;
_LastName = lastName;
_Address = address;
}
}
}

P OSTE D BY D OT NE T LOVE R AT 12 :1 5 PM 0 C OM M E N TS
passing data from javascript to asp.net cs code on the
server side

<%@ Page Language="C#" AutoEventWireup="true"


CodeFile="PassFromClientToServer.aspx.cs"
Inherits="PassFromClientToServer" %>

<!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 Page</title>

<script type="text/javascript">
function Pass()
{
var hidden = document.getElementById("ContentType");
hidden.value = "test value from client side";
var frm = document.getElementById("form1");
frm.submit();
}
</script>

</head>
<body>
<form id="form1" runat="server">
<div>
<input type="hidden" id="ContentType"
name="ContentType" />
<asp:TextBox ID="txt1"
runat="Server"></asp:TextBox>
<asp:Button ID="btnClick" runat="server"
Text="Test"
OnClientClick="Pass();" />
</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 PassFromClientToServer :


System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (Request.Form["ContentType"] != null)
{
string myHiddenFiledValue =
Request.Form["ContentType"].ToString();
txt1.Text = myHiddenFiledValue.ToString();
}

P OSTE D BY D OT NE T LOVE R AT 10 :2 1 AM 0 C OMM E N TS

How To Add Client Side code to to select Checkboxes All


and deselct Check boxes all in GridView

<%@ Page Language="C#" AutoEventWireup="true"


CodeFile="GridViewCheckbox.aspx.cs"
Inherits="GridViewCheckbox" %>

<!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 Page</title>

<script type="text/javascript">

function SetStatus(headObj) {
var obj = document.getElementsByTagName("input");
for(var i =0; i < obj.length ; i++) {
if(obj[i].type.toLowerCase() == "checkbox" &&
obj[i].name.toLowerCase() != headObj.name.toLowerCase() )
{
if(headObj.checked)
obj[i].checked = true;
else
obj[i].checked = false;
}
}
return true;
}

</script>

</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="GridView1" runat="server"
AutoGenerateColumns="false">
<Columns>
<asp:TemplateField>
<HeaderTemplate>
<asp:CheckBox runat="server"
ID="HeaderLevelCheckBox"
OnClick="SetStatus(this);" />
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox runat="server"
ID="RowLevelCheckBox" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="CompanyName"
HeaderText="CompanyName" />
<asp:BoundField DataField="Address"
HeaderText="Address" />
</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 GridViewCheckbox : System.Web.UI.Page


{
protected void Page_Load(object sender, EventArgs e)
{
GridView1.DataSource = c();
GridView1.DataBind();

}
public DataSet c()
{
DataSet ds = new DataSet();
DataTable dt = new DataTable("Company");
DataRow dr;
dt.Columns.Add(new DataColumn("accountNo",
typeof(Int32)));
dt.Columns.Add(new DataColumn("CompanyName",
typeof(string)));
dt.Columns.Add(new DataColumn("Address",
typeof(string)));
for (int i = 0; i <= 10; i++)
{
dr = dt.NewRow();
dr[0] = i;
dr[1] = "Company" + i + Environment.NewLine +
"Title" + i;
dr[2] = "Address" + i + Environment.NewLine +
"Title" + i;
dt.Rows.Add(dr);
}
ds.Tables.Add(dt);
return ds;
}
}
P OSTE D BY D OT NE T LOVE R AT 8 :45 AM 0 C OM M E N TS
March 2008 Home

Subscribe to: Posts (Atom)

1h

Você também pode gostar