Friday, August 29, 2008

Creating the List of Drives in the TreeView Control


you can see the code that uses the static GeTDrives method of the DriveInfo class to get a list of all installed drives, then iterates through them. For each fixed, formatted, and available (ready) drive, the code creates a new node containing details of the drive. It then sets the ImageUrl to the custom image, specifies that clicking this node will cause a postback that executes the "populate on demand" event handler, and adds the node to the treeView.



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

<!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:TreeView ID="treeDir" runat="Server">
</asp:TreeView>
<asp:Label ID="lblError" 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;
using System.Text;
using System.IO;

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

}
private void CreateTreeView()
{
treeDir.Nodes.Clear();
TreeNode node = new TreeNode("My Computer", "Root");
node.SelectAction = TreeNodeSelectAction.None;
node.Expanded = true;
treeDir.Nodes.Add(node);
try
{
// get a list of installed drives
DriveInfo[] allDrives = DriveInfo.GetDrives();
foreach (DriveInfo d in allDrives)
{
// only include fixed drives that are ready
if (d.DriveType == DriveType.Fixed && d.IsReady)
{
// create text for the TreeView to display
StringBuilder sb = new StringBuilder();
sb.Append(d.Name.Substring(0, 2));
sb.Append(" ");
sb.Append(d.VolumeLabel);
sb.Append(" (");
sb.Append(d.DriveFormat);
sb.Append(") ");
Double space = d.AvailableFreeSpace / 1024 / 1024;
sb.Append(space.ToString("#,###,###,##0"));
sb.Append(" MB available");
String theName = sb.ToString();
String theValue = d.Name;
// add a node to the TreeView with "drive" image
TreeNode child = new TreeNode(theName, theValue);
child.ImageUrl = "images/icon_drive.gif";
// specify postback for populating child nodes
child.SelectAction = TreeNodeSelectAction.Expand;
child.PopulateOnDemand = true;
node.ChildNodes.Add(child);
}
}
}
catch (Exception ex)
{
lblError.Text = "ERROR: " + ex.Message + "<p />";
}
}

}

Thursday, August 28, 2008

How to: Create Templated ASP.NET User Controls



Another feature that is often ignored with user controls, but that can be very useful, is the template. Templates are often associated with server controls and are an important part of both the DataList and the Repeater controls. However, their usefulness is not limited to server controls. Templates, however, allow us to provide a means for the page designer to supply HTML content that will be rendered within our control. Templates allow our user controls to be more flexible because they are used across pages within our application.

1. In the .ascx file, add an ASP.NET PlaceHolder control where you want the template to appear.

2. In the user control's code, implement a property of type ITemplate.

3. Define a server control class that implements the INamingContainer interface as a container in which to create an instance of the template. This is called the template's naming container.

4. Apply the TemplateContainerAttribute to the property that implements ITemplate and pass the type of the template's naming container as the argument to the attribute's constructor.

5. In the control's Init method, repeat the following steps one or more times:

o Create an instance of the naming container class.

o Create an instance of the template in the naming container.

o Add the naming container instance to the Controls property of the PlaceHolder server control.


SupportTemplates.ascx



<%@ Control Language="C#" AutoEventWireup="true" CodeFile="SupportTemplates.ascx.cs"
Inherits="SupportTemplates" %>

<table>
<tr>
<td>
<asp:PlaceHolder ID="headerContainer" runat="server"></asp:PlaceHolder>
</td>
</tr>
<tr>
<td>
<i>This is the static content that always appears on the control</i><br />
<asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder>
</td>
</tr>
<tr>
<td>
<asp:PlaceHolder ID="footerContainer" runat="server"></asp:PlaceHolder>
</td>
</tr>
</table>
SupportTemplates.ascx.cs

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.ComponentModel;
public partial class SupportTemplates : System.Web.UI.UserControl
{
private ITemplate messageTemplate = null;

[TemplateContainer(typeof(MessageContainer))]
[PersistenceMode(PersistenceMode.InnerProperty)]
public ITemplate MessageTemplate
{
get
{
return messageTemplate;
}
set
{
messageTemplate = value;
}
}
protected ITemplate _footerTemplate;
protected ITemplate _headerTemplate;
[TemplateContainer(typeof(MessageContainer))]
[PersistenceMode(PersistenceMode.InnerProperty)]
public ITemplate FooterTemplate
{
get { return _footerTemplate; }
set { _footerTemplate = value; }
}
[TemplateContainer(typeof(MessageContainer))]
[PersistenceMode(PersistenceMode.InnerProperty)]
public ITemplate HeaderTemplate
{
get { return _headerTemplate; }
set { _headerTemplate = value; }
}

private void Page_PreRender(object sender, System.EventArgs e)
{
if (_headerTemplate != null)
_headerTemplate.InstantiateIn(headerContainer);
if (_footerTemplate != null)
_footerTemplate.InstantiateIn(footerContainer);
}

void Page_Init()
{
if (messageTemplate != null)
{
String[] fruits = { "apple", "orange", "banana", "pineapple" };
for (int i = 0; i < 4; i++)
{
MessageContainer container = new MessageContainer(i, fruits[i]);
messageTemplate.InstantiateIn(container);
PlaceHolder1.Controls.Add(container);
}
}
}

public class MessageContainer : Control, INamingContainer
{
private int m_index;
private String m_message;
internal MessageContainer(int index, String message)
{
m_index = index;
m_message = message;
}
public int Index
{
get
{
return m_index;
}
}
public String Message
{
get
{
return m_message;
}
}
}


}
How To Use


TemplateDemo.aspx

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

<%@ Register Src="SupportTemplates.ascx" TagName="SupportTemplates" TagPrefix="uc2" %>
<!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>
<uc2:SupportTemplates ID="SupportTemplates1" runat="server">
<HeaderTemplate>
<b>This is Header</b>
</HeaderTemplate>
<MessageTemplate>
Index:
<asp:Label runat="server" ID="Label1" Text='<%# Container.Index %>' />
<br />
Message:
<asp:Label runat="server" ID="Label2" Text='<%# Container.Message %>' />
<hr />
</MessageTemplate>
<FooterTemplate>
<b>This Is Footer</b>
</FooterTemplate>
</uc2:SupportTemplates>
</div>
</form>
</body>
</html>

TemplateDemo.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 Template : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
this.DataBind();
}
}

How To Display vertical record in GridView




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

<!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 VerticalData : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{


GridView1.DataSource = GoDoReShape(_sampleData);
GridView1.DataBind();
}

}
public DataTable _sampleData
{
get
{
DataTable dt = (DataTable)Session["DataTable"];
if (dt == null)
{
dt = new DataTable();
dt.Columns.Add(new DataColumn("ID", typeof(string)));
dt.Columns.Add(new DataColumn("Item", typeof(string)));
dt.Columns.Add(new DataColumn("Price", typeof(string)));


dt.Rows.Add(new object[] { "1", "Product1", "12.43", });
dt.Rows.Add(new object[] { "2", "Product2", "11.43", });
dt.Rows.Add(new object[] { "3", "Product3", "13.43", });
Session["DataTable"] = dt;
}
return dt;
}
set
{
Session["DataTable"] = value;
}
}
public DataTable GoDoReShape(DataTable dt)
{
DataTable NewDt = new DataTable();
//Create Two Columns with names "ColumnName" and "Value"
//ColumnName -> Displays all ColumnNames
//Value -> Displays ColumnData
NewDt.Columns.Add("ColumnName");
NewDt.Columns.Add("Value");
foreach (DataRow dr in dt.Rows)
{
foreach (System.Data.DataColumn dcol in dt.Columns)
{
//Declare Array
string[] MyArray ={ dcol.ColumnName.ToString(), dr[dcol.ColumnName.ToString()].ToString() };
NewDt.Rows.Add(MyArray);
}
}
return NewDt;
}



}

Using the RegisterArrayDeclaration Method


Let's create a simple Web page to demonstrate the RegisterArrayDeclaration method. This page provides a slide show where the client-side JavaScript changes the image. In this example, we will search a specified folder on the server and load the names of all the images in a JavaScript array. We will also provide two buttons, one for showing the next image from the list and another for showing the previous one



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


<!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">
var curPic = 0;

function processPrevious()
{
if (curPic==0)
{
curPic=Pictures.length - 1;
}
else
{
curPic--;
}
document.getElementById('<%=myPicture.ClientID%>').src=Pictures[curPic];
}

function processNext()
{
if (curPic==Pictures.length -1)
{
curPic=0;
}
else
{
curPic++;
}
document.getElementById('<%=myPicture.ClientID%>').src=Pictures[curPic];
}
</script>

</head>
<body>
<form id="form1" runat="server">
<div>
<table border="1">
<tr>
<td>
<asp:Image ID="myPicture" runat="Server" Height="500px" Width="600px" />
</td>
</tr>
<tr>
<td>
<asp:Button ID="BackButton" runat="Server" Text="Back" />
<asp:Button ID="NextButton" runat="Server" Text="Previous" />
</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;
using System.Text;
using System.IO;

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

StringBuilder imageArray = new StringBuilder();
// The GetImageArray method searches the Images
// folder and returns a JavaScript array declaration
// for all files contained in the folder.

imageArray = GetImageArray("Image");
// Once we have the array declaration, we simply add it
// to the page by using the RegisterArrayDeclaration method.
// The name of the JavaScript array will be Pictures,
// as specified in the first parameter.

ClientScript.RegisterArrayDeclaration("Pictures", imageArray.ToString());
// Wiring the Back button's click event to
// the processPrevious function. Make sure to
// return false in order to disable post-back operation.

BackButton.Attributes.Add("onClick", "processPrevious();return false;");

//Wiring the Next button's click event to
// the processNext function. Make sure to
// return false in order to disable post-back operation.

NextButton.Attributes.Add("onClick", "processNext();return false;");

}
}
// This function receives a folder name and returns a
// JavaScript array declaration containing names of all files
// from the folder.

protected StringBuilder GetImageArray(string folderName)
{


string Path;
DirectoryInfo Folder;

FileInfo[] Images;
StringBuilder ImageArray = new StringBuilder();

Path = Request.PhysicalApplicationPath + folderName;
Folder = new DirectoryInfo(Path);
Images = Folder.GetFiles();

// Looping through all files in the folder and generating
// a JavaScript array declaration.
foreach (FileInfo Image in Images)
{
ImageArray.AppendFormat("'{0}/{1}',", folderName, Image.Name);
}

// Removing the unwanted last comma.
ImageArray.Remove(ImageArray.Length - 1, 1);

return ImageArray;
}


}

How to hide and show data in the DataList?



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

<!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:DataList runat="server" ID="Datalist1" Font-Size="10pt"
Font-Name="Verdana" OnItemCommand="Datalist1_ItemCommand">
<ItemTemplate>
<asp:LinkButton Style="text-decoration: none" runat="server" ID="btnDetails" Text="+"
CommandName="Show" Font-Name="Verdana" />
<b>
<%# DataBinder.Eval(Container.DataItem, "Id") %>
</b>
<br />
<asp:Label ID="lblEID" Visible="False" runat="Server" Text='<%# DataBinder.Eval(Container.DataItem, "ID") %>' />
<asp:DataGrid runat="server" ID="Datagrid1" Font-Name="Verdana" Font-Size="10pt"
HorizontalAlign="Center" Visible="False" Width="85%"/>
</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 DataListHide : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{

Datalist1.DataSource = CreateDS();
Datalist1.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 Datalist1_ItemCommand(object source, DataListCommandEventArgs e)
{
if (e.CommandName == "Show")
{
Label EmpIDlabel = (Label)e.Item.FindControl("lblEID");
string strEmpID = EmpIDlabel.Text;
((DataGrid)e.Item.FindControl("Datagrid1")).DataSource = GetEmpDetails(strEmpID);
((DataGrid)e.Item.FindControl("Datagrid1")).DataBind();
((DataGrid)e.Item.FindControl("Datagrid1")).Visible = true;
((LinkButton)e.Item.FindControl("btnDetails")).Text = "-";
((LinkButton)e.Item.FindControl("btnDetails")).CommandName = "Hide";
}
if (e.CommandName == "Hide")
{
((DataGrid)e.Item.FindControl("Datagrid1")).Visible = false;
((LinkButton)e.Item.FindControl("btnDetails")).Text = "+";
((LinkButton)e.Item.FindControl("btnDetails")).CommandName = "Show";
}
}
protected DataView GetEmpDetails(string id)
{

DataSet ds = CreateDS() as DataSet;
DataView dv = ds.Tables[1].DefaultView;
dv.RowFilter = "CompanyID=" + id;
return dv;

}


}

