Ajax Captcha

June 9, 2008

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

<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”&gt;
<html xmlns=”http://www.w3.org/1999/xhtml”&gt;
<head>
<title>Ajax Captcha</title>

<script language=”javaScript” type=”text/javascript”>

var url = ‘Services/AjaxServiceRequestPages/CheckImageCaptcha.aspx?code=’;
var captchaOK = 2; // 2 – not yet checked, 1 – correct, 0 – failed
function getHTTPObject()
{
try
{
req = new XMLHttpRequest();
}
catch (err1)
{
try
{
req = new ActiveXObject(“Msxml12.XMLHTTP”);
}
catch (err2)
{
try
{
req = new ActiveXObject(“Microsoft.XMLHTTP”);
}
catch (err3)
{
req = false;
}
}
}
return req;
}

var http = getHTTPObject(); // We create the HTTP Object
function handleHttpResponse()
{
if (http.readyState == 4)
{
captchaOK = http.responseText.charAt(0);
if(captchaOK != 1)
{
alert(‘The entered code was not correct. Please try again’);
document.forms[0].code.value=”;
document.forms[0].code.focus();
return false;
}
document.forms[0].submit();
}
}

function checkcode(thecode)
{
http.open(“GET”, url + escape(thecode), true);
http.onreadystatechange = handleHttpResponse;
http.send(null);
}

function checkform()
{
// First the normal form validation
if(document.forms[0].req.value==”)
{
alert(‘Please complete the “required” field’);
document.forms[0].req.focus();
return false;
}
if(document.forms[0].code.value==”)
{
alert(‘Please enter the string from the displayed image’);
document.forms[0].code.value=”;
document.forms[0].code.focus();
return false;
}
// Now the Ajax CAPTCHA validation
checkcode(document.forms[0].code.value);
return false;
}

</script>

</head>
<body>
<form name=”myform” runat=”server”>
<table>
<tr>
<td>
Required field:
</td>
<td>
<input type=”text” name=”req” value=”” />
</td>
</tr>
<tr>
<td>
Optional field:
</td>
<td>
<input type=”text” name=”opt” value=”” />
</td>
</tr>
<tr>
<td>
Captcha image:
</td>
<td>
<img alt=”Security Image” src=”Services/AjaxServiceRequestPages/SecurityCodeImage.aspx”/>
</td>
</tr>
<tr>
<td>
String:
</td>
<td>
<input type=”text” name=”code” value=”” />
</td>
</tr>
<tr>
<td>
</td>
<td>
<input type=”submit” value=”Submit Form” onclick=”return checkform()” />
</td>
</tr>
</table>
</form>
</body>
</html>


Nested GridView with JS

January 31, 2008

Nested GridView with JS

<html xmlns=”http://www.w3.org/1999/xhtml&#8221; >
<head runat=”server”>
<title>Nested GridView</title>

<script type=”text/C#” runat=”server”>

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if(e.Row.RowType == DataControlRowType.DataRow)
{
GridView gv = (GridView)e.Row.FindControl(“GridView2”);
SqlDataSource dbSrc = new SqlDataSource();
dbSrc.ConnectionString = ConfigurationManager.ConnectionStrings[“LoginCon”].ConnectionString;
dbSrc.SelectCommand = “SELECT * FROM Orders WHERE CustomerID = ‘” + GridView1.DataKeys[e.Row.RowIndex].Value + “‘ ORDER BY OrderDate”;
gv.DataSource = dbSrc;
gv.DataBind();
}
}

</script>

<script type=”text/javascript”>

function ShowChildGrid(obj)
{
var div = document.getElementById(obj);
var img = document.getElementById(‘img’ + obj);
var theFlag = div.style.display == “none”;
div.style.display = (theFlag) ? “inline” : “none”;
img.src = (theFlag) ? “Images/arrowdown.jpg” : “Images/arrowright.jpg”;
}

</script>
</head>
<body>
<form id=”form1″ runat=”server”>
<div>
<asp:GridView ID=”GridView1″ runat=”server”
AllowPaging=”True”
AutoGenerateColumns=”False”
DataKeyNames=”CustomerID”
DataSourceID=”SqlDataSource1″
PageSize=”20″
OnRowDataBound=”GridView1_RowDataBound”>

<HeaderStyle CssClass=”dataTable” />
<RowStyle CssClass=”dataTable” />
<AlternatingRowStyle CssClass=”dataTableAlt” />