How To change the background image of html table placed in gridview's template field.




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

<!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" AutoGenerateColumns="true" runat="Server" OnRowDataBound="GridView1_RowDataBound1">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<table id="myTable" runat="server" width="200px" height="150px">
<tr>
<td>
<asp:Label ID="lblName" runat="Server" Text='<%#Eval("Name")%>'></asp:Label>
</td>
</tr>
</table>
</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;
using System.Collections.Generic;

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

if (!IsPostBack)
{
List<dataStruct> mylist = new List<dataStruct>();

mylist.Add(new dataStruct(new DateTime(1982, 01, 01), "Bill", 'm'));
mylist.Add(new dataStruct(new DateTime(1981, 01, 01), "Philip", 'm'));
mylist.Add(new dataStruct(new DateTime(1980, 01, 01), "Susan", 'f'));

GridView1.DataSource = mylist;
GridView1.DataBind();
}

}

public struct dataStruct
{

private DateTime birthdate;
private string name;
private char sex;
public DateTime BirthDate
{
get { return birthdate; }
set { birthdate = value; }
}

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

public char Sex
{
get { return sex; }
set { sex = value; }
}


public dataStruct(DateTime _birthdate, string _name, char _sex)
{

this.birthdate = _birthdate;
this.name = _name;
this.sex = _sex;
}
}

protected void GridView1_RowDataBound1(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
HtmlTable tbl = (HtmlTable)e.Row.FindControl("myTable");
if (tbl != null)
{
if (((Label)tbl.FindControl("lblName")).Text == "Bill")
{
tbl.Attributes.Add("style", "color:red;background-color:green;height:50px);");
}
else if (((Label)tbl.FindControl("lblName")).Text == "Philip")
{
tbl.Attributes.Add("style", "background-image:url(images/pdf-icon.jpg);");
}
else
{
tbl.Attributes.Add("style", "background-image:url(images/mime_text.png);");
}

}
}

}
}

Wednesday, August 27, 2008

Adding/Using Embedded Resources in .Net Web Application/Class Library (C#/VB.Net/ASP.Net)




In .Net when you don’t want to relay for a file on physical location, then it is very good option to take an advantage of Embedded resources.

Using embedded resources you can add any file type in the assembly/DLL/EXE when they get compiled. And whenever you want to use it, load it from the assembly, the files get stored in the metadata of Assembly.

Here is an example of how to use Embedded Resources.

1.
Open Microsoft Visual Studio and create new project for C# Windows Application, here I have created Windows Application named “EmbeddedTest”, even you can use “Class Library” 2.
To add a file in the project Right click on the project name in Solution Explorer, select “Add” >> “Existing Item…”

3.
Now we have added a file to the project, so it doesn’t mean that it will automatically embedded in the Assembly, for that we need to change the files “Build Action” property to “Embedded Resource”, and compiler will include this file in metatdata. Here I have added Image file(blue.jpg), you can add one or more any kind of files






Now use the following code in Form1_Load method to list all the Embedded Resources available in the Assembly



protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
string[] resources = ImageLibrary.Images.GetNames();

foreach (string resourceName in resources)
{
ListBox1.Items.Add(resourceName);
}
}
}
5.
The following code is used to get the resource from the Manifest of the Assembly when user clicks on the listBox1



protected void ListBox1_SelectedIndexChanged(object sender, EventArgs e)
{
if (ListBox1.SelectedIndex == -1)
return;

string selectedResourceName = ListBox1.SelectedItem.ToString();

System.Drawing.Image img = ImageLibrary.Images.GetImageByResourceName(selectedResourceName);
if (img != null)
{
System.Drawing.Bitmap obj = new System.Drawing.Bitmap(img);
Response.ContentType = "image/gif";


obj.Save(Response.OutputStream, System.Drawing.Imaging.ImageFormat.Gif);

}
else
{


}


}
complete code



using System;
using System.Collections.Generic;
using System.Text;
using System.Drawing;
using System.Reflection;

using System.IO;

namespace ImageLibrary
{
public class Images
{
public static string[] GetNames()
{
Assembly a = Assembly.GetExecutingAssembly();

return a.GetManifestResourceNames();
}

public static Image GetImageByResourceName(string resourceName)
{
Assembly a = Assembly.GetExecutingAssembly();

try
{
Stream stream = a.GetManifestResourceStream(resourceName);

return Bitmap.FromStream(stream) as Bitmap;
}
catch (Exception ex)
{
return null;
}
}
}
}





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

<!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 style="width: 100%">
<tr>
<td style="width: 100px">
<asp:ListBox ID="ListBox1" runat="server" AutoPostBack="True" OnSelectedIndexChanged="ListBox1_SelectedIndexChanged">
</asp:ListBox></td>
<td style="width: 100px">
</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 EmbeedTest : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
string[] resources = ImageLibrary.Images.GetNames();

foreach (string resourceName in resources)
{
ListBox1.Items.Add(resourceName);
}
}
}
protected void ListBox1_SelectedIndexChanged(object sender, EventArgs e)
{
if (ListBox1.SelectedIndex == -1)
return;

string selectedResourceName = ListBox1.SelectedItem.ToString();

System.Drawing.Image img = ImageLibrary.Images.GetImageByResourceName(selectedResourceName);
if (img != null)
{
System.Drawing.Bitmap obj = new System.Drawing.Bitmap(img);
Response.ContentType = "image/gif";


obj.Save(Response.OutputStream, System.Drawing.Imaging.ImageFormat.Gif);

}
else
{


}


}
}

How To Use Out Parameter



<%@ Page Language="C#" %>
<script runat="server">

void Page_Load()
{
int a = 1;
int b;
Increment(a, out b);
lblMessage.Text = b.ToString();
}

void Increment(int Number, out int Result)
{
Result = Number + 1;
}

</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Demonstration of using out Parameters</title>
</head>
<body>
<form id="form1" runat="server">

<asp:Label id="lblMessage" runat="server"></asp:Label>


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

Working with postback of dropdown list inside Gridview


Many a times there are circumstances where by we need to use dropdown list inside a Gridview and also handle the index changed event of the dropdown list. The easy example of this kind of requirement would be when we nee to fill another dropdown list in the same row from the value selected in the first dropdown list.

We all know that the dropdown list does not support command name property so you cannot handle the event in the row command event.

A simple solution to the problem is to use the namingcontainer in the selectedindexchanged event and get the reference of the parent row view. After that we can do what we want from the row view. Here is an example in the code.




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


<!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="Publisher">
<ItemTemplate>
<asp:DropDownList ID="ddlPub" runat="Server" AutoPostBack="true" OnSelectedIndexChanged="ddlPub_SelectedIndexChanged"
DataSource='<%#GetCustomMadeDataTable()%>' DataTextField="Publisher">
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Title">
<ItemTemplate>
<asp:DropDownList ID="ddlTitle" runat="Server">
</asp:DropDownList>
</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 GridViewDropDown : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindGridViewView();
this.DataBind();
}
}
private void BindGridViewView()
{
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("ISBN", typeof(int));
objDataTable.Columns.Add("Title", typeof(string));
objDataTable.Columns.Add("Publisher", typeof(string));
objDataTable.Columns.Add("Year", typeof(string));
DataColumn[] dcPk = new DataColumn[1];
dcPk[0] = objDataTable.Columns["ISBN"];
objDataTable.PrimaryKey = dcPk;
objDataTable.Columns["ISBN"].AutoIncrement = true;
objDataTable.Columns["ISBN"].AutoIncrementSeed = 1;
//Adding some data in the rows of this DataTable
DataRow dr;
for (int i = 1; i <= 5; i++)
{
dr = objDataTable.NewRow();
dr[1] = "Title" + i.ToString();
dr[2] = "Publisher" + i.ToString();
dr[3] = "200" + i.ToString();
objDataTable.Rows.Add(dr);
}
for (int i = 6; i <= 8; i++)
{
dr = objDataTable.NewRow();
dr[1] = "Computer" + i.ToString();
dr[2] = "TMH" + i.ToString();
dr[3] = "200" + i.ToString();
objDataTable.Rows.Add(dr);
}
Session["strTemp"] = objDataTable;
return objDataTable;
}

protected ArrayList RelatedData(string s)
{
ArrayList ar = new ArrayList();
if (s == "Publisher1")
{

ar.Add("Book1");
ar.Add("Book2");


}
if (s == "Publisher2")
{

ar.Add("Computer");
ar.Add("C#");

}
return ar;
}
protected void ddlPub_SelectedIndexChanged(object sender, EventArgs e)
{
// get reference to the row
GridViewRow gvr = (GridViewRow)(((Control)sender).NamingContainer);

// Get the reference of this DropDownlist
DropDownList dropdownlist1 = (DropDownList)gvr.FindControl("ddlPub");

// Get the reference of other DropDownlist in the same row.
DropDownList ddlParagraph = (DropDownList)gvr.FindControl("ddlTitle");

string strValue = dropdownlist1.SelectedItem.Text;
ddlParagraph.DataSource = RelatedData(strValue);
ddlParagraph.DataBind();
}
}

Tuesday, August 26, 2008

How To Create your Own Custom Events

In this post i will show how to extend EventArgs class.

1) Create your custom event args class derived from System.EventArgs
2) Declare your delegate with two parameters, object source and YourEventArgsClass e.
3) Create a protected virtual method that fires the event for you (its protected and virtual so that deriving class can see the method and also override it if they wish to change how and when the event is fired)





using System;

public class MyEventArgs : System.EventArgs
{
private bool m_OldValue;
private bool m_NewValue;

public MyEventArgs(bool oldVal, bool newVal)
{
this.m_OldValue = oldVal;
this.m_NewValue = newVal;
}

public bool OldValue
{
get { return this.m_OldValue; }
}

public bool NewValue
{
get { return this.m_NewValue; }
}
}
public class MyClass
{
public delegate void ValueChangedHandler(object source, MyEventArgs e);
public event ValueChangedHandler ValueChanged;

private bool m_MyBool = false;

public MyClass() { }

public void SomeMethod()
{
this.MyBool = true;
}

public bool MyBool
{
get { return this.m_MyBool; }
set
{
//Now call our virtual method, with the old and new value (this fires the event for us)
this.OnValueChanged(new MyEventArgs(this.m_MyBool, value));
this.m_MyBool = value;
}
}

protected virtual void OnValueChanged(MyEventArgs e)
{
this.ValueChanged(this, e);
}
}

class Test
{


public static void Main()
{

MyClass obj = new MyClass();
obj.ValueChanged += new MyClass.ValueChangedHandler(obj_ValueChanged);
obj.SomeMethod();
Console.Read();

}

static void obj_ValueChanged(object source, MyEventArgs e)
{
if (e.NewValue == false)
{
Console.WriteLine("Hi");
Console.Read();
}
else
{
Console.WriteLine("bye");
Console.Read();
}
}

}

UserControl and Event

I will create a new and very simple UserControl, to illustrate how to create events. It won't have a real life purpose, but is only meant to show you how to use events in a UserControl.

First, we create a new, simple EventUserControl, with this code in it:



<%@ Control Language="C#" AutoEventWireup="true" CodeFile="EventUserControl.ascx.cs"
Inherits="EventUserControl" %>

Page title:
<asp:TextBox runat="server" ID="txtPageTitle" />
<asp:Button runat="server" ID="btnUpdatePageTitle" OnClick="btnUpdatePageTitle_Click"
Text="Update" />

All just text and server controls that we know. In the CodeBehind, it looks a bit like this:
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 EventUserControl : System.Web.UI.UserControl
{
private string pageTitle;
public event EventHandler PageTitleUpdated;

protected void btnUpdatePageTitle_Click(object sender, EventArgs e)
{
this.pageTitle = txtPageTitle.Text;
if (PageTitleUpdated != null)
PageTitleUpdated(this, EventArgs.Empty);
}

public string PageTitle
{
get { return pageTitle; }
}
}

We have defined a pageTitle container variable and a property for it. Then we have a new thing, an event. As you can see, it's defined much like any other kind of field, but it is a bit different. The theory about is explained in the C# tutorial, so we won't get into that here. In the Click event of our button, we set the pageTitle field. Then we check if PageTitleUpdated, our event, is null. If it's not, it means that we have subscribed to this event somewhere, and in that case, we send a notification by calling the PageTitleUpdated as a method. As parameters, we send this (a reference to the UserControl it self) as the sender, and an empty EventArgs parameter. This will make sure that all subscribers are notified that the pageTitle has just been updated. Now, in our page, I've declared our UserControl like this:



<%@ Register TagPrefix="My" TagName="EventUserControl" Src="~/EventUserControl.ascx" %>


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


<%@ Register TagPrefix="My" TagName="EventUserControl" Src="~/EventUserControl.ascx" %>
<!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>
<My:EventUserControl runat="server" ID="MyEventUserControl" OnPageTitleUpdated="MyEventUserControl_PageTitleUpdated" />
</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 EventUserControl : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{

}
protected void MyEventUserControl_PageTitleUpdated(object sender, EventArgs e)
{
this.Title = MyEventUserControl.PageTitle;
}

}

IsNumeric C# equivalent

IsNumeric in C#, WHY NOT?

This is something that has bothered me for a long while now. Why doesn't C# have a IsNumeric(string num) function like VB.NET?
I have used every kind of IsNumeric code you van think of... This is what I started with.

public bool IsNumeric(string s)
{
try
{
Int32.Parse(s);
}
catch
{
return false;
}
return true;
}

But we all no the unspoken rule, NEVER use try, catch for functionality... So I tried this.

internal static bool IsNumeric(string numberString)
{
char [] ca = numberString.ToCharArray();
for (int i = 0; i <> if (ca[i] > 57 || ca[i] <> return false;
}
return true;
}

Then I found char.IsNumber: (Why do they have a char.IsNumber, but no string.IsNumeric???)

internal static bool IsNumeric(string numberString)
{
char [] ca = numberString.ToCharArray();
for (int i = 0; i <> if (!char.IsNumber(ca[i]))
return false;
}
return true;
}


public static bool IsNumeric(object Expression)
{
bool isNum;
double retNum;
isNum = Double.TryParse(Convert.ToString(Expression), System.Globalization.NumberStyles.Any,System.Globalization.NumberFormatInfo.InvariantInfo, out retNum );
return isNum;
}

How To Add IsNumneric Function in C#


That's right, you can call VB's IsNumeric() function directly from C#. First add a reference to the Visual Basic compatibility assembly, Microsoft.VisualBasic.dll, which contains the function's implementation:

import namespace
using Microsoft.VisualBasic;




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

<!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 ID="TextBox1" runat="server"></asp:TextBox>
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Button" /></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 Microsoft.VisualBasic;

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

}
protected void Button1_Click(object sender, EventArgs e)
{
string strValue = TextBox1.Text;
if (!Information.IsNumeric(strValue))
{
Label1.Text = "Is Not Numeric";
}
else
{
Label1.Text = "Numeric";

}
}
}

Friday, August 22, 2008

Working With ObjectDataSource And GridView

1. Create Middle Tier class

l Create static, stateless methods

l Mark class and methods with DataObjectMethod attribute (requires using System.ComponentModel)

2. Configure Data Source

· Choose a business object

· Define data methods

3. Configure GridView

· Check “Enable Editing”, etc.


step1.Add a new project in VS.net


step2. Add a class CustomersDataObject in App_Code Folder and add following code





using System;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.IO;
using System.Web;

/// <summary>
/// Summary description for CustomerDataObject
/// </summary>
[DataObject(true)]
public class CustomersDataObject
{
/// <summary>
///
/// </summary>
private DataSet _customers;

/// <summary>
///
/// </summary>
public CustomersDataObject()
{
this._customers = HttpContext.Current.Session["Customers"] as DataSet;

if (this._customers == null)
{
this._customers = new DataSet();
this._customers.ReadXml(HttpContext.Current.Server.MapPath(@"App_Data\customers.xml"));

HttpContext.Current.Session["Customers"] = this._customers;
}
}

/// <summary>
///
/// </summary>
private DataTable CustomerTable
{
get { return this._customers.Tables["customers"]; }
}

/// <summary>
///
/// </summary>
/// <returns></returns>
[DataObjectMethod(DataObjectMethodType.Select)]
public DataView Select()
{
this.CustomerTable.DefaultView.Sort = "CustomerID";
return this.CustomerTable.DefaultView;
}
}
step3 .Place the xml file in App_Data Folder



<?xml version="1.0" encoding="utf-8" ?>
<customers>
<customers>
<CustomerID>ALFKI</CustomerID>
<CompanyName>Alfreds Futterkiste</CompanyName>
<ContactName>Maria Anders</ContactName>
<ContactTitle>Sales Representative</ContactTitle>
<Address>Obere Str. 57</Address>
<City>Berlin</City>
<PostalCode>12209</PostalCode>
<Country>Germany</Country>
<Phone>030-0074321</Phone>
<Fax>030-0076545</Fax>
</customers>
<customers>
<CustomerID>ANATR</CustomerID>
<CompanyName>Ana Trujillo Emparedados y helados</CompanyName>
<ContactName>Ana Trujillo</ContactName>
<ContactTitle>Owner</ContactTitle>
<Address>Avda. de la Constitución 2222</Address>
<City>México D.F.</City>

<PostalCode>05021</PostalCode>
<Country>Mexico</Country>
<Phone>(5) 555-4729</Phone>
<Fax>(5) 555-3745</Fax>
</customers>
<customers>
<CustomerID>ANTON</CustomerID>
<CompanyName>Antonio Moreno Taquería</CompanyName>
<ContactName>Antonio Moreno</ContactName>
<ContactTitle>Owner</ContactTitle>
<Address>Mataderos 2312</Address>
<City>México D.F.</City>
<PostalCode>05023</PostalCode>
<Country>Mexico</Country>
<Phone>(5) 555-3932</Phone>
</customers>
<customers>
<CustomerID>AROUT</CustomerID>
<CompanyName>Around the Horn</CompanyName>
<ContactName>Thomas Hardy</ContactName>
<ContactTitle>Sales Representative</ContactTitle>
<Address>120 Hanover Sq.</Address>
<City>London</City>
<PostalCode>WA1 1DP</PostalCode>
<Country>UK</Country>
<Phone>(171) 555-7788</Phone>
<Fax>(171) 555-6750</Fax>
</customers>
<customers>
<CustomerID>BERGS</CustomerID>
<CompanyName>Berglunds snabbköp</CompanyName>
<ContactName>Christina Berglund</ContactName>
<ContactTitle>Order Administrator</ContactTitle>
<Address>Berguvsvägen 8</Address>
<City>Luleå</City>
<PostalCode>S-958 22</PostalCode>
<Country>Sweden</Country>
<Phone>0921-12 34 65</Phone>
<Fax>0921-12 34 67</Fax>
</customers>
<customers>
<CustomerID>BLAUS</CustomerID>
<CompanyName>Blauer See Delikatessen</CompanyName>
<ContactName>Hanna Moos</ContactName>
<ContactTitle>Sales Representative</ContactTitle>
<Address>Forsterstr. 57</Address>
<City>Mannheim</City>
<PostalCode>68306</PostalCode>
<Country>Germany</Country>
<Phone>0621-08460</Phone>
<Fax>0621-08924</Fax>
</customers>
<customers>
<CustomerID>BLONP</CustomerID>
<CompanyName>Blondesddsl père et fils</CompanyName>
<ContactName>Frédérique Citeaux</ContactName>
<ContactTitle>Marketing Manager</ContactTitle>
<Address>24, place Kléber</Address>
<City>Strasbourg</City>
<PostalCode>67000</PostalCode>
<Country>France</Country>
<Phone>88.60.15.31</Phone>
<Fax>88.60.15.32</Fax>
</customers>
<customers>
<CustomerID>BOLID</CustomerID>
<CompanyName>Bólido Comidas preparadas</CompanyName>
<ContactName>Martín Sommer</ContactName>
<ContactTitle>Owner</ContactTitle>
<Address>C/ Araquil, 67</Address>
<City>Madrid</City>
<PostalCode>28023</PostalCode>
<Country>Spain</Country>
<Phone>(91) 555 22 82</Phone>
<Fax>(91) 555 91 99</Fax>
</customers>
<customers>
<CustomerID>BONAP</CustomerID>
<CompanyName>Bon app'</CompanyName>
<ContactName>Laurence Lebihan</ContactName>
<ContactTitle>Owner</ContactTitle>
<Address>12, rue des Bouchers</Address>
<City>Marseille</City>
<PostalCode>13008</PostalCode>
<Country>France</Country>
<Phone>91.24.45.40</Phone>
<Fax>91.24.45.41</Fax>
</customers>
<customers>
<CustomerID>BOTTM</CustomerID>
<CompanyName>Bottom-Dollar Markets</CompanyName>
<ContactName>Elizabeth Lincoln</ContactName>
<ContactTitle>Accounting Manager</ContactTitle>
<Address>23 Tsawassen Blvd.</Address>
<City>Tsawassen</City>
<Region>BC</Region>
<PostalCode>T2F 8M4</PostalCode>
<Country>Canada</Country>
<Phone>(604) 555-4729</Phone>
<Fax>(604) 555-3745</Fax>
</customers>
<customers>
<CustomerID>BSBEV</CustomerID>
<CompanyName>B's Beverages</CompanyName>
<ContactName>Victoria Ashworth</ContactName>
<ContactTitle>Sales Representative</ContactTitle>
<Address>Fauntleroy Circus</Address>
<City>London</City>
<PostalCode>EC2 5NT</PostalCode>
<Country>UK</Country>
<Phone>(171) 555-1212</Phone>
</customers>
<customers>
<CustomerID>CACTU</CustomerID>
<CompanyName>Cactus Comidas para llevar</CompanyName>
<ContactName>Patricio Simpson</ContactName>
<ContactTitle>Sales Agent</ContactTitle>
<Address>Cerrito 333</Address>
<City>Buenos Aires</City>
<PostalCode>1010</PostalCode>
<Country>Argentina</Country>
<Phone>(1) 135-5555</Phone>
<Fax>(1) 135-4892</Fax>
</customers>
<customers>
<CustomerID>CENTC</CustomerID>
<CompanyName>Centro comercial Moctezuma</CompanyName>
<ContactName>Francisco Chang</ContactName>
<ContactTitle>Marketing Manager</ContactTitle>
<Address>Sierras de Granada 9993</Address>
<City>México D.F.</City>
<PostalCode>05022</PostalCode>
<Country>Mexico</Country>
<Phone>(5) 555-3392</Phone>
<Fax>(5) 555-7293</Fax>
</customers>
<customers>
<CustomerID>CHOPS</CustomerID>
<CompanyName>Chop-suey Chinese</CompanyName>
<ContactName>Yang Wang</ContactName>
<ContactTitle>Owner</ContactTitle>
<Address>Hauptstr. 29</Address>
<City>Bern</City>
<PostalCode>3012</PostalCode>
<Country>Switzerland</Country>
<Phone>0452-076545</Phone>
</customers>
<customers>
<CustomerID>COMMI</CustomerID>
<CompanyName>Comércio Mineiro</CompanyName>
<ContactName>Pedro Afonso</ContactName>
<ContactTitle>Sales Associate</ContactTitle>
<Address>Av. dos Lusíadas, 23</Address>
<City>Sao Paulo</City>
<Region>SP</Region>
<PostalCode>05432-043</PostalCode>
<Country>Brazil</Country>
<Phone>(11) 555-7647</Phone>
</customers>
<customers>
<CustomerID>CONSH</CustomerID>
<CompanyName>Consolidated Holdings</CompanyName>
<ContactName>Elizabeth Brown</ContactName>
<ContactTitle>Sales Representative</ContactTitle>
<Address>Berkeley Gardens 12 Brewery</Address>
<City>London</City>
<PostalCode>WX1 6LT</PostalCode>
<Country>UK</Country>
<Phone>(171) 555-2282</Phone>
<Fax>(171) 555-9199</Fax>
</customers>
</customers>
step4. Last and final step drag a gridview on web page and assign DataSourceID="odsCustomers"

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


<!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:ObjectDataSource ID="odsCustomers" runat="server" SelectMethod="Select" TypeName="CustomersDataObject" />
<asp:GridView ID="GridView1" runat="Server" DataSourceID="odsCustomers">
</asp:GridView>
</div>
</form>
</body>
</html>

Thursday, August 21, 2008

How to find a cell value


If you find yourself wanting to parse through a dataset for a particular cellvalue and you need to do this programatically, this might help a little..



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


<!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">
.Hide{visibility:hidden};
</style>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="GridView1" runat="Server" OnRowDataBound="GridView1_RowDataBound">
</asp:GridView>
</div>
</form>
</body>
</html>


using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

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