<Columns>
<asp:TemplateField>
<ItemTemplate>
<a href=”javascript:ShowChildGrid(‘div<%# Eval(“CustomerID”) %>’);”>
<img id=”imgdiv<%# Eval(“CustomerID”) %>” alt=”Click to show/hide orders” border=”0″ src=”Images/arrowright.jpg” />
</a>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField=”CompanyName” HeaderText=”CompanyName” SortExpression=”CompanyName” />
<asp:BoundField DataField=”ContactName” HeaderText=”ContactName” SortExpression=”ContactName” />
<asp:BoundField DataField=”Address” HeaderText=”Address” SortExpression=”Address” />
<asp:BoundField DataField=”City” HeaderText=”City” SortExpression=”City” />
<asp:BoundField DataField=”PostalCode” HeaderText=”PostalCode” SortExpression=”PostalCode” />
<asp:BoundField DataField=”Phone” HeaderText=”Phone” SortExpression=”Phone” />
<asp:TemplateField>
<ItemTemplate>
</td></tr>
<tr>
<td colspan=”100%”>
<div id=”div<%# Eval(“CustomerID”) %>” style=”display:none;position:relative;left:25px;” >
<asp:GridView ID=”GridView2″ runat=”server”
AutoGenerateColumns=”false”
DataKeyNames=”OrderID”
EmptyDataText=”No orders for this customer.”
Width=”80%”>
<HeaderStyle CssClass=”dataTable” />
<AlternatingRowStyle CssClass=”dataTableAlt” />
<RowStyle CssClass=”dataTable” />
<Columns>
<asp:BoundField DataField=”OrderDate” HeaderText=”Order Date” DataFormatString=”{0:MMM-dd-yyyy}” HtmlEncode=”False” />
<asp:BoundField DataField=”ShippedDate” HeaderText=”Shipped Date” DataFormatString=”{0:MMM-dd-yyyy}” HtmlEncode=”False” />
<asp:BoundField DataField=”ShipCity” HeaderText=”Shipped To” />
</Columns>
</asp:GridView>
</div>
</td>
</tr>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:SqlDataSource ID=”SqlDataSource1″ runat=”server” ConnectionString=”<%$ ConnectionStrings:LoginCon %>”
SelectCommand=”SELECT [CustomerID], [CompanyName], [ContactName], [Address], [City], [PostalCode], [Phone] FROM [Customers]”>
</asp:SqlDataSource>

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

Create two tables Customers and Orders with the relationship field (Foreign Key) “CustomerID”.
P.S Dont forget to find two images appropriate images

Images arrowright arrowdown


Image from DB as ToolTip in GridView(IE only)

January 9, 2008

Image from DB as ToolTip in GridView(IE only)

In ASPX

<html xmlns=”http://www.w3.org/1999/xhtml&#8221; >
<head id=”Head1″ runat=”server”>
<title>Untitled Page</title>
<script type=”text/javascript”>
<!–
var browserName, browserVersion, isInternetExplorer, theDiv, myPath;
var tempX = 0;
var tempY = 0;
var bFlag = false;

function GetBrowser()
{
browserName=navigator.appName;
browserVersion=parseInt(navigator.appVersion)
isInternetExplorer = (browserName == “Microsoft Internet Explorer”) ? true : false;
}

function DisplayToolTip(row,path)
{
bFlag = true;
myPath = path;
// Set-up to use getMouseXY function onMouseMove
document.onmousemove = getMouseXY;
}

function HideToolTip()
{
bFlag = false;
if (browserVersion >= 4)
{
theDiv.style.visibility = “hidden”;
theDiv.innerHTML =””;
}
}

function getMouseXY(e)
{
if (isInternetExplorer)
{
// grab the x-y pos.s if browser is IE
tempX = event.clientX + document.body.scrollLeft
tempY = event.clientY + document.body.scrollTop
}
else
{
// grab the x-y pos.s if browser is NS
tempX = e.pageX
tempY = e.pageY
}
// catch possible negative values in NS4
if (tempX < 0){tempX = 0}
if (tempY < 0){tempY = 0}
if (browserVersion >= 4 && bFlag)
{
theDiv =document.getElementById(“picdiv”);
theDiv.innerHTML = ‘<img src=’ + myPath + ‘ height=”30px” width=”30px”/>’;
theDiv.style.top = tempY + ‘px’;
theDiv.style.left = tempX + ‘px’;
theDiv.style.visibility = “visible”;
}
}
window.onresize=GetBrowser;

//–>
</script>
</head>

<body onload=”GetBrowser();”>
<form id=”form1″ runat=”server”>
<div>
<div id=”picdiv” style=”position: absolute; visibility: hidden; width:30px”>
</div>
<table style=”margin-left:auto;margin-right:auto;”>
<tr>
<td>
<asp:GridView ID=”GridView1″ runat=”server”
OnRowDataBound=”GridView1_RowDataBound”>
</asp:GridView>
</td>
</tr>
</table>
</div>
</form>
</body>

</html>

In ASPX.CS

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

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

DataRow dr = table.NewRow();
dr[“booktitle”] = “aaaaa”;
dr[“tooltip”] = “AJAX.gif”;
table.Rows.Add(dr);

dr = table.NewRow();
dr[“booktitle”] = “sheldon”;
dr[“tooltip”] = “Image/sheldon.jpg”;
table.Rows.Add(dr);

dr = table.NewRow();
dr[“booktitle”] = “archer”;
dr[“tooltip”] = “Image/archer.jpg”;
table.Rows.Add(dr);

dr = table.NewRow();
dr[“booktitle”] = “click”;
dr[“tooltip”] = “Image/click.jpg”;
table.Rows.Add(dr);

this.GridView1.DataSource = table;
GridView1.DataBind();
}

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