BindGridViewView();
}


}
private void BindGridViewView()
{
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("ISBN", typeof(int));
objDataTable.Columns.Add("Title", typeof(string));
objDataTable.Columns.Add("Publisher", typeof(string));
objDataTable.Columns.Add("Year", typeof(string));
DataColumn[] dcPk = new DataColumn[1];
dcPk[0] = objDataTable.Columns["ISBN"];
objDataTable.PrimaryKey = dcPk;
objDataTable.Columns["ISBN"].AutoIncrement = true;
objDataTable.Columns["ISBN"].AutoIncrementSeed = 1;
//Adding some data in the rows of this DataTable
DataRow dr;
for (int i = 1; i <= 5; i++)
{
dr = objDataTable.NewRow();
dr[1] = "Title" + i.ToString();
dr[2] = "Publisher" + i.ToString();
dr[3] = "200" + i.ToString();
objDataTable.Rows.Add(dr);
}
for (int i = 6; i <= 8; i++)
{
dr = objDataTable.NewRow();
dr[1] = "Computer" + i.ToString();
dr[2] = "TMH" + i.ToString();
dr[3] = "200" + i.ToString();
objDataTable.Rows.Add(dr);
}
Session["strTemp"] = objDataTable;
return objDataTable;
}
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
//Create the array/collection of rows containing your data
GridViewRowCollection data = GridView1.Rows;

//Iterate through each row to...
foreach (GridViewRow row in data)
{

//Iterate through each cell in each row...
foreach (DataControlFieldCell cellResult in row.Cells)
{

//Create a variable to store the data control field required
//to reference the header text
DataControlField cellDCF = cellResult.ContainingField;

//Create a variable to store the header text that identifies your cell
string cellID = cellDCF.HeaderText;

//Check to see if your header text is the one you want
if (cellID.ToString() == "ISBN" || cellID.ToString()=="Year")
{

//If it is, then grab its value (data in the cell) and store it in
//a variable to perform actions against
int cellValue = int.Parse(cellResult.Text);

//Perform whatever actions you need to here...
if (cellValue % 2 == 0)
{

cellResult.CssClass = "Hide";


}
else
{
cellResult.Text = (cellValue + 2).ToString();
cellResult.BackColor = System.Drawing.Color.Red;
}
}
}
}
}
}

sp.Net Ajax HoverMenu Control On GridView with Database Manipulations




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

<%@ Register TagPrefix="cc1" Namespace="AjaxControlToolkit" Assembly="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>
<style type="text/css">
.popupMenu {
position:absolute;
visibility:hidden;
background-color:#F5F7F8;
opacity:.9;
filter: alpha(opacity=90);
}
.popupHover {
background-image:url(img/header-opened.png);
background-repeat:repeat-x;
background-position:left top;
background-color:#F5F7F8;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManger1" runat="Server">
</asp:ScriptManager>
<div>
<asp:GridView ID="GridView1" DataKeyNames="ISBN" runat="server" AutoGenerateColumns="False"
Caption="Publisher List List" EmptyDataText="You have deleted all records in customer list"
OnRowEditing="GridView1_RowEditing" OnRowDeleting="GridView1_RowDeleting" OnRowCommand="GridView1_RowCommand"
OnRowCancelingEdit="GridView1_RowCancelingEdit" OnRowUpdating="GridView1_RowUpdating">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:Panel ID="Panel1" runat="server" Width="500px">
<asp:Label ID="Label1" runat="server" Text='<%# Eval("ISBN") %>' Visible="False"></asp:Label>
<asp:Label ID="Label2" runat="server" Text='<%# Eval("Title") %>'></asp:Label>
<asp:Label ID="Label3" runat="server" Text='<%# Eval("Publisher") %>'></asp:Label>
<asp:Label ID="Label4" runat="server" Text='<%# Eval("Year") %>'></asp:Label>
</asp:Panel>
<cc1:HoverMenuExtender ID="HoverMenuExtender1" runat="server" HoverCssClass="popupHover"
PopupControlID="PopupMenu" TargetControlID="Panel1" PopupPosition="Left">
</cc1:HoverMenuExtender>
<asp:Panel ID="PopupMenu" runat="server" CssClass="popupMenu">
<div style="border: 1px outset white; padding: 2px;">
<asp:LinkButton ID="LinkButton3" runat="server" CommandName="AddNew" Text="Add New"></asp:LinkButton>
<asp:LinkButton ID="LinkButton1" runat="server" CommandName="Edit" Text="Edit"></asp:LinkButton>
<asp:LinkButton ID="LinkButton2" runat="server" CommandName="Delete" Text="Delete"></asp:LinkButton>
</div>
</asp:Panel>
</ItemTemplate>
<EditItemTemplate>
<asp:Panel ID="Panel1" runat="server" Width="400px">
<asp:Label ID="lblISBN" runat="server" Text='<%# Eval("ISBN") %>' Visible="false"></asp:Label>
<asp:TextBox ID="txtTitle" runat="server" Text='<%# Eval("Title") %>'></asp:TextBox>
<asp:TextBox ID="txtPub" runat="server" Text='<%# Eval("Publisher") %>'></asp:TextBox>
<asp:TextBox ID="txtYear" runat="server" Text='<%# Eval("Year") %>'></asp:TextBox>
</asp:Panel>
<cc1:HoverMenuExtender ID="HoverMenuExtender2" runat="server" HoverCssClass="popupHover"
PopupControlID="PopupMenu" PopupPosition="Right" TargetControlID="Panel1">
</cc1:HoverMenuExtender>
<asp:Panel ID="PopupMenu" runat="server" CssClass="popupMenu" Width="80">
<div style="border: 1px outset white; padding: 2px;">
<asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="True" CommandName="Update"
Text="Update"></asp:LinkButton>
<asp:LinkButton ID="LinkButton2" runat="server" CausesValidation="False" CommandName="Cancel"
Text="Cancel"></asp:LinkButton>
</div>
</asp:Panel>
</EditItemTemplate>
</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 GridViewHover : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{

if (!IsPostBack)
{

BindGridViewView();
}
}
private void BindGridViewView()
{
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("ISBN", typeof(string));
objDataTable.Columns.Add("Title", typeof(string));
objDataTable.Columns.Add("Publisher", typeof(string));
objDataTable.Columns.Add("Year", typeof(string));
DataColumn[] dcPk = new DataColumn[1];
dcPk[0] = objDataTable.Columns["ISBN"];
objDataTable.PrimaryKey = dcPk;
objDataTable.Columns["ISBN"].AutoIncrement = true;
objDataTable.Columns["ISBN"].AutoIncrementSeed = 1;
//Adding some data in the rows of this DataTable
DataRow dr;
for (int i = 1; i <= 5; i++)
{
dr = objDataTable.NewRow();
dr[1] = "Title" + i.ToString();
dr[2] = "Publisher" + i.ToString();
dr[3] = "200" + i.ToString();
objDataTable.Rows.Add(dr);
}
for (int i = 6; i <= 8; i++)
{
dr = objDataTable.NewRow();
dr[1] = "Computer" + i.ToString();
dr[2] = "TMH" + i.ToString();
dr[3] = "200" + i.ToString();
objDataTable.Rows.Add(dr);
}
Session["strTemp"] = objDataTable;
return objDataTable;
}
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
BindGridViewView();
}
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
string ISBN = GridView1.DataKeys[e.RowIndex].Value.ToString();
DataTable dt = Session["strTemp"] as DataTable;
DataRow dr;
dr = dt.NewRow();
dt.Rows.Find(ISBN).Delete();
dt.GetChanges();
Session["strTemp"] = dt;
BindGridViewView();


}
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName.Equals("AddNew"))
{
InsertBlanRow();
GridView1.EditIndex = GridView1.Rows.Count;
BindGridViewView();
}
//BindGridViewView();
}
protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
GridView1.EditIndex = -1;
BindGridViewView();
}
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
string ISBN = GridView1.DataKeys[e.RowIndex].Value.ToString();
DataTable dt = Session["strTemp"] as DataTable;
DataRow dr;
dr = dt.NewRow();
dr = dt.Rows.Find(ISBN);
GridViewRow row = GridView1.Rows[e.RowIndex];

if (row != null)
{

TextBox txtTitle = row.FindControl("txtTitle") as TextBox;
TextBox txtPub = row.FindControl("txtPub") as TextBox;
TextBox txtYear = row.FindControl("txtYear") as TextBox;
dr["Title"] = txtTitle.Text;
dr["Publisher"] = txtPub.Text;
dr["Year"] = txtYear.Text;

dt.AcceptChanges();
Session["strTemp"] = dt;

}
GridView1.EditIndex = -1;
BindGridViewView();

}
protected void InsertBlanRow()
{

DataTable dt = Session["strTemp"] as DataTable;
DataRow dr;
dr = dt.NewRow();
dr["Title"] = "";
dr["Publisher"] = "";
dr["Year"] = "";
dt.Rows.Add(dr);
Session["strTemp"] = dt;


}
}

Wednesday, August 20, 2008

Tips -Master Page

ASP.NET master pages are pretty handy and here is a simple tip to make them even easier to use.

Using the MasterType reference in your content page allows you to refer to your master page properties without having to cast it to your master page type everytime.

For example...



<%@ MasterType TypeName="myMasterType" %>


allows me to write...



this.Master.myProperty = "value";

rather than...



((myMasterType)this.Master).myProperty = "value";

Which saves you a little typing and provides intellisense

Select GridView Row on Double Click


Start with an existing GridView that is populated from a data source In the
ItemDataBound event handler of GridView, you assign a JavaScript ondblclick method
to the GridViewRow


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


<!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" OnRowDataBound="GridView1_RowDataBound">
</asp:GridView>
</div>
</form>
</body>
</html>


using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

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


//Insure that the __doPostBack() JavaScript method is created...
this.ClientScript.GetPostBackEventReference(this, string.Empty);
if (!IsPostBack)
{

BindGridViewView();
}
else
{
if (!(Request.Form["_EventTarget"] != null && Request.Form["_EventTarget"] == "myDblclick"))
{
GridView1.SelectedIndex = int.Parse(Request.Form["__EVENTARGUMENT"].ToString());
Response.Write(Request.Form["__EVENTARGUMENT"].ToString());


}


}
}
private void BindGridViewView()
{
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("ISBN", typeof(string));
objDataTable.Columns.Add("Title", typeof(string));
objDataTable.Columns.Add("Publisher", typeof(string));
objDataTable.Columns.Add("Year", typeof(string));
DataColumn[] dcPk = new DataColumn[1];
dcPk[0] = objDataTable.Columns["ISBN"];
objDataTable.PrimaryKey = dcPk;
objDataTable.Columns["ISBN"].AutoIncrement = true;
objDataTable.Columns["ISBN"].AutoIncrementSeed = 1;
//Adding some data in the rows of this DataTable
DataRow dr;
for (int i = 1; i <= 5; i++)
{
dr = objDataTable.NewRow();
dr[1] = "Title" + i.ToString();
dr[2] = "Publisher" + i.ToString();
dr[3] = "200" + i.ToString();
objDataTable.Rows.Add(dr);
}
for (int i = 6; i <= 8; i++)
{
dr = objDataTable.NewRow();
dr[1] = "Computer" + i.ToString();
dr[2] = "TMH" + i.ToString();
dr[3] = "200" + i.ToString();
objDataTable.Rows.Add(dr);
}
Session["strTemp"] = objDataTable;
return objDataTable;
}
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
//Each row will then behave like a link, and when you select one it
//can drive the behavior of another control(s) on your page
//other way to select
//e.Row.Attributes["ondblclick"] = ClientScript.GetPostBackClientHyperlink(this.GridView1, "Select$" + e.Row.RowIndex);

e.Row.Attributes["onmouseover"] = "this.style.cursor='hand';this.style.textDecoration='underline';this.style.color='red'";
e.Row.Attributes["onmouseout"] = "this.style.textDecoration='none';this.style.color='black';";
e.Row.Attributes.Add("ondblclick", "Javascript:__doPostBack('myDblClick','" + e.Row.RowIndex + "');");

}
}
}

How To Open Hover Menu on Mouse Over




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

<%@ Register TagPrefix="ccl" Namespace="AjaxControlToolkit" Assembly="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>
<style type="text/css">
.popupMenu
{
position: absolute;
visibility: hidden;
background-color: #E3F2F7;
opacity: .9;
filter: alpha(opacity=90);
}

.popupHover
{
background-image: url(images/header-opened.png);
background-repeat: repeat-x;
background-position: left top;
background-color: #DEB887;
}