To Display Image thats stored as Type Image in DB

January 9, 2008

To Display Image thats stored as Type Image in DB

ASPX Page

<html xmlns=”http://www.w3.org/1999/xhtml&#8221; >
<head runat=”server”>
<title>Untitled Page</title>
</head>
<body>
<form id=”form1″ runat=”server”>
<div>
<asp:GridView ID=”gvwImages” runat=”server”
AutoGenerateColumns=”false”
DataSourceID=”dsImages”>
<%–DataSourceID=”dsImages”–%>
<Columns>

<asp:TemplateField HeaderText=”Name”>
<ItemTemplate>
<%–//field img_name is the name given to image–%>
<asp:Label ID=”lblName” runat=”server” Text='<%#Eval(“img_name”) %>’>
</asp:Label>
</ItemTemplate>
</asp:TemplateField>

<asp:TemplateField HeaderText=”Image”>
<ItemTemplate>
<%–//here field img_id is the id of the image–%>
<asp:Image ID=”Image1″ runat=”server”
ImageUrl='<%# “Handler.ashx?id=” + Eval(“img_id”) %>’ />
</ItemTemplate>
</asp:TemplateField>

</Columns>

</asp:GridView>
<asp:SqlDataSource ID=”dsImages” runat=”server”
ConnectionString='<%$ConnectionStrings: LoginCon %>’
SelectCommand=”Select img_id,img_name from Images”>
</asp:SqlDataSource>
</div>
</form>
</body>
</html>

In Handler.ashx

<%@ WebHandler Language=”C#” Class=”Handler” %>

using System;
using System.Web;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;

public class Handler : IHttpHandler
{

public bool IsReusable
{
get {return false;}
}
public void ProcessRequest(HttpContext context)
{
SqlConnection myConnection = new SqlConnection(ConfigurationManager.ConnectionStrings[“LoginCon”].ConnectionString);
myConnection.Open();
//here field img_data is the content of the image (type image in DB)
//field img_contenttype is the type of the image (optional)
string sql = “Select img_data,img_contenttype from Images where img_id=@ImageId”;
SqlCommand cmd = new SqlCommand(sql, myConnection);
cmd.Parameters.Add(“@ImageId”, SqlDbType.Int).Value = context.Request.QueryString[“id”];
cmd.Prepare();
SqlDataReader dr = cmd.ExecuteReader();
dr.Read();
context.Response.ContentType = dr[“img_contenttype”].ToString();
context.Response.BinaryWrite((byte[])dr[“img_data”]);
}

}


Flip DataSet

January 4, 2008

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


Trim Function in JavaScript

December 26, 2007

function trim(stringToTrim)
{
return stringToTrim.replace(/^\s+|\s+$/g,””);
}


Bind GridView with XML

December 21, 2007

XML File

<?xml version=”1.0″ encoding=”UTF-8″?>
<root>
<fruit id=”1″>
<fid>1</fid>
<fname>Lemons</fname>
<fcolor>Yellow</fcolor>
</fruit>
<fruit id=”2″>
<fid>2</fid>
<fname>Grape</fname>
<fcolor>White</fcolor>
</fruit>
<fruit id=”3″>
<fid>3</fid>
<fname>Grape</fname>
<fcolor>Black</fcolor>
</fruit>
<fruit id=”4″>
<fid>4</fid>
<fname>Banana</fname>
<fcolor>Yellow</fcolor>
</fruit>
</root>

ASPX Page

<asp:GridView ID=”GridView1″ runat=”server”
AutoGenerateColumns=”false”
DataKeyNames=”id”
DataSourceID=”XmlDataSource1″
Width=”60%”
OnRowCancelingEdit=”GridView1_RowCancelingEdit”
OnRowEditing=”GridView1_RowEditing”
OnRowUpdating=”GridView1_RowUpdating”
OnRowDeleting=”GridView1_RowDeleting”>
<Columns>

<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID=”btnEdit” runat=”server”
Text=”Edit”
CommandName=”Edit”>
</asp:LinkButton>
<asp:LinkButton ID=”btnDelete” runat=”server”
Text=”Delete”
CommandName=”Delete”>
</asp:LinkButton>
</ItemTemplate>
<EditItemTemplate>
<asp:LinkButton ID=”btnUpdate” runat=”server”
Text=”Update”
CommandName=”Update”>
</asp:LinkButton>
<asp:LinkButton ID=”btnCancel” runat=”server”
Text=”Cancel”
CommandName=”Cancel”>
</asp:LinkButton>
</EditItemTemplate>
<ItemStyle Width=”10%” />
</asp:TemplateField>

<asp:TemplateField HeaderText=”ID”>
<ItemTemplate>
<asp:Label ID=”lblID” runat=”server”
Text='<%# XPathBinder.Eval(Container.DataItem, “fid”)%>’>
</asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID=”txtID” runat=”server”
Text='<%# XPathBinder.Eval(Container.DataItem, “fid”)%>’>
</asp:TextBox>
</EditItemTemplate>
<ItemStyle Width=”30%” />
</asp:TemplateField>

<asp:TemplateField HeaderText=”Name”>
<ItemTemplate>
<asp:Label ID=”lblName” runat=”server”
Text='<%# XPathBinder.Eval(Container.DataItem, “fname”)%>’>
</asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID=”txtName” runat=”server”
Text='<%# XPathBinder.Eval(Container.DataItem, “fname”)%>’>
</asp:TextBox>
</EditItemTemplate>
<ItemStyle Width=”30%” />
</asp:TemplateField>

<asp:TemplateField HeaderText=”Colour”>
<ItemTemplate>
<asp:Label ID=”lblColor” runat=”server”
Text='<%# XPathBinder.Eval(Container.DataItem, “fcolor”)%>’>
</asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID=”txtColor” runat=”server”
Text='<%# XPathBinder.Eval(Container.DataItem, “fcolor”)%>’>
</asp:TextBox>
</EditItemTemplate>
<ItemStyle Width=”30%” />
</asp:TemplateField>

</Columns>
<HeaderStyle ForeColor=”White” BackColor=”DarkGreen” />
</asp:GridView>
<asp:XmlDataSource ID=”XmlDataSource1″ runat=”server”
DataFile=”~/App_Data/myData.xml”
XPath= “root/fruit”>
</asp:XmlDataSource>

ASPX.CS

#region “GridView Events”

#region “Edit Events”

#region “Row Editing Event”

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

#endregion

#region “Row Updating Event”

protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
string myID = GridView1.DataKeys[e.RowIndex].Value.ToString();
string fruitID = ((TextBox)GridView1.Rows[e.RowIndex].FindControl(“txtID”)).Text;
string fruitName = ((TextBox)GridView1.Rows[e.RowIndex].FindControl(“txtName”)).Text;
string fruitColor = ((TextBox)GridView1.Rows[e.RowIndex].FindControl(“txtColor”)).Text;
XmlDocument xmlDoc = XmlDataSource1.GetXmlDocument();
XmlNodeList nodeList = xmlDoc.SelectNodes(“root/fruit[@id='” + myID + “‘]”);
nodeList[0].ChildNodes[0].InnerText = fruitID;
nodeList[0].ChildNodes[1].InnerText = fruitName;
nodeList[0].ChildNodes[2].InnerText = fruitColor;
//xmlDoc.Save(Server.MapPath(“./”)+”/App_Data/hi.xml”);
XmlDataSource1.Save();
GridView1.EditIndex = -1;
e.Cancel = true;
GridView1.DataBind();
}

#endregion

#region “Row Cancelling Edit Event”

protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
GridView1.EditIndex = -1;
GridView1.DataBind();

}