h1 {


font: 1.2em Arial, Helvetica, sans-serif;

}
input.txt {
color: #00008B;
background-color: #E3F2F7;
border: 1px inset #00008B;
width: 200px;
}
input.btn {
color: #00008B;
background-color: #ADD8E6;
border: 1px outset #00008B;
}
form div {
clear: left;
margin: 0;
padding: 0;
padding-top: 5px;
}
form div label {
float: left;
width: 40%;
font: bold 0.9em Arial, Helvetica, sans-serif;
}
fieldset {
border: 1px dotted #61B5CF;
margin-top: 1.4em;
padding: 0.6em;
}
legend {
font: bold 0.8em Arial, Helvetica, sans-serif;
color: #00008B;
background-color: #FFFFFF;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server" />
<div>
<ccl:HoverMenuExtender ID="HoverMenuExtender1" runat="Server" TargetControlID="QuickLinkLinkButton"
PopupControlID="PanelPopUp" PopupPosition="Bottom" OffsetX="6" PopDelay="500"
HoverCssClass="popupHover">
</ccl:HoverMenuExtender>
<asp:Panel ID="PanelPopUp" runat="server" Height="50px" Width="125px" CssClass="popupMenu"
BorderColor="Transparent">
<div style="width: 600px">
<fieldset>
<legend>Personal Information</legend>
<div>
<label for="fullname">
Name:</label>
<input type="text" name="fullname" id="fullname" class="txt" runat="server" />
</div>
<div>
<label for="email">
Email Address:</label>
<input type="text" name="email" id="email" class="txt" runat="server" />
</div>
<div>
<label for="password1">
Password:</label>
<input type="password" name="password1" id="password1" class="txt" runat="server" />
</div>
<div>
<label for="password2">
Confirm Password:</label>
<input type="password" name="password2" id="password2" class="txt" runat="server" />
</div>
</fieldset>
<fieldset>
<legend>Address Details</legend>
<div>
<label for="address1">
Address line one:</label>
<input type="text" name="address1" id="address1" class="txt" runat="server" />
</div>
<div>
<label for="address2">
Address line two:</label>
<input type="text" name="address2" id="address2" class="txt" runat="server" />
</div>
<div>
<label for="city">
Town / City:</label>
<input type="text" name="city" id="city" class="txt" runat="server" />
</div>
<div>
<label for="zip">
Zip / Post code:</label>
<input type="text" name="zip" id="zip" class="txt" runat="server" />
</div>
</fieldset>
<div>
<input type="submit" name="btnSubmit" id="btnSubmit" value="Sign Up!" class="btn"
onserverclick="btnSubmit_ServerClick" runat="server" />
</div>
</div>
</asp:Panel>
<asp:LinkButton ID="QuickLinkLinkButton" runat="server">Quick Link</asp:LinkButton>
</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 Default2 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{

}
protected void btnSubmit_ServerClick(object sender, EventArgs e)
{
System.Text.StringBuilder sb = new System.Text.StringBuilder();
sb.Append("Full Name:" + fullname.Value+"\n");
sb.Append("Email:" + email.Value + "\n");
sb.Append("Address1:" + address1.Value + "\n");
sb.Append("Address2:" + address2.Value + "\n");
Response.Write(sb.ToString());
}
}

Passing Information Between Content and Master Pages




To access the Master Page's methods or properties from a content page, reference the Master Page through the Page.Master property. This property returns an object of type MasterPage, so you'll need to explicitly cast it to the appropriate type before calling its methods or referencing its properties. Alternatively, you can set the @MasterType directive, which adds a property to the auto-generated ASP.NET code-behind class code named Master that is a strongly-typed reference to the specified Master Page.

The following markup in the .aspx file for the content page spells out the Master Page type:



<%@ MasterType VirtualPath="~/MasterPage.master" %>

To illustrate this, imagine that we had a DropDownList in the Master Page. When its selected index changes, we want to notify the content page of the change so that it can update its display accordingly. Start by creating a DropDownList named Color in the Master Page that lists various colors(red, green, etc.) and then create an event handler for this DropDownList's SelectedIndexChanged event. Next, we need to define an event for the Master Page, specifying the event handler signature. The event handler signature specifies what input parameters are passed to the event handler. For this example, let's pass the selected DropDownList item's Text and Value property values. Therefore, we can use the CommandEventHandler delegate, which passes a CommandEventArgs object to the event handler, which includes CommandName and CommandArgument properties that we can use to hold the selected ListItem's Text and Value property values.

To define an event named MoodChanged for the Master Page that uses the CommandEventHandler delegate, use the following syntax:


[Masterpage.aspx]





<%@ Master Language="C#" AutoEventWireup="true" CodeFile="MasterPage.master.cs" Inherits="MasterPage" %>
<!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="Color" runat="server" OnSelectedIndexChanged="Color_SelectedIndexChanged"
AutoPostBack="True">
<asp:ListItem>Red</asp:ListItem>
<asp:ListItem Value="Green">Green</asp:ListItem>
<asp:ListItem Value="Blue">Blue</asp:ListItem>
<asp:ListItem Value="Yellow">Yellow</asp:ListItem>
</asp:DropDownList>
<asp:Panel ID="Panel1" runat="Server">
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Login" />
</asp:Panel>
<asp:ContentPlaceHolder ID="ContentPlaceHolder1" runat="server">
</asp:ContentPlaceHolder>
</div>
</form>
</body>
</html>
[Master Page Code-Behind]



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 MasterPage : System.Web.UI.MasterPage
{
public event CommandEventHandler ColorChanged;
public event CommandEventHandler MoodChanged;
protected void Page_Load(object sender, EventArgs e)
{

}

protected void Color_SelectedIndexChanged(object sender, EventArgs e)
{
if (Color.SelectedIndex != 0 && ColorChanged != null)
ColorChanged(this, new CommandEventArgs(Color.SelectedItem.Text, Color.SelectedValue));
}
protected void Button1_Click(object sender, EventArgs e)
{
if (TextBox1.Text != "" && MoodChanged != null)
MoodChanged(this, new CommandEventArgs(TextBox1.Text, TextBox2.Text));


}
}
[Content Page]

[Default.aspx]



<%@ Page Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true"
CodeFile="Default.aspx.cs" Inherits="_Default" Title="Untitled Page" %>


<%@ MasterType VirtualPath="~/MasterPage.master" %>
<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" runat="Server">
<asp:Label ID="ColorChnage" runat="Server"></asp:Label><br />
<asp:Label ID="Label1" runat="Server"></asp:Label>
</asp:Content>

[Code-Behind]



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 _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{

}
protected void Page_Init(object sender, EventArgs e)
{
// Wire up the event (MoodChanged) to the event handler (MoodChangedFromMasterPage)
Master.ColorChanged += new CommandEventHandler(ColorChangedFromMasterPage);
Master.MoodChanged += new CommandEventHandler(MoodChangedFromMasterPage);
}

private void ColorChangedFromMasterPage(object sender, CommandEventArgs e)
{
string moodText = e.CommandName;
string moodValue = e.CommandArgument.ToString();

ColorChnage.Text = String.Format("You have selected color {0}, which has a value of {1}...", moodText, moodValue);
Label1.Visible = false;
ColorChnage.Visible = true;
}

private void MoodChangedFromMasterPage(object sender, CommandEventArgs e)
{
string moodText = e.CommandName;
string moodValue = e.CommandArgument.ToString();

Label1.Text = String.Format("You have enterd user name {0}, which has a password of {1}...", moodText, moodValue);
((Panel)Master.FindControl("Panel1")).Visible = false;
Label1.Visible = true;
ColorChnage.Visible = false;
}
}

Tuesday, August 19, 2008

How to add a Text box in the Gridview Header?



protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Header)
{

// Check the header type
if (e.Row.RowType == DataControlRowType.Header)
{
Literal litHeader;
TextBox txtSearch;

// loop through each cell
for (int i = 0; i <= (e.Row.Cells.Count - 1); i++)
{
litHeader = new Literal();
txtSearch = new TextBox();

// get the current header text
litHeader.Text = e.Row.Cells[i].Text;

// add the header text plus a new textbox
e.Row.Cells[i].Controls.Add(litHeader);
e.Row.Cells[i].Controls.Add(txtSearch);
}

}
}

Searching Inside the GridView Control




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

<!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" AllowPaging="true" runat="Server" AutoGenerateColumns="False"
OnRowCreated="GridView1_RowCreated">
<Columns>
<asp:TemplateField>
<HeaderTemplate>
<label>Enter Search String</label>
<asp:TextBox ID="txtSearch" runat="Server">
</asp:TextBox>
</HeaderTemplate>
<ItemTemplate>
<asp:Label ID="lblIsbn" runat="Server" Text='<%#Eval("ISBN")%>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="lblTitle" runat="Server" Text='<%#Eval("Title") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<HeaderTemplate>
<asp:Button ID="btnSearch" runat="Server" Text="Search" />
</HeaderTemplate>
<ItemTemplate>
<asp:Label ID="lblPublisher" runat="Server" Text='<%#Eval("Publisher") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
</form>
</body>
</html>


using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Text.RegularExpressions;

public partial class HeaderSearch : System.Web.UI.Page
{
protected string searchString=string.Empty;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindGridViewView();
}
}
private void BindGridViewView()
{
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("ISBN", typeof(string));
objDataTable.Columns.Add("Title", typeof(string));
objDataTable.Columns.Add("Publisher", typeof(string));
objDataTable.Columns.Add("Year", typeof(string));
DataColumn[] dcPk = new DataColumn[1];
dcPk[0] = objDataTable.Columns["ISBN"];
objDataTable.PrimaryKey = dcPk;
objDataTable.Columns["ISBN"].AutoIncrement = true;
objDataTable.Columns["ISBN"].AutoIncrementSeed = 1;
//Adding some data in the rows of this DataTable
DataRow dr;
for (int i = 1; i <= 5; i++)
{
dr = objDataTable.NewRow();
dr[1] = "Title" + i.ToString();
dr[2] = "Publisher" + i.ToString();
dr[3] = "200" + i.ToString();
objDataTable.Rows.Add(dr);
}
for (int i = 6; i <= 8; i++)
{
dr = objDataTable.NewRow();
dr[1] = "Computer" + i.ToString();
dr[2] = "TMH" + i.ToString();
dr[3] = "200" + i.ToString();
objDataTable.Rows.Add(dr);
}
Session["strTemp"] = objDataTable;
return objDataTable;
}
protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Header)
{
SetHeader(GridView1, e.Row, this);
}




}

public void SetHeader(GridView gridView, GridViewRow gvHeaderRow, Page page)
{

TextBox txtSearch = (TextBox)gvHeaderRow.FindControl("txtSearch");
Button btnSearch = (Button)gvHeaderRow.FindControl("btnSearch");
btnSearch.Click += delegate
{

DataTable dt = Session["strTemp"] as DataTable;
DataView dv = dt.DefaultView;
dv.RowFilter = "title like'%" + txtSearch.Text + "%'";
GridView1.DataSource = dv;
GridView1.DataBind();

};


}


}

How to develop a row-clickable GridVIew control?


This post shows you how to develop a row Clickable GridView, clicking the row (e.g entire row, not specific column) in the control causes a postback and throws RowClicked event. This can be used to customize selections a user can make with the control.I added CSS class properties to the grid, to allow a different style applied to a row if hovered over.

[Code for the control]



using System;
using System.ComponentModel;
using System.Configuration;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace CustomGridView
{
/// <summary>
/// Summary description for ClickableGridView
/// </summary>
public class ClickableGridView : GridView
{
public string RowCssClass
{
get
{
string rowClass = (string)ViewState["rowClass"];
if (!string.IsNullOrEmpty(rowClass))
return rowClass;
else
return string.Empty;
}
set
{
ViewState["rowClass"] = value;
}
}

public string HoverRowCssClass
{
get
{
string hoverRowClass = (string)ViewState["hoverRowClass"];
if (!string.IsNullOrEmpty(hoverRowClass))
return hoverRowClass;
else
return string.Empty;
}
set
{
ViewState["hoverRowClass"] = value;
}
}

private static readonly object RowClickedEventKey = new object();

public event GridViewRowClicked RowClicked;
protected virtual void OnRowClicked(GridViewRowClickedEventArgs e)
{
if (RowClicked != null)
RowClicked(this, e);
}

protected override void RaisePostBackEvent(string eventArgument)
{
if (eventArgument.StartsWith("rc"))
{
int index = Int32.Parse(eventArgument.Substring(2));
GridViewRowClickedEventArgs args = new GridViewRowClickedEventArgs(Rows[index]);
OnRowClicked(args);
}
else
base.RaisePostBackEvent(eventArgument);
}

protected override void PrepareControlHierarchy()
{
base.PrepareControlHierarchy();

for (int i = 0; i < Rows.Count; i++)
{
string argsData = "rc" + Rows[i].RowIndex.ToString();
Rows[i].Attributes.Add("onclick", Page.ClientScript.GetPostBackEventReference(this, argsData));

if (RowCssClass != string.Empty)
Rows[i].Attributes.Add("onmouseout", "this.className='" + RowCssClass + "';");

if (HoverRowCssClass != string.Empty)
Rows[i].Attributes.Add("onmouseover", "this.className='" + HoverRowCssClass + "';");
}
}
}

public class GridViewRowClickedEventArgs : EventArgs
{
private GridViewRow _row;

public GridViewRowClickedEventArgs(GridViewRow aRow)
: base()
{
_row = aRow;
}

public GridViewRow Row
{
get
{ return _row; }
}
}

public delegate void GridViewRowClicked(object sender, GridViewRowClickedEventArgs args);
}
[Usage example]


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


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<%@ Register Namespace="CustomGridView" TagPrefix="sc" %>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Untitled Page</title>
<style type="text/css">