#endregion

#endregion

#region “Deleting Events”

protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
System.Xml.XmlDocument Document = XmlDataSource1.GetXmlDocument();
string myID = GridView1.DataKeys[e.RowIndex].Value.ToString();
System.Xml.XmlNode node = Document.SelectSingleNode(“root/fruit[@id='” + myID + “‘]”);
node.ParentNode.RemoveChild(node);
XmlDataSource1.Save();
e.Cancel = true;
GridView1.DataBind();
}

#endregion

#endregion


Custom Paging and Sorting in a Filtered GridView

December 6, 2007

sprite.ng

ASPX


<html xmlns=”http://www.w3.org/1999/xhtml&#8221; >
<head runat=”server”>
<title>Untitled Page</title>
<link type=”text/css” rel=”Stylesheet” href=”GridStyle.css” />
<script type=”text/javascript” src=”App_Scripts/JScript2.js”>
</script>
</head>
<body>
<form id=”form1″ runat=”server”>
<div>

<table>
<tr>
<td>
Country Name:
</td>
<td>
<asp:TextBox ID=”txtCountries” runat=”server”>
</asp:TextBox>
</td>
<td>
<asp:Button ID=”btnpopulate” runat=”server”
Text=”Populate” OnClick=”btnpopulate_Click”/>
</td>
</tr>
<tr>
<td colspan=”3″>
<asp:GridView ID=”gvwCountries” runat=”server”
AllowPaging=”true”
AllowSorting=”true”
AutoGenerateColumns=”false”
OnRowDataBound=”gvwCountries_RowDataBound”
OnSorting=”gvwCountries_Sorting” >
<EmptyDataTemplate>
No Rows to Display
</EmptyDataTemplate>

<Columns>

<asp:TemplateField HeaderText=”Serial No”>
<ItemTemplate>
<%# Container.DataItemIndex %>
</ItemTemplate>
</asp:TemplateField>

<asp:TemplateField HeaderText=”Country Name” SortExpression=”countryName”>
<ItemTemplate>
<asp:Label ID=”lblCountries” runat=”server”
Text = ‘<%# DataBinder.Eval(Container.DataItem, “countryName”) %>’>
</asp:Label>
</ItemTemplate>
</asp:TemplateField>

</Columns>

<PagerTemplate>
<asp:LinkButton ID=”Btn_Previous” runat=”server”
CommandName=”Previous”
OnCommand=”ChangePage”
Text=”Previous” >
</asp:LinkButton>

Page

<%–<asp:Label ID=”lblCurrentPage” runat=”server”>
</asp:Label>–%>
<asp:DropDownList ID=”ddlPages” runat=”server” AutoPostBack=”true” OnSelectedIndexChanged=”ddlPages_SelectedIndexChanged”>
</asp:DropDownList>

of

<asp:Label ID=”lblTotalPages” runat=”server”>
</asp:Label>

<asp:LinkButton ID=”Btn_Next” runat=”server”
CommandName=”Next”
OnCommand=”ChangePage”
Text=”Next” >
</asp:LinkButton>
</PagerTemplate>

<AlternatingRowStyle CssClass=”altrowstyle” />
<HeaderStyle CssClass=”headerstyle” />
<RowStyle CssClass=”rowstyle” />
<PagerStyle CssClass=”pagerstyle” />

</asp:GridView>
</td>
</tr>
</table>

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

ASPX.CS
#region “Local Variables and Declarations”

SqlParameter[] parmCountries = new SqlParameter[10];
protected static int currentPageNumber = 1;
private const int PAGE_SIZE = 10;
int parmCount = 3;
DataSet ds = new DataSet();
DataTable dt = new DataTable();

#endregion

#region “Page Load Events”

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

}
}

#endregion

#region “Populate Button Events”

protected void btnpopulate_Click(object sender, EventArgs e)
{
currentPageNumber = 1;
BindGrid();
}

#endregion

#region “GridView Events”