.hover{color:red}
</style>
</head>
<body>
<form id="form1" runat="server">
<div>
<sc:ClickableGridView ID="GridView1" runat="Server" HoverRowCssClass="hover" OnRowClicked="GridView1_RowClicked">
</sc:ClickableGridView>
</div>
</form>
</body>
</html>



[code-behind]


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 Meta : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{

BindGridViewView();
}

}
private void BindGridViewView()
{
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("ISBN", typeof(string));
objDataTable.Columns.Add("Title", typeof(string));
objDataTable.Columns.Add("Publisher", typeof(string));
objDataTable.Columns.Add("Year", typeof(string));
DataColumn[] dcPk = new DataColumn[1];
dcPk[0] = objDataTable.Columns["ISBN"];
objDataTable.PrimaryKey = dcPk;
objDataTable.Columns["ISBN"].AutoIncrement = true;
objDataTable.Columns["ISBN"].AutoIncrementSeed = 1;
//Adding some data in the rows of this DataTable
DataRow dr;
for (int i = 1; i <= 10; i++)
{
dr = objDataTable.NewRow();
dr[1] = "Title" + i.ToString();
dr[2] = "Publisher" + i.ToString();
dr[3] = "200" + i.ToString();
objDataTable.Rows.Add(dr);
}
Session["strTemp"] = objDataTable;
return objDataTable;
}
protected void GridView1_RowClicked(object sender, CustomGridView.GridViewRowClickedEventArgs args)
{
Response.Write("Index of the clicked row was: " + args.Row.RowIndex.ToString());
}
}

How To Add Custom DropDownList Pager in GridView


This post shows you how to add a custom DropDownlist pager and pager buttons to the GridView as shown below:



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

<!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" AllowPaging="true" runat="Server" OnRowCreated="GridView1_RowCreated"
ShowFooter="True" OnPageIndexChanging="GridView1_PageIndexChanging">
<PagerTemplate>
Goto Page
<asp:DropDownList ID="ddlPageSelector" runat="server" AutoPostBack="true">
</asp:DropDownList>
<asp:Button Text="First" CommandName="Page" CommandArgument="First" runat="server"
ID="btnFirst" />
<asp:Button Text="Previous" CommandName="Page" CommandArgument="Prev" runat="server"
ID="btnPrevious" />
<asp:Button Text="Next" CommandName="Page" CommandArgument="Next" runat="server"
ID="btnNext" />
<asp:Button Text="Last" CommandName="Page" CommandArgument="Last" runat="server"
ID="btnLast" />
</PagerTemplate>
</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 GridViewPaging : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindGridViewView();
}
}
private void BindGridViewView()
{
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("ISBN", typeof(string));
objDataTable.Columns.Add("Title", typeof(string));
objDataTable.Columns.Add("Publisher", typeof(string));
objDataTable.Columns.Add("Year", typeof(string));
DataColumn[] dcPk = new DataColumn[1];
dcPk[0] = objDataTable.Columns["ISBN"];
objDataTable.PrimaryKey = dcPk;
objDataTable.Columns["ISBN"].AutoIncrement = true;
objDataTable.Columns["ISBN"].AutoIncrementSeed = 1;
//Adding some data in the rows of this DataTable
DataRow dr;
for (int i = 1; i <= 45; i++)
{
dr = objDataTable.NewRow();
dr[1] = "Title" + i.ToString();
dr[2] = "Publisher" + i.ToString();
dr[3] = "200" + i.ToString();
objDataTable.Rows.Add(dr);
}
Session["strTemp"] = objDataTable;
return objDataTable;
}
protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Pager)
{
SetPagerButtonStates(GridView1, e.Row, this);
}
}
public void SetPagerButtonStates(GridView gridView, GridViewRow gvPagerRow, Page page)
{

int pageIndex = gridView.PageIndex;
int pageCount = gridView.PageCount;
Button btnFirst = (Button)gvPagerRow.FindControl("btnFirst");
Button btnPrevious = (Button)gvPagerRow.FindControl("btnPrevious");
Button btnNext = (Button)gvPagerRow.FindControl("btnNext");
Button btnLast = (Button)gvPagerRow.FindControl("btnLast");
btnFirst.Enabled = btnPrevious.Enabled = (pageIndex != 0);
btnNext.Enabled = btnLast.Enabled = (pageIndex < (pageCount - 1));
DropDownList ddlPageSelector = (DropDownList)gvPagerRow.FindControl("ddlPageSelector");
ddlPageSelector.Items.Clear();
for (int i = 1; i <= gridView.PageCount; i++)
{
ddlPageSelector.Items.Add(i.ToString());
}
ddlPageSelector.SelectedIndex = pageIndex;
//Anonymous method (see another way to do this at the bottom)
ddlPageSelector.SelectedIndexChanged += delegate
{
GridView1.PageIndex = ddlPageSelector.SelectedIndex;
BindGridViewView();
};
//for vb.net( VB.net 2.0 does not support anonymous methods)

//protected void ddlPageSelector_SelectedIndexChanged(object sender, EventArgs e)
//{
//GridView1.PageIndex = ((DropDownList)sender).SelectedIndex;
//GridView1.DataBind();
//}
}

protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
BindGridViewView();
}
}

How to change the row color of the Repeater based on some condition?




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

<%@ Import Namespace="System.Data" %>
<!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 Page_Load(object sender, EventArgs e)
{

if (!IsPostBack)
{

Repeater1.DataSource = GetCustomMadeDataTable();
Repeater1.DataBind();
}
}
protected string FormatColorRow(string strYear)
{


if (int.Parse(strYear) <= 2005)
{
return "style='backGround-color:red'";
}
else
{
return "style='backGround-color:green'";
}
}

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("ISBN", typeof(string));
objDataTable.Columns.Add("Title", typeof(string));
objDataTable.Columns.Add("Publisher", typeof(string));
objDataTable.Columns.Add("Year", typeof(string));

DataColumn[] dcPk = new DataColumn[1];
dcPk[0] = objDataTable.Columns["ISBN"];
objDataTable.PrimaryKey = dcPk;
objDataTable.Columns["ISBN"].AutoIncrement = true;
objDataTable.Columns["ISBN"].AutoIncrementSeed = 1;
//Adding some data in the rows of this DataTable
DataRow dr;
for (int i = 1; i <= 10; i++)
{
dr = objDataTable.NewRow();

dr[1] = "Title" + i.ToString();
dr[2] = "Publisher" + i.ToString();
dr[3] = "200" + i.ToString();
objDataTable.Rows.Add(dr);
}

Session["strTemp"] = objDataTable;
return objDataTable;
}
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Repeater ID="Repeater1" runat="server" EnableViewState="False">
<HeaderTemplate>
<table>
</HeaderTemplate>
<ItemTemplate>

<tr &lt;%#FormatColorRow(DataBinder.Eval(Container.DataItem,"Year").ToString())%&gt;>
<td> <%# DataBinder.Eval(Container.DataItem,"Title").ToString() %></td>
<td> <%# DataBinder.Eval(Container.DataItem,"Publisher").ToString() %></td>
<td>
<%# DataBinder.Eval(Container.DataItem,"Year").ToString() %>
</td>
</ItemTemplate>
<FooterTemplate>
</table>
</FooterTemplate>
</asp:Repeater>
</div>
</form>
</body>
</html>

How can I check whether left or right mouse button has been clicked?


To determine whether the user clicked the left or right button, you can use the following properties.
# Event.which in Netscape Navigator
# event.button in Internet Explorer



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

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

<script runat="server">


</script>

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Untitled Page</title>
<script type="text/javascript">
<!--
function mouseDown(e)
{
if (parseInt(navigator.appVersion)>3)
{
var clickType=1;
if (navigator.appName=="Netscape") clickType=e.which;
else clickType=event.button;
if (clickType==1)
{
self.status='Left button!';
alert("Left Button");
}
if (clickType!=1)
{
self.status='Right button!';
alert("Right Button");
}
}
return true;
}
if (parseInt(navigator.appVersion)>3)
{
document.onmousedown = mouseDown;
if (navigator.appName=="Netscape")
document.captureEvents(Event.MOUSEDOWN);
}
//-->
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Panel ID="Panel1" runat="Server" GroupingText="Test">
<asp:TextBox ID="txtBox" runat="Server"></asp:TextBox><br />
<asp:Button ID="btnTest" runat="Server" Text="Submit" />
</asp:Panel>
</div>
</form>
</body>
</html>

Monday, August 18, 2008

How To get selected value of dropdownlist using javascript




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