protected void gvwCountries_RowDataBound(object sender, GridViewRowEventArgs e)
{
string mySortExpression = (Session[“mySortExpression”] != null ? Session[“mySortExpression”].ToString() : “”);
GridView gridView = (GridView)sender;
if (mySortExpression.Length > 0)
{
int cellIndex = -1;
foreach (DataControlField field in gridView.Columns)
{
if (field.SortExpression == mySortExpression)
{
cellIndex = gridView.Columns.IndexOf(field);
if (e.Row.RowType == DataControlRowType.Header)
{
string mySortDirection = (Session[“mySortDirection”] != null ? Session[“mySortDirection”].ToString() : “”);
e.Row.Cells[cellIndex].CssClass += (mySortDirection == “ASC” ? ” sortascheader” : ” sortdescheader”);
}
else if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Cells[cellIndex].CssClass += (e.Row.RowIndex % 2 == 0 ? ” sortaltrow” : “sortrow”);
}
break;
}
}
}
}

protected void gvwCountries_Sorting(object sender, GridViewSortEventArgs e)
{
Session[“mySortExpression”] = e.SortExpression;
DataView dataView = new DataView(GetMyDataTable());
dataView.Sort = e.SortExpression + ” ” + GetSortDirection(e.SortExpression);
gvwCountries.DataSource = dataView;
gvwCountries.DataBind();
ActivatePages();
}

#endregion

#region “Custom Functions”

#region “DataBind Events”

public DataTable GetMyDataTable()
{
string strConnection = ConfigurationManager.ConnectionStrings[“LoginCon”].ConnectionString;
SqlConnection myConnection = new SqlConnection(strConnection);
SqlCommand cmdUsers = new SqlCommand(“SP_GetSomeCountries”, myConnection);
cmdUsers.CommandType = CommandType.StoredProcedure;
parmCountries[0] = new SqlParameter(“@startRowIndex”, currentPageNumber);
parmCountries[1] = new SqlParameter(“@maximumRows”, PAGE_SIZE);
parmCountries[2] = new SqlParameter(“@totalRows”, SqlDbType.Int, 4);
parmCountries[2].Direction = ParameterDirection.Output;
if (txtCountries.Text.Trim() != “”)
{
parmCountries[3] = new SqlParameter(“@CountryName”, txtCountries.Text.Trim());
parmCount++;
}
for (int i = 0; i < parmCount; i++)
{
cmdUsers.Parameters.Add(parmCountries[i]);
}
SqlDataAdapter adapUsers = new SqlDataAdapter(cmdUsers);
adapUsers.Fill(dt);
Session[“totalRows”] = (int)cmdUsers.Parameters[“@totalRows”].Value;
return dt;
}

public void BindGrid()
{
gvwCountries.PageSize = PAGE_SIZE;
gvwCountries.DataSource = GetMyDataTable();
gvwCountries.DataBind();
if (Session[“totalRows”].ToString() != “0”)
{
ActivatePages();
}
}

#endregion

#region “Custom Sorting”

protected string GetSortDirection(string sortBy)
{
string sortDir = “ASC”;
if (ViewState[“sortBy”] != null)
{
string sortedBy = ViewState[“sortBy”].ToString();
if (sortedBy == sortBy)
{
sortDir = ” DESC”;
ViewState[“sortBy”] = null;
}
else
{
ViewState[“sortBy”] = sortBy;
}
}
else
{
ViewState[“sortBy”] = sortBy;
}
Session[“mySortDirection”] = sortDir;
return sortDir;
}

#endregion

#region “Custom Paging”

protected void ChangePage(object sender, CommandEventArgs e)
{
Session[“mySortDirection”] = “”;
Session[“mySortExpression”] = “”;
Label lblTotalPages = (Label)gvwCountries.BottomPagerRow.FindControl(“lblTotalPages”);
//Label lblCurrentPage = (Label)gvwCountries.BottomPagerRow.FindControl(“lblCurrentPage”);
DropDownList ddlPage = (DropDownList)gvwCountries.BottomPagerRow.FindControl(“ddlPages”);
currentPageNumber = (e.CommandName == “Previous” ? Int32.Parse(ddlPage.SelectedItem.Text) – 1 : Int32.Parse(ddlPage.SelectedItem.Text) + 1);
Session[“CurrentPageIndex”] = currentPageNumber;
BindGrid();
}

#endregion

#region “Display Pages”