<!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">
.blue { background-color: #ADD8E6; color: #000000; }
.red { background-color: #E20A0A; color: #ffffff; }
.green { background-color: #3CB371; color: #ffffff; }
.yellow { background-color: #FFF280; color: #000000; }
</style>

<script type="text/javascript">
function Change()
{
var e = document.getElementById("ddlColor"); // select element
var strColor = e.options[e.selectedIndex].value; //select value
e.options[e.selectedIndex].className=strColor; //change class

}

</script>

</head>
<body >
<form id="form1" runat="server">
<asp:Panel ID="pnl" runat="Server" GroupingText="Dropdownlist">
<div>
<asp:DropDownList ID="ddlColor" runat="Server" onchange="Change();">
<asp:ListItem Value="red">Red</asp:ListItem>
<asp:ListItem Value="blue">Blue</asp:ListItem>
<asp:ListItem Value="green">Green</asp:ListItem>
<asp:ListItem Value="yellow">Yellow</asp:ListItem>
</asp:DropDownList>
</div>
</asp:Panel>
</form>
</body>
</html>

How do you group related fields in HTML




The <fieldset> and <legend> tags are a great way to group related
information in a form. These tags provide an easy means to group items visually,
and are understood by screen readers and text-only devices, which can perceive that
the tagged items are logically grouped together. This wouldn’t be the case if you
simply wrapped the related items in a styled div users of a standard browser would
understand the relationship, but those who couldn’t see the results of our CSS would
not.To group form fields, simply wrap the related fields with a <fieldset>
tag and, immediately after your opening <fieldset> tag, add a <legend>
tag that contains a title for the group:




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

    <title>Untitled Page</title>

    <style type="text/css">

    h1 {

font: 1.2em Arial, Helvetica, sans-serif;

}

input.txt {

color: #00008B;

background-color: #E3F2F7;

border: 1px inset #00008B;

width: 200px;

}

input.btn {

color: #00008B;

background-color: #ADD8E6;

border: 1px outset #00008B;

}

form div {

clear: left;

margin: 0;

padding: 0;

padding-top: 5px;

}

form div label {

float: left;

width: 40%;

font: bold 0.9em Arial, Helvetica, sans-serif;

}

fieldset {

border: 1px dotted #61B5CF;

margin-top: 1.4em;

padding: 0.6em;

}

legend {

font: bold 0.8em Arial, Helvetica, sans-serif;

color: #00008B;

background-color: #FFFFFF;

}

    </style>

</head>

<body>

    <form method="post" action="#">

        <fieldset>

            <legend>Personal Information</legend>

            <div>

                <label for="fullname">

                    Name:</label>

                <input type="text" name="fullname" id="fullname" class="txt" />

            </div>

            <div>

                <label for="email">

                    Email Address:</label>

                <input type="text" name="email" id="email" class="txt" />

            </div>

            <div>

                <label for="password1">

                    Password:</label>

                <input type="password" name="password1" id="password1" class="txt" />

            </div>

            <div>

                <label for="password2">

                    Confirm Password:</label>

                <input type="password" name="password2" id="password2" class="txt" />

            </div>

        </fieldset>

        <fieldset>

            <legend>Address Details</legend>

            <div>

                <label for="address1">

                    Address line one:</label>

                <input type="text" name="address1" id="address1" class="txt" />

            </div>

            <div>

                <label for="address2">

                    Address line two:</label>

                <input type="text" name="address2" id="address2" class="txt" />

            </div>

            <div>

                <label for="city">

                    Town / City:</label>

                <input type="text" name="city" id="city" class="txt" />

            </div>

            <div>

                <label for="zip">

                    Zip / Post code:</label>

                <input type="text" name="zip" id="zip" class="txt" />

            </div>

        </fieldset>

        <div>

            <input type="submit" name="btnSubmit" id="btnSubmit" value="Sign Up!" class="btn" />

        </div>

    </form>

</body>

</html>

How To Change Gridview Row Color on Mouseover using css and Javascript




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

 

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

    .datatable tr:hover,.datatable tr.hilite

    {

    background-color: #DFE7F2;

    color: #000000;

    }

    </style>

</head>

<body>

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

        <div>

            <asp:GridView ID="GridView1" runat="Server" CssClass="datatable">

            </asp:GridView>

        </div>

    </form>

 

    <script type="text/javascript">

    var rows = document.getElementsByTagName('tr');

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

    rows[i].onmouseover = function() {

    this.className += ' hilite';

    }

    rows[i].onmouseout = function() {

    this.className = this.className.replace('hilite', '');

    }

    }

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

{

    protected void Page_Load(object sender, EventArgs e)

    {

        if (!IsPostBack)

        {

 

            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("ISBN", typeof(string));

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

        objDataTable.Columns.Add("Publisher", typeof(string));

        objDataTable.Columns.Add("Year", typeof(string));

 

        DataColumn[] dcPk = new DataColumn[1];

        dcPk[0] = objDataTable.Columns["ISBN"];

        objDataTable.PrimaryKey = dcPk;

        objDataTable.Columns["ISBN"].AutoIncrement = true;

        objDataTable.Columns["ISBN"].AutoIncrementSeed = 1;

        //Adding some data in the rows of this DataTable

        DataRow dr;

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

        {

            dr = objDataTable.NewRow();

 

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

            dr[2] = "Publisher" + i.ToString();

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

            objDataTable.Rows.Add(dr);

        }

        Session["strTemp"] = objDataTable;

        return objDataTable;

    }

 

    

 

 

}

Insert, Update, delete, paging in formview


The FormView control displays a single record of data. It provides a built-in mechanism
for navigating from record to record; as well, it supports the updating, insertion,
and deletion of a record. As a result, the FormView control provides a way to
create a Web-based data-entry form somewhat analogous to the forms in a program
like Microsoft Access or Oracle Forms.



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

<!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">
.dataValues{font-size:20px}
</style>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:FormView ID="FormView1" runat="server" AllowPaging="true" OnPageIndexChanging="FormView1_PageIndexChanging"
OnItemUpdating="FormView1_ItemUpdating" OnModeChanging="FormView1_ModeChanging"
DataKeyNames="ISBN" OnItemInserting="FormView1_ItemInserting" OnItemDeleting="FormView1_ItemDeleting">
<HeaderTemplate>
<h2>
Book Details</h2>
</HeaderTemplate>
<ItemTemplate>
<asp:Button ID="btnInsert" runat="Server" Text="Edit" CommandName="Edit" />
<asp:Button ID="Button1" runat="Server" Text="New" CommandName="New" />
<asp:Button ID="Button2" runat="Server" Text="Delete" CommandName="Delete" />
<div>
ISBN:
<br />
<asp:Label ID="labIsbn" runat="server" Text='<%# Eval("ISBN") %>' CssClass="dataValues" />
<br />
Title:<br />
<asp:Label ID="labTitle" runat="server" Text='<%# Eval("Title") %>' CssClass="dataValues" />
<br />
Publisher:<br />
<asp:Label ID="labPublisher" runat="server" Text='<%# Eval("Publisher") %>' CssClass="dataValues" />
<br />
Year:<br />
<asp:Label ID="labDesc" runat="server" Text='<%# Eval("Year") %>' CssClass="dataValues" />
<br />
</div>
</ItemTemplate>
<EditItemTemplate>
<div class="singleBook">
ISBN:
<br />
<asp:Label ID="labEditIsbn" runat="server" CssClass="dataValues" Text='<%# Eval("ISBN") %>' /><br />
Title:<br />
<asp:TextBox ID="txtTitle" runat="server" CssClass="dataValues" Text='<%# Bind("Title") %>'
Columns="75" Width="358px" /><br />
Publisher:<br />
<asp:TextBox ID="txtPub" runat="server" CssClass="dataValues" Text='<%# Bind("Publisher") %>'
Columns="4" Width="363px" /><br />
Year:<br />
<asp:TextBox ID="txtYear" runat="server" CssClass="dataValues" Text='<%# Bind("Year") %>'
Columns="4" Width="362px" /><br />
<asp:RequiredFieldValidator ID="reqTitle" runat="server" ControlToValidate="txtTitle"
ErrorMessage="Title can not be blank" />
<div class="actionBar">
<asp:LinkButton ID="lbtnUpdate" runat="server" Text="Update" CommandName="Update" />
<asp:LinkButton ID="lbtnCancel" CausesValidation="false" runat="server" Text="Cancel"
CommandName="Cancel" />
</div>
</div>
</EditItemTemplate>
<InsertItemTemplate>
<div class="singleBook">
ISBN:
<br />
<asp:Label ID="labEditIsbn" runat="server" CssClass="dataValues" Text='<%# Eval("ISBN") %>' /><br />
Title:<br />
<asp:TextBox ID="txtTitle" runat="server" CssClass="dataValues" Text='<%# Bind("Title") %>'
Columns="75" Width="358px" /><br />
Publisher:<br />
<asp:TextBox ID="txtPub" runat="server" CssClass="dataValues" Text='<%# Bind("Publisher") %>'
Columns="4" Width="363px" /><br />
Year:<br />
<asp:TextBox ID="txtYear" runat="server" CssClass="dataValues" Text='<%# Bind("Year") %>'
Columns="4" Width="362px" /><br />
<asp:RequiredFieldValidator ID="reqTitle" runat="server" ControlToValidate="txtTitle"
ErrorMessage="Title can not be blank" />
<div class="actionBar">
<asp:LinkButton ID="lbtnUpdate" runat="server" Text="Insert" CommandName="Insert" />
<asp:LinkButton ID="lbtnCancel" CausesValidation="false" runat="server" Text="Cancel"
CommandName="Cancel" />
</div>
</div>
</InsertItemTemplate>
</asp:FormView>
</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 FormView : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindFormView();
}

}
private void BindFormView()
{
if (Session["strTemp"] != null)
{

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

}
else
{
FormView1.DataSource = GetCustomMadeDataTable();
FormView1.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("ISBN", typeof(string));
objDataTable.Columns.Add("Title", typeof(string));
objDataTable.Columns.Add("Publisher", typeof(string));
objDataTable.Columns.Add("Year", typeof(string));

DataColumn[] dcPk = new DataColumn[1];
dcPk[0] = objDataTable.Columns["ISBN"];
objDataTable.PrimaryKey = dcPk;
objDataTable.Columns["ISBN"].AutoIncrement = true;
objDataTable.Columns["ISBN"].AutoIncrementSeed = 1;
//Adding some data in the rows of this DataTable
DataRow dr;
for (int i = 1; i <= 5; i++)
{
dr = objDataTable.NewRow();

dr[1] = "Title" + i.ToString();
dr[2] = "Publisher" + i.ToString();
dr[3] = "200" + i.ToString();
objDataTable.Rows.Add(dr);
}
Session["strTemp"] = objDataTable;
return objDataTable;
}

protected void FormView1_PageIndexChanging(object sender, FormViewPageEventArgs e)
{

FormView1.PageIndex = e.NewPageIndex;
BindFormView();
}



protected void FormView1_ModeChanging(object sender, FormViewModeEventArgs e)
{
if (e.NewMode.ToString() == "Edit")
{
FormView1.ChangeMode(e.NewMode);
}
else if (e.NewMode.ToString() == "Insert")
{
FormView1.ChangeMode(e.NewMode);
}
else
FormView1.ChangeMode(e.NewMode);

BindFormView();
}
protected void FormView1_ItemUpdating(object sender, FormViewUpdateEventArgs e)
{
string ISBN = FormView1.DataKey.Value.ToString();
DataTable dt = Session["strTemp"] as DataTable;
DataRow dr;
dr = dt.NewRow();
dr = dt.Rows.Find(ISBN);


dr[1] = ((TextBox)FormView1.FindControl("txtTitle")).Text;
dr[2] = ((TextBox)FormView1.FindControl("txtPub")).Text;
dr[3] = ((TextBox)FormView1.FindControl("txtYear")).Text;
dt.GetChanges();
Session["strTemp"] = dt;
FormView1.ChangeMode(FormViewMode.ReadOnly);
BindFormView();

}
protected void FormView1_ItemInserting(object sender, FormViewInsertEventArgs e)
{
DataTable dt = Session["strTemp"] as DataTable;
DataRow dr;
dr = dt.NewRow();



dr[1] = ((TextBox)FormView1.FindControl("txtTitle")).Text;
dr[2] = ((TextBox)FormView1.FindControl("txtPub")).Text;
dr[3] = ((TextBox)FormView1.FindControl("txtYear")).Text;
dt.Rows.Add(dr);
Session["strTemp"] = dt;
FormView1.ChangeMode(FormViewMode.ReadOnly);
BindFormView();

}
protected void FormView1_ItemDeleting(object sender, FormViewDeleteEventArgs e)
{
string ISBN = FormView1.DataKey.Value.ToString();
DataTable dt = Session["strTemp"] as DataTable;
DataRow dr;
dr = dt.NewRow();
dt.Rows.Find(ISBN).Delete();
dt.GetChanges();
Session["strTemp"] = dt;
FormView1.ChangeMode(FormViewMode.ReadOnly);
BindFormView();
}
}

How To store View State on the Server(asp.net 2.0)

In ASP.NET pages, the view state represents the state of the page when it was last processed on the server. It's used to build a call context and retain values across two successive requests for the same page. By default, the state is persisted on the client using a hidden field added to the page and is restored on the server before the page request is processed. The view state travels back and forth with the page itself, but does not represent or contain any information that's relevant to client-side page display. In this post i will show how to store viewstate on server side. For more details check out this link.




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


<!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>
<div>
<asp:GridView ID="GridView1" runat="server">
</asp:GridView>
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="PostBack" /></div>
</div>
</form>
</body>
</html>


using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Drawing;

public partial class CropImage : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
if (Session["strTemp"] != null)
{

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

GridView1.DataBind();


}
else
{
GridView1.DataSource = GetCustomMadeDataTable();


GridView1.DataBind();
}
}

}

protected override object LoadPageStateFromPersistenceMedium()
{
return Session["_ViewState"];
}


protected override void SavePageStateToPersistenceMedium(object viewState)
{
Session["_ViewState"] = viewState;
}
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(string));
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 = 0; i <= 20; i++)
{
dr = objDataTable.NewRow();
dr[0] = i.ToString();
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 Button1_Click(object sender, EventArgs e)
{

}
}

ASP.NET Tips : Redirect the page when the session ends



protected void Page_Load(object sender, System.EventArgs e)
{
if (!Page.IsPostBack) {
Response.AppendHeader("Refresh", (Session.Timeout * 60) + 5 + "; Url=SessionEnded.aspx");
}
}

Sunday, August 17, 2008

How to: Read Image Metadata



Some image files contain metadata that you can read to determine features of the image. For example, a digital photograph might contain metadata that you can read to determine the Author,Title and Keywords of the image. With Microsoft Developer Support OLE File Property Reader you can read existing metadata, and you can also write new metadata to image files.




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

<!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:FileUpload ID="FileUpload1" runat="server" />
<asp:Button ID="Button1" runat="server" Text="Read" OnClick="Button1_Click" /><br />
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label><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;
using DSOFile;

public partial class ImageMetaData : System.Web.UI.Page
{
OleDocumentPropertiesClass oDocument;
string strImgName = string.Empty;
string strImgPath = string.Empty;
string strImgTitle = string.Empty;
string strImgAuthor = string.Empty;
string strImgSubject = string.Empty;
string strImgCompany = string.Empty;
string strImgComments = string.Empty;
string strImgApplication = string.Empty;
string strImgVersion = string.Empty;
string strImgCategory = string.Empty;
string strImgKeywords = string.Empty;
string strImgManager = string.Empty;
string strImgLastSavedBy = string.Empty;
string strImgByteCount = string.Empty;
string strImgDateCreated = string.Empty;
string strImgRevisionnum = string.Empty;
string strImgHeight = string.Empty;
string strImgWidth = string.Empty;
string strImgHResolution = string.Empty;
string strImgVResolution = string.Empty;
protected void Page_Load(object sender, EventArgs e)
{

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

System.Text.StringBuilder sb = new System.Text.StringBuilder();
OpenDocumentProperties(FileUpload1.PostedFile.FileName.ToString());
sb.Append("<table><tr><th>Author</th><th>Subject</th><th>Title</th></tr>");
sb.Append("<tr><td>");
sb.Append(strImgAuthor);
sb.Append("</td>");
sb.Append("<td>");
sb.Append(strImgSubject);
sb.Append("</td>");
sb.Append("<td>");
sb.Append(strImgTitle);
sb.Append("</td>");
sb.Append("</table>");

Label1.Text = sb.ToString();



}

protected void OpenDocumentProperties(string strFile)
{
try
{
DSOFile.SummaryProperties oSummProps;
string strTmp = string.Empty;
oDocument = new DSOFile.OleDocumentPropertiesClass();
oDocument.Open(strFile, false, DSOFile.dsoFileOpenOptions.dsoOptionOpenReadOnlyIfNoWriteAccess);
oSummProps = oDocument.SummaryProperties;
strImgName = oDocument.Name;
strImgPath = oDocument.Path;
if (oSummProps.Author == "" || oSummProps.Comments == "" || oSummProps.Title == "" || oSummProps.Keywords == "")
{
strImgTitle = "All";


}
else
{


strImgTitle = oSummProps.Title;

}
if (oSummProps.Author == "")
{
strImgAuthor = "Unknown";
}
else
{
strImgAuthor = oSummProps.Author;
}
strImgSubject = oSummProps.Subject;
strImgCompany = oSummProps.Company;
strImgComments = oSummProps.Comments;
strImgApplication = oSummProps.ApplicationName;
strImgVersion = oSummProps.Version;
strImgCategory = oSummProps.Category;
strImgKeywords = "," + oSummProps.Keywords.ToString() + ",";
strImgManager = oSummProps.Manager;
strImgLastSavedBy = oSummProps.LastSavedBy;
strImgByteCount = oSummProps.ByteCount.ToString();
if (oSummProps.DateCreated != null)
{
strImgDateCreated = oSummProps.DateCreated.ToString();
}
else
{
strImgDateCreated = "";
}

strImgRevisionnum = oSummProps.RevisionNumber;
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
finally
{

}

}
}

Monday, August 11, 2008

Using the RegEx Class in ASP.NET




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

<!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="panUrl" runat="server" GroupingText="Search" CssClass="myPanel">
Enter Url:
<asp:TextBox ID="txtUrl" runat="server" Columns="50" />
<br />
<asp:Button ID="btnSearch" runat="server" OnClick="btnSearch_Click" Text="Search" />
</asp:Panel>
<p>
</p>
<asp:Panel ID="panHeadings" runat="server" GroupingText="Headings in this Url" CssClass="myPanel">
<asp:Literal ID="litContent" runat="server" />
</asp:Panel>
</div>
</form>
</body>
</html>


using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Text.RegularExpressions;
using System.Net;

public partial class RegX : System.Web.UI.Page
{
/// <summary>
/// Each time the page loads, empty the literal control
/// </summary>
protected void Page_Load(object sender, EventArgs e)
{
litContent.Text = "";
}
/// <summary>
/// Event handler for search button
/// </summary>
protected void btnSearch_Click(object sender, EventArgs e)
{
// Need to trap error in case of unresponsive URL
try
{
// Use WebClient to download content at URL into a string
WebClient client = new WebClient();
string content = client.DownloadString(txtUrl.Text);
// Match any of the H? tags
Regex reg = new Regex(@"<h\d>.+</h\d>",
RegexOptions.IgnoreCase);
// Get a collection of all the matches
MatchCollection mc = reg.Matches(content);
// Iterate through the collection of matches
foreach (Match m in mc)
{
// HTML encode the tag and display in literal
litContent.Text += HttpUtility.HtmlEncode(m.Value) +
"<br/>";
}
}
catch
{
litContent.Text = "Could not connect to " + txtUrl.Text;
}
}
}

How To Create Contextmenu in asp.net using Javascript (Only for IE)




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

<!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 contextMenuClick()
{
var objContextMenu=document.getElementById("contextMenu");


objContextMenu.style.left=event.clientX;
objContextMenu.style.top=event.clientY;
objContextMenu.style.visibility="visible";
}
</script>

</head>
<body oncontextmenu="contextMenuClick(); return false;">
<form id="form1" runat="server">
<div>
Click Here
</div>
<div id="contextMenu" style="position: absolute; z-index: 999; visibility: hidden;
border: 3px solid #000080; background-color: #red; color: #ee00ee"
>
<a href="AllColors.aspx">My excellent context menu</a><br />
<a href="ajax.htm">Ajax</a>
</div>
</form>
</body>
</html>

How To Convert Pdf file to text in asp.net




in this post i will show how to convert pdf document to text file using pdftotext.

(pdftotext is an open source command-line utility for converting PDF files to plain text files —i.e. extracting text data from PDF-protected files. It is freely available and included with many Linux distributions. It must be installed as part of the xpdf package for Windows.) click here to download pdftotext


<%@ Page Language="C#" AutoEventWireup="true" CodeFile="pdf2tex.aspx.cs" Inherits="pdf2tex"
ValidateRequest="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>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:FileUpload ID="FileUpload1" runat="server" />
<br />
<asp:Button ID="btnRead" Text="Convert" runat="Server" OnClick="btnRead_Click" />
<br />
<asp:TextBox ID="txtContent" runat="Server" TextMode="MultiLine" Height="376px" Width="411px"></asp:TextBox>
</div>
</form>
</body>
</html>


using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.IO;

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

}
protected void btnRead_Click(object sender, EventArgs e)
{
string appPath = Request.ApplicationPath;
System.Diagnostics.Process p = new System.Diagnostics.Process();
p.StartInfo.Arguments = " -raw -htmlmeta" + " " + FileUpload1.PostedFile.FileName + " " + "c:\\output.htm"; ;
p.StartInfo.FileName = Page.MapPath("pdftotext.exe");

p.StartInfo.UseShellExecute = false;
p.StartInfo.CreateNoWindow = false;
p.StartInfo.RedirectStandardOutput = false;
p.Start();
p.WaitForExit();
System.Threading.Thread.Sleep(3000);
txtContent.Text = ReadFile("c:\\output.htm");


}

public string ReadFile(string s)
{
StreamReader sr = new StreamReader(s);
string strReturn = sr.ReadToEnd();
return strReturn;

}
}

How To Read word document (like .doc, .rtf , txt ) in ASP.Net , C#






Here is the code that helps to read any document (like .doc, .rtf , txt )
from specified location. This is a web based application and this code is
written in C# as code behind in ASP.Net 2.0, where the word document
is hard to upload from client side. Here is the code that uploads the
document file and stores it into a string and from that I have placed
that string into a textbox.

The First Step is that, we need to add a COM reference (that’s how we
need to define the word application) to the project by right clicking in
the solution explorer on References->Add Reference. Click on the COM
tab and look for the Microsoft Word 11.0 Object Library. Click Select
and OK.

Now u need to add the line <identity impersonate="true"/>

Like:

<system.web>

<identity impersonate="true"/>

in your web.config .



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


<!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:FileUpload ID="FileUpload1" runat="server" /><br />
<asp:Button ID="btnRead" runat="server" Text="Read Word Document" OnClick="btnRead_Click" /><br />
<asp:TextBox ID="TextBox1" runat="server" Height="373px" TextMode="MultiLine" Width="500px"></asp:TextBox>
</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 Microsoft.Office.Interop.Word;

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

}
protected void btnRead_Click(object sender, EventArgs e)
{

ApplicationClass wordApp = new ApplicationClass();

// Input box is used to get the path of the file which has to be
// uploaded into textbox.

string filePath = FileUpload1.PostedFile.FileName;

object file = filePath;

object nullobj = System.Reflection.Missing.Value;

// here on Document.Open there should be 9 arg.

Document doc = wordApp.Documents.Open(ref file,
ref nullobj,
ref nullobj,
ref nullobj,
ref nullobj,
ref nullobj,
ref nullobj,
ref nullobj,
ref nullobj,
ref nullobj,
ref nullobj,
ref nullobj,
ref nullobj,
ref nullobj,
ref nullobj,
ref nullobj);

// Here the word content is copeied into a string which helps to
// store it into textbox.

Document doc1 = wordApp.ActiveDocument;

string m_Content = doc1.Content.Text;

// the content is stored into the textbox.

TextBox1.Text = m_Content;

doc.Close(ref nullobj, ref nullobj, ref nullobj);
}
}

How To: Merge Multiple Microsoft Word Documents in ASP.net

In this post i will show how to combine multiple word document in asp,net using " Microsoft Office Interop Assemblies"



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

<!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>
&nbsp;<table>
<tr>
<td style="width: 100px">
File1</td>
<td style="width: 100px">
<asp:FileUpload ID="FileUpload1" runat="server" /></td>
</tr>
<tr>
<td style="width: 100px">
File2</td>
<td style="width: 100px">
<asp:FileUpload ID="FileUpload2" runat="server" /></td>
</tr>
<tr>
<td style="width: 100px">
</td>
<td style="width: 100px">
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Merge" /></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;
using Word = Microsoft.Office.Interop.Word;


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


}
protected void Button1_Click(object sender, EventArgs e)
{
string[] strFiles ={ FileUpload1.PostedFile.FileName,FileUpload2.PostedFile.FileName };
MsWord.Merge(strFiles, "c:\\output.doc", true);
}
}
public class MsWord
{
/// <summary>
/// This is the default Word Document Template file
/// </summary>
private const string defaultWordDocumentTemplate = @"Normal.dot";

/// <summary>
/// A function that merges Microsoft Word Documents that uses the default template
/// </summary>
/// <param name="filesToMerge">An array of files that we want to merge</param>
/// <param name="outputFilename">The filename of the merged document</param>
/// <param name="insertPageBreaks">Set to true if you want to have page breaks inserted after each document</param>
public static void Merge(string[] filesToMerge, string outputFilename, bool insertPageBreaks)
{
Merge(filesToMerge, outputFilename, insertPageBreaks, defaultWordDocumentTemplate);
}

/// <summary>
/// A function that merges Microsoft Word Documents that uses a template specified by the user
/// </summary>
/// <param name="filesToMerge">An array of files that we want to merge</param>
/// <param name="outputFilename">The filename of the merged document</param>
/// <param name="insertPageBreaks">Set to true if you want to have page breaks inserted after each document</param>
/// <param name="documentTemplate">The word document you want to use to serve as the template</param>
public static void Merge(string[] filesToMerge, string outputFilename, bool insertPageBreaks, string documentTemplate)
{
object defaultTemplate = documentTemplate;
object missing = System.Type.Missing;
object pageBreak = Word.WdBreakType.wdPageBreak;
object outputFile = outputFilename;

// Create a new Word application
Word._Application wordApplication = new Word.Application();

try
{
// Create a new file based on our template
Word._Document wordDocument = wordApplication.Documents.Add(
ref defaultTemplate
, ref missing
, ref missing
, ref missing);

// Make a Word selection object.
Word.Selection selection = wordApplication.Selection;

// Loop thru each of the Word documents
foreach (string file in filesToMerge)
{
// Insert the files to our template
selection.InsertFile(
file
, ref missing
, ref missing
, ref missing
, ref missing);

//Do we want page breaks added after each documents?
if (insertPageBreaks)
{
selection.InsertBreak(ref pageBreak);
}
}

// Save the document to it's output file.
wordDocument.SaveAs(
ref outputFile
, ref missing
, ref missing
, ref missing
, ref missing
, ref missing
, ref missing
, ref missing
, ref missing
, ref missing
, ref missing
, ref missing
, ref missing
, ref missing
, ref missing
, ref missing);

// Clean up!
wordDocument = null;
}
catch (Exception ex)
{

throw ex;
}
finally
{
// Finally, Close our Word application
wordApplication.Quit(ref missing, ref missing, ref missing);
}
}
}

Sunday, August 10, 2008

How To Create A Simple Wizard Form using Panel and Viewstate




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

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