public void ActivatePages()
{
GridViewRow gvrPager = gvwCountries.BottomPagerRow;
gvrPager.Visible = true;
double totalRows = Convert.ToInt32(Session[“totalRows”].ToString());
LinkButton Btn_Previous = (LinkButton)gvrPager.FindControl(“Btn_Previous”);
LinkButton Btn_Next = (LinkButton)gvrPager.FindControl(“Btn_Next”);
Label lblTotalPages = (Label)gvrPager.FindControl(“lblTotalPages”);
DropDownList ddlPage = (DropDownList)gvrPager.FindControl(“ddlPages”);
//Label lblCurrentPage = (Label)gvrPager.FindControl(“lblCurrentPage”);
lblTotalPages.Text = Convert.ToString(Math.Ceiling(totalRows / PAGE_SIZE));
for (int i = 1; i <= Convert.ToInt32(lblTotalPages.Text); i++)
{
ddlPage.Items.Add(new ListItem(i.ToString()));
}
//lblCurrentPage.Text = currentPageNumber.ToString();
ddlPage.Items.FindByText(currentPageNumber.ToString()).Selected = true;
if (currentPageNumber == 1)
{
Btn_Previous.Enabled = false;
Btn_Next.Enabled = (Int32.Parse(lblTotalPages.Text) > 1 ? true : false);
}
else
{
Btn_Previous.Enabled = true;
Btn_Next.Enabled = (currentPageNumber == Int32.Parse(lblTotalPages.Text) ? false : true);
}
}

#endregion

#endregion

protected void ddlPages_SelectedIndexChanged(object sender, EventArgs e)
{
DropDownList ddl =(DropDownList)sender;
currentPageNumber = Convert.ToInt32(ddl.SelectedItem.Text);
BindGrid();
}

SP

ALTER PROCEDURE [SP_GetSomeCountries]
@startRowIndex int,
@maximumRows int,
@totalRows int OUTPUT

AS

DECLARE @first_id int

SET @startRowIndex = (@startRowIndex – 1) * @maximumRows + 1

IF @startRowIndex = 0
SET @startRowIndex = 1

SET ROWCOUNT @startRowIndex

SELECT @first_id = countryID FROM tbl_Countries

SET ROWCOUNT @maximumRows

SELECT countryID, countryName FROM tbl_Countries WHERE
(countryID >= @first_id )
SET ROWCOUNT 0

— GEt the total rows

SELECT @totalRows = COUNT(countryID) FROM tbl_Countries

StyleSheet

.tablestyle
{
font-family: arial;
font-size: small;
border: solid 1px #7f7f7f;
}

.altrowstyle
{
background-color: #edf5ff;
}

.headerstyle th
{
background: url(img/sprite.png) repeat-x 0px 0px;
border-color: #989898 #cbcbcb #989898 #989898;
border-style: solid solid solid none;
border-width: 1px 1px 1px medium;
color: #000;
padding: 4px 5px 4px 10px;
text-align: center;
vertical-align: bottom;
}

.headerstyle th a
{
font-weight: normal;
text-decoration: none;
text-align: center;
color: #000;
display: block;
padding-right: 10px;
}

.rowstyle .sortaltrow, .altrowstyle .sortaltrow
{
background-color: #edf5ff;
}

.rowstyle .sortrow, .altrowstyle .sortrow
{
background-color: #dbeaff;
}

.rowstyle td, .altrowstyle td
{
padding: 4px 10px 4px 10px;
border-right: solid 1px #cbcbcb;
}

.headerstyle .sortascheader
{
background: url(img/sprite.png) repeat-x 0px -100px;
}

.headerstyle .sortascheader a
{
background: url(img/dt-arrow-up.png) no-repeat right 50%;
}

.headerstyle .sortdescheader
{
background: url(img/sprite.png) repeat-x 0px -100px;
}

.headerstyle .sortdescheader a
{
background: url(img/dt-arrow-dn.png) no-repeat right 50%;
}

.pagerstyle
{
background: url(img/sprite.png) repeat-x 0px 0px;
border-color: #989898 #cbcbcb #989898 #989898;
border-style: solid solid solid none;
border-width: 1px 1px 1px medium;
color: #000;
padding: 4px 5px 4px 10px;
text-align: center;
vertical-align: bottom;
}


MultiDelete in GridView

December 4, 2007

MultiDeleting using CheckBox in ItemTemplate and DeleteButton outside GridView

In ASPX:

<table><tr><td align=”left”><asp:Button ID=”btnDelete” runat=”server” Text=”Delete” OnClick=”btnDelete_Click” /> </td>

</tr><tr><td><asp:GridView ID=”gvwCountries” runat=”server”

AutoGenerateColumns=”false”DataKeyNames=”countryID” ><Columns><asp:TemplateField>

<ItemTemplate><asp:CheckBox ID=”chkCountries” runat=”server” /></ItemTemplate></asp:TemplateField>

<asp:TemplateField><ItemTemplate><asp:Label ID=”lblCountries” runat=”server” Text=’<%# Bind(“countryName”) %>‘></asp:Label>

<input id=”hdnCountryID” type=”hidden” runat=”server” value=’<%# Bind(“countryID”) %> /></ItemTemplate></asp:TemplateField></Columns>

</asp:GridView></td></tr> </table>In ASPX.CS:

string strConn = String.Empty;SqlConnection sqlConn;SqlCommand cmdCountries;SqlDataAdapter adapCountries;DataSet dsCountries = new DataSet();SqlParameter parmCountries = new SqlParameter();protected void Page_Load(object sender, EventArgs e){

if (!IsPostBack)BindGrid();}protected void btnDelete_Click(object sender, EventArgs e){bool blnFlag = false;string cScript;

foreach (GridViewRow gvr in gvwCountries.Rows){bool blnIsChecked = ((CheckBox)gvr.FindControl(“chkCountries”)).Checked;int intCountryID = Convert.ToInt32(((HtmlInputHidden)gvr.FindControl(“hdnCountryID”)).Value);if (blnIsChecked){parmCountries = new SqlParameter(“@CountryID”, intCountryID);bool mybln = ExcecuteNonquery(“SP_DeleteCountries”, parmCountries);blnFlag =

true;}}if (!blnFlag){cScript = “<script>alert(‘Please Select atleast one CheckBox’);</script>”;ClientScript.RegisterStartupScript(typeof(Page), “clientscript”, cScript);}BindGrid();}

protected void BindGrid(){strConn = ConfigurationManager.ConnectionStrings[“LoginCon”].ToString();sqlConn = new SqlConnection(strConn);cmdCountries =

new SqlCommand(“Select * from tbl_countries”, sqlConn);adapCountries = new SqlDataAdapter(cmdCountries);adapCountries.Fill(dsCountries);gvwCountries.DataSource = dsCountries;gvwCountries.DataBind();

}

protected bool ExcecuteNonquery(string strSql, SqlParameter sqlParm){SqlConnection sqlConn = new SqlConnection(ConfigurationManager.ConnectionStrings[“LoginCon”].ToString());SqlCommand cmd;try{sqlConn.Open();cmd =

new SqlCommand(strSql);cmd.Connection = sqlConn;cmd.CommandType = CommandType.StoredProcedure;cmd.Parameters.Add(sqlParm);cmd.ExecuteNonQuery();if (cmd != null) cmd.Dispose();sqlConn.Close();

return true;}catch (Exception ex){return false;}}The SP:

CREATE PROCEDURE dbo.SP_DeleteCountries(@CountryID int

)ASBEGIN DELETE FROM [tbl_Countries] where [countryID] = @CountryIDEND


close a child window and refresh the parent window

November 22, 2007

Parent page (page_load):

string script = @
function setSearchText(theText)
{
    textBox=document.getElementById({0}).value=theText;
}
;

this.ClientScript.RegisterClientScriptBlock(this.GetType(), “setSearchText”, string.Format(script,EncodeJsString(txtItemSearch.ClientID)),true);

Child page (the usual place..):

 string script = @” if (window.opener && window.opener.setSearchText)
{
    window.opener.setSearchText({0});
}
window.close();
;

this.ClientScript.RegisterClientScriptBlock(this.GetType(), “setSearchText”, string.Format(script,EncodeJsString(row.Cells[0].Text)),true);

public static string EncodeJsString(string s)
{
    StringBuilder sb = new StringBuilder();
    sb.Append(“\””);
    foreach (char c in s)
    {
        switch (c)
        {
            case ‘\”‘:
               sb.Append(“\\\””);
                break;
            case ‘\\’:
                sb.Append(“\\\\”);
                break;
            case ‘\b’:
                sb.Append(“\\b”);
                break;
            case ‘\f’:
                sb.Append(“\\f”);
                break;
            case ‘\n’:
                sb.Append(“\\n”);
                break;
            case ‘\r’:
                sb.Append(“\\r”);
                break;
            case ‘\t’:
                sb.Append(“\\t”);
                break;
            default:
                int i = (int)c;
                if (i < 32 || i > 127)
                {
                    sb.AppendFormat(“\\u{0:X04}”, i);
                }
                else
                {
                    sb.Append(c);
                }
                break;
        }
    }
    sb.Append(“\””);

    return sb.ToString();
}