Subscribe

RSS Feed (xml)

Powered By

Skin Design:
Free Blogger Skins

Powered by Blogger

Monday, September 29, 2008

How to display a serial number from 1 to n in a grid view







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

DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>Untitled Pagetitle>
head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="GridView1" runat="server" AllowPaging="True" AutoGenerateColumns="False"
PageSize="3" OnPageIndexChanging="GridView1_PageIndexChanging">
<Columns>
<asp:BoundField DataField="LastName" HeaderText="Name" />
<asp:BoundField DataField="Lectures" HeaderText="Lectures" />
<asp:TemplateField HeaderText="S.No">

<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# (GridView1.PageSize * GridView1.PageIndex) + Container.DisplayIndex + 1 %>'>asp:Label>
ItemTemplate>
asp:TemplateField>
Columns>
asp:GridView>
div>
form>
body>
html>



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

public partial class Paging : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
GridView1.DataSource = GetDataTable();
GridView1.DataBind();

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

GridView1.DataSource = GetDataTable();
GridView1.DataBind();
}
private DataTable GetDataTable()
{
//create table
DataTable dt = new DataTable("Members");
dt.Columns.Add("ID", Type.GetType("System.Int32"));
dt.Columns.Add("LastName", Type.GetType("System.String"));
dt.Columns.Add("Lectures", Type.GetType("System.Int32"));

//create fields
DataColumn[] pk = new DataColumn[1];
pk[0] = dt.Columns["ID"];
dt.PrimaryKey = pk;
dt.Columns["ID"].AutoIncrement = true;
dt.Columns["ID"].AutoIncrementSeed = 1;
dt.Columns["ID"].ReadOnly = true;

//fill rows
DataRow dr;
for (int x = 1; x <= 10; x++)
{
//make every other one different
if (Math.IEEERemainder(x, 2) == 0)
{
dr = dt.NewRow();
dr["LastName"] = "Riss";
dr["Lectures"] = 14;
dt.Rows.Add(dr);
}
else
{
dr = dt.NewRow();
dr["LastName"] = "Anders";
dr["Lectures"] = 3;
dt.Rows.Add(dr);

}
}

return dt;
}
}
*

create a template field, in that item template, put a label, specify it's text as

Text='<%# (GridView1.PageSize * GridView1.PageIndex) + Container.DisplayIndex + 1 %>'

Load Controls Dynamically in ASP.NET


In this article, I will show you one of the ways you can use to handle adding controls dynamically in an ASP.NET Page
Load Controls Dynamically in ASP.NET

Three Tier Architecture with ASP.NET


Brian Mains talks about the GridView control in the context of 3-tier ASP.NET applications.
Three Tier Architecture with ASP.NET

ADO.NET Tutorial


DO.NET is a set of computer software components that can be used by programmers to access data and data services. It is a part of the base class library that is included with the Microsoft .NET Framework. It is commonly used by programmers to access and modify data stored in relational database systems, though it can also be used to access data in non-relational sources. ADO.NET is sometimes considered an evolution of ActiveX Data Objects (ADO) technology, but was changed so extensively that it can be conceived of as an entirely new product.
check out this link for more details

Building a DAL using Strongly Typed TableAdapters and DataTables in VS 2005 and ASP.NET 2.0


he word Dataset does not need introduction because it is one of most commonly used object in .net world. So proceeding with this assumption, a typed dataset is an object that derives from Dataset class and additionally it provides strongly typed access to its containing tables and columns. To justify the above line still in depth, to access tables and columns in a dataset we use, check out this link for more details

Return new identity from Strongly Typed Dataset DataTable.Insert method


Datasets are pretty good at auto generating stored procedures and wrapping c# code around them for you.

However with the insert method you often want to do something with the object that you have just inserted.

Fortunately there is an easy way to get the Sproc and the c# method to return a reference to the object.

Firstly edit your insert stored procedure adding a @return parameter and a line after the insert to set this to a suitable value.

The exmaple below assumes that you are using bigint identity fields.

ALTER PROCEDURE dbo.insMyRow
(
@Description varchar(500),
@Return bigint output
)
AS
SET NOCOUNT OFF;
INSERT INTO [myTable] ([Description]) VALUES (@Description);

SET @Return = SCOPE_IDENTITY()

Note that SCOPE_IDENTITY() is similar to @@IDENTITY except its scope is limited to the current command and so improves scalability.

Now when you save the Dataset you see that the insert method takes two parameters, the second being a nullable long.

My first thought was that Datasets should be the end of editing stored procedures but I am still impressed that the c# method declaration changes accordingly.

You can call the updated method in the following way.

long? objId=null;

myTableAdapter d =new myTableAdapter();

d.Insert("Descriptive text", ref objId);

the long? just means nullable long.

After filling the table you can now use the FindByxxxID functions of the DataTable to return the DataRow object.

Select a row in an asp:GridView without using a Select Command





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

DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Untitled Pagetitle>
head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="ID"
Width="200px" AllowPaging="True" OnRowDataBound="PeopleGridView_RowDataBound">
<Columns>
<asp:BoundField DataField="StringField" HeaderText="Name" SortExpression="StringField">
asp:BoundField>
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 SelectRow : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
GridView1.DataSource = GetDataSet();
GridView1.DataBind();
}

}
public DataTable GetDataSet()
{

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

return dt;
}
protected void PeopleGridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Attributes["onmouseover"] = "this.style.cursor='hand';this.style.textDecoration='underline';";
e.Row.Attributes["onmouseout"] = "this.style.textDecoration='none';";

e.Row.Attributes["onclick"] = ClientScript.GetPostBackClientHyperlink(this.GridView1, "Select$" + e.Row.RowIndex);
}

}
}

How To Restrict the number of rows in a dataview when binding to a GridView



In this post i will show how to restrict the number of items bound to an asp:GridView. Basically I never wanted more than 10 items to be displayed.



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


DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Untitled Pagetitle>
head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="GridView1" runat="Server">
asp:GridView>
div>
form>
body>
html>




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

FilterRows obj = new FilterRows(GetDataSet().DefaultView,2);
GridView1.DataSource = obj;
GridView1.DataBind();
}

}
public class FilterRows : IEnumerable
{
DataView dataView;
private int rowsToShow;

public FilterRows(DataView dataView, int rowsToShow)
{
this.rowsToShow = rowsToShow;
this.dataView = dataView;
}

public IEnumerator GetEnumerator()
{
return new PageOfData(this.dataView.GetEnumerator(), this.rowsToShow);
}


internal class PageOfData : IEnumerator
{
private IEnumerator e;
private int cnt = 0;
private int rowsToShow;

internal PageOfData(IEnumerator e, int rowsToShow)
{
this.rowsToShow = rowsToShow;
this.e = e;
}

public object Current
{
get { return e.Current; }
}

public bool MoveNext()
{
// If we've hit out limit return false
if (cnt >= rowsToShow)
return false;

// Track the current row
cnt++;

return e.MoveNext();
}

public void Reset()
{
e.Reset();
cnt = 0;
}
}
}
public DataTable GetDataSet()
{

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

return dt;
}

}

Thursday, September 25, 2008

How To Convert HTML to Text, Easily





Whether you want to convert an HTML page into pure text so you can parse out that special piece of information, or you simply want to load a page from the Net into your own word processing package, this mini function could come in handy.

It’s called StripTags and accepts an HTML string. Using a regular expression, it identifies all <tags>, removes them, and returns the modified string. Here’s the code:



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


DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Untitled Pagetitle>
head>
<body>
<form id="form1" runat="server">
<div>
<asp:TextBox ID="TextBox1" runat="server" Height="172px" Width="363px" TextMode="MultiLine">asp:TextBox>div>
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
<asp:Label ID="Label1" runat="server" Text="Label">asp:Label>
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 StripTag : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{


}
public string StripTags(string HTML)
{
// Removes tags from passed HTML
return System.Text.RegularExpressions.Regex.Replace(HTML, "<[^>]*>", "");
}


protected void Button1_Click(object sender, EventArgs e)
{
Label1.Text = StripTags(TextBox1.Text);

}
}

How To Post Data From ASP.net To Another URL






using System;
using System.Net;
using System.Web;
using System.Collections.Specialized;


public class RemotePost
{
NameValueCollection Inputs = new NameValueCollection();
public string Url = "";
public string Method = "post";
public string FormName = "form1";
public void Add(string name, string value)
{
Inputs.Add(name, value);
}
public void Post()
{
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.Write("");
HttpContext.Current.Response.Write(string.Format("", FormName));
HttpContext.Current.Response.Write(string.Format("
", FormName, Method, Url));
int i = 0;
while (i < Inputs.Keys.Count)
{
HttpContext.Current.Response.Write(string.Format("", Inputs.Keys[i],Inputs.Keys[i]));
i += 1;
}
HttpContext.Current.Response.Write(""
);
HttpContext.Current.Response.Write("");
HttpContext.Current.Response.End();
}
}


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

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



"http://www.w3.org/1999/xhtml">
"server">
Untitled Page


"form1" runat="server">

"Button1" runat="server" OnClick="Button1_Click" Text="Post Data To Another Application" />






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

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



"http://www.w3.org/1999/xhtml" >
"server">
Untitled Page


"form1" runat="server">





The .NET Replacement for App.Path


A lot of confusion surrounds how to find out the startup path of your application —the .NET equivalent of the App.Path property we had in Visual Basic 6. I’ve personally written my own elongated routines, when in fact the solution is incredibly simple.

If you want to find out the application path of your Windows application, just reference the StartupPath property of the Application object, as so:

Dim strPath As String = Application.StartupPath 

Note that the returned path doesn’t include a trailing slash.

If you’re developing a class library or similar project, however, you might stumble upon a slight problem. You see, not all projects support the Application object. In these cases, you can use the System.Reflection class to analyze the executing assembly and return its location. A little like this:

Dim strPath As String = System.Reflection.Assembly.GetExecutingAssembly().Location 

A bit more in depth, but still pretty darn simple

Binding a Listcontrol(Dropdownlist) to Enumeration Values





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

<%@ Import Namespace="System" %>
<%@ Import Namespace="System.Web" %>
<%@ Import Namespace="System.Web.UI" %>
<%@ Import Namespace="System.Web.UI.WebControls" %>
"-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">



"http://www.w3.org/1999/xhtml">
"server">
Untitled Page


"form1" runat="server">

"DropDownList1" runat="server">



Tips

how to resolve the error

One or more errors encountered while loading the designer. The errors are listed below. Some errors can be fixed by rebuilding your project, while others may require code changes. for more details check out this link



using arrayList as DataSource for Gridview




Let us suppose that you have four controls (TextBox ,DropDownList ,ListBox ) and your requirement is that when the user enters texts or make a selection all these items/values gets stored inside an ArrayList and then this Array List is used as the Data Source for a Gridview control.




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



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

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

<head runat="server">

<title>Untitled Pagetitle>

head>

<body>

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

<div>

<asp:TextBox ID="TextBox1" runat="server" /><br />

<asp:DropDownList ID="DropDownList1" runat="server">

<asp:ListItem>Aasp:ListItem>

<asp:ListItem>Basp:ListItem>

<asp:ListItem>Casp:ListItem>

asp:DropDownList><br />

<asp:DropDownList ID="DropDownList2" runat="server">

<asp:ListItem>Aasp:ListItem>

<asp:ListItem>Basp:ListItem>

<asp:ListItem>Casp:ListItem>

asp:DropDownList><br />

<asp:ListBox ID="ListBox1" runat="server">

<asp:ListItem>Aasp:ListItem>

<asp:ListItem>Basp:ListItem>

<asp:ListItem>Casp:ListItem>

asp:ListBox><br />

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false">

<Columns>

<asp:BoundField DataField="Txt1" HeaderText="TextBox1" />

<asp:BoundField DataField="DDL1" HeaderText="DropDownList1" />

<asp:BoundField DataField="DDL2" HeaderText="DropDownList2" />

<asp:BoundField DataField="Lst1" HeaderText="ListBox1" />

Columns>

asp:GridView>

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



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

{

private List Data

{

get

{

if (this.ViewState["Data"] == null)

{

this.ViewState["Data"] = new List();

}



return this.ViewState["Data"] as List;

}

}



protected void Page_Load(object sender, EventArgs e)

{

if (!this.IsPostBack)

{

this.GetData();

}

}



private void GetData()

{

GridView1.DataSource = this.Data;

GridView1.DataBind();

}



protected void Button1_Click(object sender, EventArgs e)

{

Row obj = new Row();

obj.Txt1 = TextBox1.Text;

obj.DDL1 = DropDownList1.SelectedValue;

obj.DDL2 = DropDownList2.SelectedValue;

obj.Lst1 = ListBox1.SelectedValue;

this.Data.Add(obj);



this.GetData();

}







}

[Serializable()]

public class Row

{



private string _txt1;

private string _ddl1;

private string _ddl2;

private string _Lst1;



public string Lst1

{

get { return _Lst1; }

set { _Lst1 = value; }

}





public string DDL2

{

get { return _ddl2; }

set { _ddl2 = value; }

}





public string DDL1

{

get { return _ddl1; }

set { _ddl1 = value; }

}



public string Txt1

{

get { return _txt1; }

set { _txt1 = value; }

}



}

Enum With String Values In C#





In this post i will show how to assign string value to enum(In C# you cannot have an enum that has string values)
Step1
First I created the new custom attribute class, the source is below:
Step2
Then I created a new which I will use to get the string value for an enums value:



using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.IO;
using System.Reflection;
public class StringValueAttribute : Attribute
{
public string StringValue;

public StringValueAttribute(string value)
{
this.StringValue = value;
}
}
public static class Util
{
public static string GetStringValue(Enum value)
{
// Get the type
Type type = value.GetType();

// Get fieldinfo for this type
FieldInfo fieldInfo = type.GetField(value.ToString());
// Get the stringvalue attributes
StringValueAttribute[] attribs = fieldInfo.GetCustomAttributes(
typeof(StringValueAttribute), false) as StringValueAttribute[];
// Return the first if there was a match.
return attribs.Length > 0 ? attribs[0].StringValue : null;
}

}


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

DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Untitled Pagetitle>
head>
<body>
<form id="form1" runat="server">
<div>
<asp: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;

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

}
protected void Button1_Click(object sender, EventArgs e)
{
string val = Util.GetStringValue(Test.Something);
Response.Write(val);
}

}

public enum Test : int
{
[StringValue("Value1")]
Foo = 1,
[StringValue("Value2")]
Something = 2
}

Making a small Popup picture on mouse over event





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

DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Untitled Pagetitle>

<script type="text/javascript">
function get_(div_)
{
div_=div_.id+"1";
document.getElementById(div_).style.display="block";
}
function get_1(div_)
{
div_=div_.id+"1";
document.getElementById(div_).style.display="none";
}
script>

head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="GridView1" runat="Server" AutoGenerateColumns="False">
<Columns>
<asp:BoundField DataField="Id" HeaderText="Id" />
<asp:BoundField DataField="Name" HeaderText="Name" />
<asp:TemplateField HeaderText="Description">
<ItemTemplate>
<asp:LinkButton ID="lnk" runat="server" Text="Details" onmouseover="get_(this);"
onmouseout="get_1(this);" />
<div id="lnk1" runat="server" style="display: none; position: absolute; background-color: #FEFFB3;
width: 150px"
>
<p>
<strong>Image Namestrong>p>
<p>
<img src='<%#Eval("ImagePath")%>' runat="Server" id="A" />p>
div>
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 MouseOverGrid : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
GridView1.DataSource = GetData();
GridView1.DataBind();

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

dt.Columns.Add(new DataColumn("ImagePath", typeof(string)));
for (int i = 1; i <= 5; i++)
{
dr = dt.NewRow();
dr[0] = i;
dr[1] = "Name" + i.ToString();
dr[2] = "~/images/sa2.jpeg";
dt.Rows.Add(dr);
}
for (int i = 1; i <= 5; i++)
{
dr = dt.NewRow();
dr[0] = i;
dr[1] = "Name" + i.ToString();
dr[2] = "~/images/pdf-icon.jpg";
dt.Rows.Add(dr);
}
ds.Tables.Add(dt);
Session["dt"] = dt;
return ds;
}
}

Wednesday, September 24, 2008

Databinding Tips: Nesting Eval Statements





Maybe this is obvious, but it wasn’t obvious to me. I’m binding some data in a GridView that has the following output based on two numeric columns in my database. It doesn’t matter why or what the data represents. It’s just two pieces of data with some formatting:

int, (string) Basically these are two measurements. Initially, I would databind this like so

Basically these are two measurements. Initially, I would databind this like so:

<%# Eval("First") %>, (<%# Eval("Second") %>)

The problem with this is that if the first field is null, I’m left with this output.

, (string

Ok, easy enough to fix using a format string:

<%# Eval("First", "{0}, ") %>(<%# Eval("Second") %>)

But now I’ve learned that if the first value is null, the second one should be blank as well.


<%# Eval("First", "{0}, " + Eval("Second", "({0})")) %>


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



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



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

<head runat="server">

<title>Untitled Pagetitle>

head>

<body>

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

<div>

<asp:GridView ID="GridView1" runat="Server" AutoGenerateColumns="False">

<Columns>

<asp:TemplateField>

<ItemTemplate>

<asp:Label ID="lbl" runat="Server" Text='<%# Eval("First", "{0}, " + Eval("Second", "({0})")) %>'>asp:Label>

ItemTemplate>

asp:TemplateField>

<asp:TemplateField>

<ItemTemplate>

<asp:Label ID="lbl3" runat="Server" Text='<%# Eval("First") %>, (<%# Eval("Second") %>)'>asp:Label>

ItemTemplate>

asp:TemplateField>

Columns>

asp:GridView>

div>

form>

body>






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

{

protected void Page_Load(object sender, EventArgs e)

{

if (!IsPostBack)

{

GridView1.DataSource = GetDataSet();

GridView1.DataBind();



}



}

public DataTable GetDataSet()

{



DataTable dt = new DataTable("Company");

DataRow dr;

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

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

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

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

{

dr = dt.NewRow();

dr[0] = i;

dr[1] = i;

dr[2] = "Company" + i + Environment.NewLine + "Title" + i;

dt.Rows.Add(dr);



}

for (int i = 11; i <= 15; i++)

{

dr = dt.NewRow();

dr[0] = i;



dr[2] = "Company" + i + Environment.NewLine + "Title" + i;

dt.Rows.Add(dr);

DataColumn[] Parent_PKColumns = new DataColumn[1];

Parent_PKColumns[0] = dt.Columns["ID"];

dt.PrimaryKey = Parent_PKColumns;

Session["DataSource"] = dt;

}

return dt;

}

}

How To Add Checkboxlist Dynamically





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

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

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Untitled Pagetitle>
head>
<body>
<form id="form1" runat="server">
<div>
<table width="100%">
<col width="10%" />
<col width="90%" />
<tr>
<td>
td>
<td>
<asp:PlaceHolder ID="Ph" runat="server">asp:PlaceHolder>
td>
tr>
<tr>
<td>
td>
<td>
<asp:Button ID="Btn" Text="[Add List]" runat="server" onclick="Btn_Click" />
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 DynamicControl : System.Web.UI.Page
{
static int intCount = 0;
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
intCount++;
ViewState["ListCreated"] = false;

}
else
{
/// If list is created then display the values selected. This code portion can be moved
/// to the Btn_Click function in the else {} construct.
if (Convert.ToBoolean(ViewState["ListCreated"]))
{
DisplaySelection();
}
}
}

protected void Btn_Click(object sender, EventArgs e)
{
if (!Convert.ToBoolean(ViewState["ListCreated"]))
{
AddDynamicCheckboxList();
}
}

///
/// AddDynamicCheckboxList method creates the checkboxlist dynamicall and add 5 items to it.
/// i.e. A, B, C, D, E. Once list is created ViewState["ListCreated"] will be set to true so
/// that it is redrawn again on the postback
///

private void AddDynamicCheckboxList()
{
CheckBoxList CbxList = new CheckBoxList();
CbxList.ID = "Cbx";
for (int i = 0; i < intCount; i++)
{
CbxList.Items.Add(new ListItem(Convert.ToChar(i + 65).ToString(), Convert.ToChar(i + 65).ToString()));
}
Ph.Controls.Add(CbxList);
ViewState["ListCreated"] = true;
}

///
/// DisplaySelection method is used to display the selected values once user presses the
/// button after selecting the checkboxes. It is now being called in the page_load method
/// but can also be called on the Btn_Click method int the else {} structure.
///

private void DisplaySelection()
{
CheckBoxList Cbx = (CheckBoxList)Ph.FindControl("Cbx");
foreach (ListItem e in Cbx.Items)
{
if (e.Selected)
{
Response.Write(String.Format("You selected: {0}
"
, e.Value));
}
}
}

///
/// LoadViewState method overridden so that we can check if the ListCreated is true then
/// we can redraw the controls.
///

///
protected override void LoadViewState(object savedState)
{
base.LoadViewState(savedState);

if (Convert.ToBoolean(ViewState["ListCreated"]))
{
intCount++;
AddDynamicCheckboxList();

}

}
}

Working with the DOM





<%@ 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>

"http://www.w3.org/1999/xhtml"
>

DOM Tree 2


"hdr1">
This is the Header


"p1">
This is a paragraph of text.


    "ul1">
  • List Item 1

  • List Item 2



Performing a Server Request Asynchronously







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

DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Untitled Pagetitle>

<script type = "text/javascript" language="javascript">
var xmlHttpObj;
if (window.ActiveXObject) {
try {
xmlHttpObj = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e) {
xmlHttpObj = new ActiveXObject("Msxml2.XMLHTTP");
}
}
else xmlHttpObj = new XMLHttpRequest();
function LoadCustomers() {
if (xmlHttpObj) {
// We want this request synchronous
xmlHttpObj.open("GET", "http://" + location.host + "/MyPractice/DataFile.xml", false);
// Execute the request
xmlHttpObj.send(null);
// If the request was ok (ie. equal to a Http Status code of 200)
if (xmlHttpObj.status == 200) {
var xmlDoc = xmlHttpObj.responseXML;
// Our list of nodes selected using the X Path argument
//var nodes = xmlDoc.selectNodes("//Customers/Customer");
var nodes = xmlDoc.selectNodes("//Customers/Customer/Lastname/text()");
// Obtain a reference to the drop list
ctrl.options.add(htmlCode);
// Set the
htmlCode.text = lastName;
htmlCode.value = lastName;
}
}
else {
alert('There was a problem accessing the Customer data on the server.!');
}
}
}

function DisplayCustomerDetails() {
if (xmlHttpObj) {
// We want this request asynchronous
//debugger;
xmlHttpObj.open("GET", "http://" + location.host + "/MyPractice/DataFile.xml", true);
xmlHttpObj.onreadystatechange = function() {
if ( xmlHttpObj.readyState == 4 ) {
var ctrl = document.getElementById("ddlCustomers");
var doc = xmlHttpObj.responseXML;
var lastName = ctrl.options[ctrl.selectedIndex].value;
var node = doc.selectSingleNode("//Customers/Customer[Lastname='" +lastName + "']");
var details = 'Fullname : ' + node.selectSingleNode('Firstname / text()').nodeValue + '' + lastName + '. Email : ' + node.selectSingleNode('email / text()').nodeValue;
document.getElementById("spnDetailDisplay").childNodes[0].nodeValue = details;
}
}
// Execute the request
xmlHttpObj.send(null);
}
}
script>
head>
<body onload="LoadCustomers();">
<form id="form1" runat="server">
<div>
<select id="ddlCustomers" onchange="DisplayCustomerDetails();">
<option value="">- Select a Customer -option>
select>
<hr />

<p>
Details:p>
<span id="spnDetailDisplay">(You have not made a selection yet.)span>

div>
form>
body>
html>
DataFile.xml



xml version="1.0" encoding="utf-8" ?>
<Customers>
<Customer>
<Firstname>JoeFirstname>
<Lastname>BloggsLastname>
<email>joe@bloggs.comemail>
Customer>
<Customer>
<Firstname>AlanFirstname>
<Lastname>AnonymousLastname>
<email>anon@ymous.comemail>
Customer>
<Customer>
<Firstname>MarvinFirstname>
<Lastname>MartianLastname>
<email>marvin@mars.comemail>
Customer>
Customers>

Autosugget Using xmlHTTP in Asp.net





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

DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Untitled Pagetitle>

<script type="text/javascript">
var req;

function Initialize()
{
try
{
req=new ActiveXObject("Msxml2.XMLHTTP");
}
catch(e)
{
try
{
req=new ActiveXObject("Microsoft.XMLHTTP");
}
catch(oc)
{
req=null;
}
}

if(!req && typeof XMLHttpRequest!="undefined")
{
req= new XMLHttpRequest();

}

} function SendQuery(key)
{
Initialize();
var url="http://localhost/MyPractice/AutoSuggest.aspx?k="+key;
//debugger;
if(req!=null)
{
req.onreadystatechange = Process;
req.open("GET", url, true);
req.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');

req.send(null);

}

}

function Process()
{
if (req.readyState == 4)
{
// only if "OK"
if (req.status == 200)
{
if(req.responseText=="")
HideDiv("autocomplete");
else
{
ShowDiv("autocomplete");
var result=req.responseText;
document.getElementById("autocomplete").innerHTML =result;



}
}
else
{
document.getElementById("autocomplete").innerHTML=
"There was a problem retrieving data:
"
+req.statusText;
}
}
}

function ShowDiv(divid)
{
if (document.layers) document.layers[divid].visibility="show";
else document.getElementById(divid).style.visibility="visible";
}

function HideDiv(divid)
{
if (document.layers) document.layers[divid].visibility="hide";
else document.getElementById(divid).style.visibility="hidden";
}

function BodyLoad()
{
HideDiv("autocomplete");
document.form1.keyword.focus();

}
script>

head>
<body onload="BodyLoad();">
<form name="form1">
<input name="keyword" onkeyup="SendQuery(this.value)" style="width: 500px" autocomplete="off">
<div align="left" class="box" id="autocomplete" style="width: 500px; background-color: #ccccff">
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.Data.SqlClient;

public partial class AutoSuggest : System.Web.UI.Page
{
public void Page_Load(object sender, EventArgs args)
{
string keyword = Request["k"];
if (keyword != null && keyword.Trim() != "")
{
string sql = "select top 10* from customers where companyname like '" + keyword.Trim().Replace("'", "''") + "%'";
SqlConnection conn = new SqlConnection("server=(local);database=northwind;uid=sa;pwd=12345");
conn.Open();
DataTable dt = new DataTable();
SqlCommand command = new SqlCommand(sql, conn);
SqlDataAdapter adapter = new SqlDataAdapter(command);
adapter.Fill(dt);
conn.Close();

foreach (DataRow row in dt.Rows)
{
string meaning = row["Customerid"].ToString();
Response.Write("
");
Response.Write("" + row["companyname"].ToString() + " ");
Response.Write(row["contactname"].ToString() + "
: " + meaning + "
"
);
Response.Write("
"
);
}
}


}

}
(Only works in Mozila)

Asynchronous Request to Server (JavaScript)





I this post i will show how to send Asynchronous Request to Server which will Query the Database for certain information. Here, I am giving one example, which will send an Asynchronous Request to server for Checking the availablity of the Customerid by the user against database.

Step1.Create a new page(Async.aspx) and write down following code


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

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

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Untitled Pagetitle>
<script type="text/javascript">
function CheckUserNameAvailablity1()
{
var name=document.getElementById('<%=TextBox1.ClientID%>').value;
CheckUserNameAvailablity2(name);
return false;
}
function CheckUserNameAvailablity2(Name)
{
try
{
var Source = new ActiveXObject("Microsoft.XMLDOM");
var XmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
var ElemList;
var Request = "DOM.aspx?Name=" + Name;
XmlHttp.open("POST",Request,false);
XmlHttp.send();
Source.async = false;
if (Source.loadXML(XmlHttp.responseText) == true)
{
ElemList = Source.getElementsByTagName("tblAjaxEx");
if(ElemList.length > 0)
alert("Entered USerName is already Exists..");
else
alert("Entered UserName is available..");
}
}
catch(Ex)
{
alert(Ex.message);
}
}
script>
head>
<body>
<form id="form1" runat="server">
<div>
<asp:Label ID="Label1" runat="server" Text="UserName:">asp:Label>
<asp:TextBox ID="TextBox1" runat="server">asp:TextBox>
<asp:Button ID="Button1" runat="server" Text="Button" OnClientClick="return CheckUserNameAvailablity1()" />
div>
form>
body>
html>

Step2.Create a second Page Dom.aspx and remove all the html except Page attribute and write down the following code

DOM.aspx



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



DOM.aspx.cs



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

public partial class DOM : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
CheckUserNameAvailablity(Convert.ToString(Request.QueryString["Name"]).ToUpper());
}
}
private void CheckUserNameAvailablity(string Name)
{
DataSet dsDataSet = new DataSet();
string strSQL = "Select customerid From customers Where Upper(customerid) = '" + Name + "'";
SqlConnection cn = new SqlConnection("server=(local);database=northwind;uid=sa;pwd=12345");
cn.Open();
SqlDataAdapter adAdapter = new SqlDataAdapter(strSQL, cn);
adAdapter.Fill(dsDataSet, "tblAjaxEx");
Response.Clear();
if (dsDataSet != null)
dsDataSet.WriteXml(Response.OutputStream);
Response.End();
}
}

How To Create Ajax Based Search Page using xmlHTTP









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

DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Untitled Pagetitle>

<script type="text/javascript">
//global variable for hold XMLHttpRequest Object
var xmlHttp;
//Creating and setting the instance of appropriate XMLHTTP Request object to a "xmlHttp" variable
function CreateXmlHttp() {
//Creating object of XMLHTTP in IE
try {
//it will work if IE have JavaScript version 5.0
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch(e) {
try {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
catch(oc) {
xmlHttp = null;
}
}
//Creating object of XMLHTTP for non-IE browsers
if(!xmlHttp && typeof XMLHttpRequest != "undefined") {
xmlHttp = new XMLHttpRequest();
}
}
//function to search
function doSearch(searchText) {
//create XMLHttpRequest Object
CreateXmlHttp();
//Requested url
var ajaxRequest = "http://localhost/MyPractice/Result.aspx?search=" + searchText;
//set callback function
xmlHttp.onreadystatechange = callBackMethod;
//Initializes request
xmlHttp.open("GET", ajaxRequest, true);
//send request
xmlHttp.send(null);
}
function callBackMethod() {
//if request completed sucessfully clear the previous result and show the new search results
if(xmlHttp.readyState == 4) {
if(xmlHttp.status == 200) {
clearResults();
showResults();
}
}
}
//function clear previous results
function clearResults() {
var tableBody = document.getElementById("tbSearchResults");
while(tableBody.childNodes.length > 0) {
tableBody.removeChild(tableBody.childNodes[0]);
}
}
//function show search results in a table
//dynamically creating table rows for show the results
function showResults() {
//debugger;
if(xmlHttp.readyState == 4)
{
if(xmlHttp.status == 200)
{
var results = xmlHttp.responseXML;


var customerid = "";
var companyname = "";
var ContactName = "";
var customers = results.getElementsByTagName("Customer");
if(customers.length < 1)
return;
//add header of the search table
addHeader();
//dynamically add search results in a table
for(var i = 0; i < customers.length; i++) {


customerid = results.getElementsByTagName("CustomerID")[i].firstChild.data;
companyname = results.getElementsByTagName("CompanyName")[i].firstChild.data;
ContactName = results.getElementsByTagName("ContactName")[i].firstChild.data;
//creating new table row
addTableRow(customerid, companyname, ContactName);
}
document.getElementById("tblSearchResults").setAttribute("border", "1");
document.getElementById("tblSearchResults").setAttribute("class", "searchtable");
}
}
}
//function for creating new table row
function addTableRow(customerid, companyname, ContactName) {
var row = document.createElement("tr");
var cell = createCellWithText(customerid);
row.appendChild(cell);
cell = createCellWithText(companyname);
row.appendChild(cell);
cell = createCellWithText(ContactName);
row.appendChild(cell);
document.getElementById("tbSearchResults").appendChild(row);
}
//function for create a cell with text
function createCellWithText(text) {
var cell = document.createElement("td");
var textNode = document.createTextNode(text);
cell.appendChild(textNode);
return cell;
}
//add headers of the search result table
function addHeader() {
var row = document.createElement("tr");
var cell = createCellWithText("CustomerID");
row.appendChild(cell);
cell = createCellWithText("CompanyName");
row.appendChild(cell);
cell = createCellWithText("ContactName");
row.appendChild(cell);
document.getElementById("tbSearchResults").appendChild(row);
}

script>

head>
<body>
<form id="Form1" method="post" runat="server">
<b>Search For Booksb> <span id="header">span>
<table width="500" border="0">
<tbody>
<tr>
<td>
Searchtd>
<td>
<input type="text" onkeyup="doSearch(this.value);" size="40">
td>
tr>
<tr>
<td colspan="2">
<table id="tblSearchResults" width="100%" border="0">
<tbody id="tbSearchResults">
tbody>
table>
td>
tr>
tbody>
table>
form>
body>
html>


Result.aspx


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



Result.aspx.cs



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

public partial class a : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
string search = Request["search"];
if (search.Length > 0)
{
Response.Clear();
DataSet dsResults = new DataSet();
//call business layer method for search results
dsResults = getvalue(search);
Response.Clear();
Response.ContentType = "text/xml";
Response.Charset = "utf-8";
string resultsString = dsResults.GetXml();
Response.Write(resultsString);
//end the response
Response.End();
}
else
{
//clears the response written into the buffer and end the response.
Response.Clear();
Response.End();
}
}

else
{
//clears the response written into the buffer and end the response.
Response.Clear();
Response.End();
}

}
private DataSet getvalue(string s)
{

SqlConnection con = new SqlConnection("server=(local);database=northwind;uid=sa;pwd=12345");
SqlDataAdapter da = new SqlDataAdapter("select * from customers where customerid like '%" + s + "%'", con);
DataSet ds = new DataSet();
da.Fill(ds,"Customer");
return ds;

}
}

How To Create Ajax Based Search Page using xmlHTTP









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

DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Untitled Pagetitle>

<script type="text/javascript">
//global variable for hold XMLHttpRequest Object
var xmlHttp;
//Creating and setting the instance of appropriate XMLHTTP Request object to a "xmlHttp" variable
function CreateXmlHttp() {
//Creating object of XMLHTTP in IE
try {
//it will work if IE have JavaScript version 5.0
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch(e) {
try {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
catch(oc) {
xmlHttp = null;
}
}
//Creating object of XMLHTTP for non-IE browsers
if(!xmlHttp && typeof XMLHttpRequest != "undefined") {
xmlHttp = new XMLHttpRequest();
}
}
//function to search
function doSearch(searchText) {
//create XMLHttpRequest Object
CreateXmlHttp();
//Requested url
var ajaxRequest = "http://localhost/MyPractice/Result.aspx?search=" + searchText;
//set callback function
xmlHttp.onreadystatechange = callBackMethod;
//Initializes request
xmlHttp.open("GET", ajaxRequest, true);
//send request
xmlHttp.send(null);
}
function callBackMethod() {
//if request completed sucessfully clear the previous result and show the new search results
if(xmlHttp.readyState == 4) {
if(xmlHttp.status == 200) {
clearResults();
showResults();
}
}
}
//function clear previous results
function clearResults() {
var tableBody = document.getElementById("tbSearchResults");
while(tableBody.childNodes.length > 0) {
tableBody.removeChild(tableBody.childNodes[0]);
}
}
//function show search results in a table
//dynamically creating table rows for show the results
function showResults() {
//debugger;
if(xmlHttp.readyState == 4)
{
if(xmlHttp.status == 200)
{
var results = xmlHttp.responseXML;


var customerid = "";
var companyname = "";
var ContactName = "";
var customers = results.getElementsByTagName("Customer");
if(customers.length < 1)
return;
//add header of the search table
addHeader();
//dynamically add search results in a table
for(var i = 0; i < customers.length; i++) {


customerid = results.getElementsByTagName("CustomerID")[i].firstChild.data;
companyname = results.getElementsByTagName("CompanyName")[i].firstChild.data;
ContactName = results.getElementsByTagName("ContactName")[i].firstChild.data;
//creating new table row
addTableRow(customerid, companyname, ContactName);
}
document.getElementById("tblSearchResults").setAttribute("border", "1");
document.getElementById("tblSearchResults").setAttribute("class", "searchtable");
}
}
}
//function for creating new table row
function addTableRow(customerid, companyname, ContactName) {
var row = document.createElement("tr");
var cell = createCellWithText(customerid);
row.appendChild(cell);
cell = createCellWithText(companyname);
row.appendChild(cell);
cell = createCellWithText(ContactName);
row.appendChild(cell);
document.getElementById("tbSearchResults").appendChild(row);
}
//function for create a cell with text
function createCellWithText(text) {
var cell = document.createElement("td");
var textNode = document.createTextNode(text);
cell.appendChild(textNode);
return cell;
}
//add headers of the search result table
function addHeader() {
var row = document.createElement("tr");
var cell = createCellWithText("CustomerID");
row.appendChild(cell);
cell = createCellWithText("CompanyName");
row.appendChild(cell);
cell = createCellWithText("ContactName");
row.appendChild(cell);
document.getElementById("tbSearchResults").appendChild(row);
}

script>

head>
<body>
<form id="Form1" method="post" runat="server">
<b>Search For Booksb> <span id="header">span>
<table width="500" border="0">
<tbody>
<tr>
<td>
Searchtd>
<td>
<input type="text" onkeyup="doSearch(this.value);" size="40">
td>
tr>
<tr>
<td colspan="2">
<table id="tblSearchResults" width="100%" border="0">
<tbody id="tbSearchResults">
tbody>
table>
td>
tr>
tbody>
table>
form>
body>
html>


Result.aspx


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



Result.aspx.cs



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

public partial class a : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
string search = Request["search"];
if (search.Length > 0)
{
Response.Clear();
DataSet dsResults = new DataSet();
//call business layer method for search results
dsResults = getvalue(search);
Response.Clear();
Response.ContentType = "text/xml";
Response.Charset = "utf-8";
string resultsString = dsResults.GetXml();
Response.Write(resultsString);
//end the response
Response.End();
}
else
{
//clears the response written into the buffer and end the response.
Response.Clear();
Response.End();
}
}

else
{
//clears the response written into the buffer and end the response.
Response.Clear();
Response.End();
}

}
private DataSet getvalue(string s)
{

SqlConnection con = new SqlConnection("server=(local);database=northwind;uid=sa;pwd=12345");
SqlDataAdapter da = new SqlDataAdapter("select * from customers where customerid like '%" + s + "%'", con);
DataSet ds = new DataSet();
da.Fill(ds,"Customer");
return ds;

}
}

How TO Use XMLHTTP Object in C#


Step 1 . Add a reference to the Microsoft,Ver3.0 (Msxml 3/4) in your project
Step 2.Import the namespace
using MSXML2;


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

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

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Untitled Pagetitle>
head>
<body>
<form id="form1" runat="server">
<div>
<asp:TextBox ID="TextBox1" runat="server">asp:TextBox>
<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 MSXML2;

public partial class MSXML : System.Web.UI.Page
{

protected void Page_Load(object sender, EventArgs e)
{

}
protected void Button1_Click(object sender, EventArgs e)
{
// to get page data (using msxml4)
XMLHTTP40 http = new XMLHTTP40();
http.open("GET", "http://localhost/MyPractice/Result.aspx?search=" + TextBox1.Text + "", false, null, null);
http.send(null);
string value = http.responseText;
Response.Write(value.ToString());
}
}

How To Use ASP.NET and HTTPrequest POST method





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

DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Untitled Pagetitle>

<script type = "text/javascript">
function validateuserid(suserid) {
document.body.style.cursor = 'wait';
// Create an instance of the XML HTTP Request object
var oXMLHTTP = new ActiveXObject( "Microsoft.XMLHTTP" );
//debugger;
// Prepare the XMLHTTP object for a HTTP POST to our validation ASP.net page
var sURL = "http://localhost/MyPractice/check.aspx";
oXMLHTTP.open( "POST", sURL, false );
oXMLHTTP.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
// Execute the request
oXMLHTTP.send("userID=" + suserid);
//alert(oXMLHTTP.responseText);
if (oXMLHTTP.responseText == "exists")
document.getElementById("test").innerText = "Sorry - the User ID already exists.";
else
document.getElementById("test").innerText = "the User ID is available.";
}
script>
head>
<body>
<form id="form1" runat="server">
<div>
<input type="text" name="userid" value="" onchange="validateuserid(this.value)">
<span id="test">span>
div>

form>
body>
html>


Check.aspx


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



Check.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 Test : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string sUserID = Request.Form["userID"].ToString();
if (sUserID == "Me")
{
Response.Write("exists");
}
}
}

How To Check That Your Browser support ajax





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 Pagetitle>
<script type = "text/javascript">
function GetXmlHttpObject() {
var xml_Http = null;
try {
// Firefox, Opera 8.0+, Safari
xml_Http = new XMLHttpRequest();
}
catch (e) {
// Internet Explorer
try {
xml_Http = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e) {
xml_Http = new ActiveXObject("Microsoft.XMLHTTP");
}
}
return xml_Http;
}
function check() {
window.xmlHttp = GetXmlHttpObject();
if (window.xmlHttp == null) {
alert ("Your browser does not support AJAX!");
return null;
}
else {
alert("Your Browser support ajax");
}
}

script>
head>
<body onload="check();">
body>
html>

How To Open A open a div with content from another page





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

DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8">

<script type="text/javascript">
function getXMLObj() {
req = false;
if(window.XMLHttpRequest) {
try {
req = new XMLHttpRequest();
} catch(e) {
req = false;
}
} else if(window.ActiveXObject) {
try {
req = new ActiveXObject("Msxml2.XMLHTTP");
} catch(e) {
try {
req = new ActiveXObject("Microsoft.XMLHTTP");
} catch(e) {
req = false;
}
}
}
return req;
}

function getPage(url, cntID) {
var xmlhttp = getXMLObj();
var elem = document.getElementById(cntID);
if (xmlhttp) {
xmlhttp.open("GET",url,true);
xmlhttp.onreadystatechange=function() {
if(xmlhttp.readyState==1)
{

elem.innerHTML='Loading..........';
}
if (xmlhttp.readyState==4) {
elem.innerHTML = xmlhttp.responseText;
}
}
xmlhttp.send(null)
} else {
alert("Page could not be found.");
}

}


function ReverseContentDisplay(d) {
if(d.length < class="kwrd">return
; }
if(document.getElementById(d).style.display == "none")
{
document.getElementById(d).style.display = "block";
}
else { document.getElementById(d).style.display = "none"; }
}

script>

head>
<body>
<form id="form1" runat="server">
<div id="loading">
div>
<div id="carDisplayDivID" style="display: none; position: absolute; left: 200px;
top: 100px; border-style: solid; background-color: white; padding: 5px;"
>
div>
<div id="Div1" style="display: none; position: absolute; left: 200px; top: 100px;
border-style: solid; background-color: white; padding: 5px;"
>
div>
<div id="Div2" style="display: none; position: absolute; left: 200px; top: 100px;
border-style: solid; background-color: white; padding: 5px;"
>
div>
<a href="#" onmouseout="ReverseContentDisplay('carDisplayDivID');" onmouseover="javascript:getPage('http://localhost/MyPractice/Return.aspx?id=1','carDisplayDivID');">
Details1a> <a href="#" onmouseout="ReverseContentDisplay('Div1');" onmouseover="javascript:getPage('http://localhost/MyPractice/Return.aspx?id=2','Div1');">
Details2a> <a href="#" onmouseout="ReverseContentDisplay('Div2');" onmouseover="javascript:getPage('http://localhost/MyPractice/Return.aspx?id=3','Div2');">
Details3a>
form>
body>
html>



Return.aspx


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

Return.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 Return : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
System.Threading.Thread.Sleep(3000);
if (Request.QueryString["Id"].ToString() == "1")
{
Response.Write("The first function, getXMLObj creates an XMLHTTPRequest object, the second actually calls the remote page and loads its content into a destination div. To use, just put the code into a script block then call getPage as follows (using your car example:");

}
if (Request.QueryString["Id"].ToString() == "2")
{
Response.Write("The second function, getXMLObj creates an XMLHTTPRequest object, the second actually calls the remote page and loads its content into a destination div. To use, just put the code into a script block then call getPage as follows (using your car example:");

}
if (Request.QueryString["Id"].ToString() == "3")
{
Response.Write("The third function, getXMLObj creates an XMLHTTPRequest object, the second actually calls the remote page and loads its content into a destination div. To use, just put the code into a script block then call getPage as follows (using your car example:");

}
}
}
}

How To Open Fancy Tooltip from GridView






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


DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Untitled Pagetitle>

<script type="text/javascript">
function showTip(e, text)
{
e = (e == null) ? window.event : e;
target = (e.target) ? e.target : e.srcElement;
document.getElementById('text').innerHTML = text;
document.getElementById('tooltip').style.left = target.offsetLeft + 10 + 'px';
document.getElementById('tooltip').style.top = target.offsetTop + 20 + 'px';
document.getElementById('tooltip').style.display='block';
target.onmouseout = function() {document.getElementById('tooltip').style.display='none'};
}
script>

head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="GridView1" runat="Server" AutoGenerateColumns="False" OnRowDataBound="GridView1_RowDataBound">
<Columns>
<asp:BoundField DataField="Id" HeaderText="Id" />
<asp:BoundField DataField="Name" HeaderText="Name" />
<asp:TemplateField HeaderText="Description">
<ItemTemplate>
<asp:LinkButton ID="lnk" runat="server" Text="Details" CausesValidation="False" />
<div id="tooltip" style="position: absolute; display: none; width: 300px; padding-left: 100px">
<div style="background: url(bubble2.gif) no-repeat top; padding: 50px 8px 0px; text-align: center">
<div id="text" style="padding-left: 10px; padding-right: 10px; position: relative">
div>
div>
<div style="background: url(bubble2.gif) no-repeat bottom; padding: 20px 8px 0px;
text-align: center;"
>
div>
div>
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 GridViewToolTip : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
GridView1.DataSource = GetData();
GridView1.DataBind();

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


for (int i = 0; i <= 5; i++)
{
dr = dt.NewRow();
dr[0] = i;
dr[1] = "Name" + i.ToString();
dt.Rows.Add(dr);
}

ds.Tables.Add(dt);
Session["dt"] = dt;
return ds;
}
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
string strValue = string.Empty;
if (e.Row.RowType == DataControlRowType.DataRow)
{
LinkButton l = (LinkButton)e.Row.FindControl("lnk");
foreach (GridViewRow gv in GridView1.Rows)
{


strValue = gv.Cells[0].Text + gv.Cells[1].Text;

l.Attributes.Add("onmouseover", "javascript:showTip(event,'" + strValue + "')");

}

}
}
}

AJAX Database Example in Asp.net





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

DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Untitled Pagetitle>

<script type="text/javascript">
var xmlHttp

function showCustomer(str)
{
xmlHttp=GetXmlHttpObject();
if (xmlHttp==null)
{
alert ("Your browser does not support AJAX!");
return;
}
var url="getcustomer.aspx";
url=url+"?q="+str;
url=url+"&sid="+Math.random();
xmlHttp.onreadystatechange=stateChanged;
xmlHttp.open("GET",url,true);
xmlHttp.send(null);
}

function stateChanged()
{
if (xmlHttp.readyState==4)
{
document.getElementById("txtHint").innerHTML=xmlHttp.responseText;
}
}

function GetXmlHttpObject()
{
var xmlHttp=null;
try
{
// Firefox, Opera 8.0+, Safari
xmlHttp=new XMLHttpRequest();
}
catch (e)
{
// Internet Explorer
try
{
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
}
return xmlHttp;
}
script>

head>
<body>
<form id="form1" runat="server">
Select a Customer:
<select name="customers" onchange="showCustomer(this.value)">
<option value="ALFKI">
Alfreds Futterkiste
<option value="NORTS ">
North/South
<option value="WOLZA">
Wolski Zajazd
select>
<div id="txtHint">
<b>Customer info will be listed here.b>div>
form>
body>
html>
GetCustomer.aspx



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



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

public partial class GetCustomer : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string strId = Request.QueryString["q"].ToString();
SqlConnection con = new SqlConnection("server=(local);database=northwind;uid=sa;pwd=12345");
SqlDataAdapter da = new SqlDataAdapter("select * from customers where customerid='" + strId + "'", con);
DataSet ds = new DataSet();
da.Fill(ds);
StringBuilder sb = new StringBuilder();
sb.Append("");


foreach (DataRow dr in ds.Tables[0].Rows)
{
sb.Append("");
sb.Append("");

sb.Append("");
sb.Append("");
}

sb.Append("
CompanyNamecontactnameContacttitleAddress
" + dr["CompanyName"].ToString() + "" + dr["contactname"].ToString() + " " + dr["Contacttitle"].ToString() + "" + dr["Address"].ToString() + "
"
);
Response.Write(sb.ToString());
}
}

How To Open GridView in Div





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

DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>Untitled Pagetitle>
head>
<body id="pgBody" runat="server">
<form id="form1" runat="server">
<div>
<table runat="server" id="table1" class="bar">
<tr>
<td>
<asp:Label ID="LabelProjects" Text="Projects:" runat="server">asp:Label>
td>
<td>
<asp:TextBox ID="TextBoxProjects" runat="server">asp:TextBox>
<asp:Button ID="btnOpen" runat="Server" CausesValidation="False" Text="Open Grid" />
td>
tr>
<tr>
<td colspan="1">
td>
<td>
<div id="splat" name="splat" runat="server" style="display: block">
<asp:GridView Width="151px" ID="GridView1" runat="server" AllowPaging="True" AutoGenerateColumns="False">
<Columns>
<asp:TemplateField HeaderText="Select All">
<HeaderTemplate>
<input id="CheckboxSelectAll" onclick="SelectAllCheckboxes(this)" type="checkbox" />
Select All
HeaderTemplate>
<ItemTemplate>
<asp:CheckBox ID="Chk" runat="server" Text='<%# Eval("NAME") %>' AutoPostBack="true"
OnCheckedChanged="Chk_CheckedChanged" />
ItemTemplate>
asp:TemplateField>
Columns>
asp:GridView>
div>
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 GridViewandDiv : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{

GridView1.DataSource = GetDataTable();
GridView1.DataBind();
}
pgBody.Attributes.Add("onclick", ClientScript.GetPostBackEventReference(Page, "CustomPostBack"));

if (Request["__EVENTARGUMENT"] == "CustomPostBack" && splat.Style["display"] == "block")
{
splat.Style.Remove("display");
splat.Style.Add("display", "none");
}
else
{
if (Request["__EVENTARGUMENT"] == "CustomPostBack")
{
splat.Style.Remove("display");
splat.Style.Add("display", "block");
}
}
}
private DataTable GetDataTable()
{
//create table
DataTable dt = new DataTable("Project");
dt.Columns.Add("ID", Type.GetType("System.Int32"));
dt.Columns.Add("NAME", Type.GetType("System.String"));

//create fields
DataColumn[] pk = new DataColumn[1];
pk[0] = dt.Columns["ID"];
dt.PrimaryKey = pk;
dt.Columns["ID"].AutoIncrement = true;
dt.Columns["ID"].AutoIncrementSeed = 1;
dt.Columns["ID"].ReadOnly = true;

//fill rows
DataRow dr;
for (int x = 1; x <= 10; x++)
{
//make every other one different
if (Math.IEEERemainder(x, 2) == 0)
{
dr = dt.NewRow();
dr["Name"] = "Riss1";

dt.Rows.Add(dr);
}
else
{
dr = dt.NewRow();
dr["Name"] = "Riss2";

dt.Rows.Add(dr);

}
}

return dt;
}

protected void Chk_CheckedChanged(object sender, EventArgs e)
{
System.Text.StringBuilder sb = new System.Text.StringBuilder();

foreach(GridViewRow gv in GridView1.Rows)
{
CheckBox chk = gv.FindControl("chk") as CheckBox;
if (chk.Checked)
{

sb.Append(chk.Text);
sb.Append(";");

}


}
TextBoxProjects.Text = sb.ToString();
}
}

How To: Redirect a user to a page using popups





Source.aspx



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

DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Untitled Pagetitle>
head>
<body>
<form id="form1" runat="server">
<div>
<asp:HyperLink ID="hlRedirect1" runat="server" NavigateUrl="RedirectToSite.aspx?site=1">Redirect 1asp:HyperLink><br />
<asp:HyperLink ID="hlRedirect2" runat="server" NavigateUrl="RedirectToSite.aspx?site=2">Redirect 2asp:HyperLink><br />
<asp:HyperLink ID="hlRedirect3" runat="server" NavigateUrl="RedirectToSite.aspx">Redirect 3asp:HyperLink> div>
form>
body>
html>

RedirectToSite.aspx




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

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

<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
<title>Redirect to sitetitle>
<script type="text/javascript">

script>
head>
<body onload="<%= redirectionEvent %>" >
<form id="form1" runat="server">
<div>
<asp:Label ID="lblRedirectStatus" runat="server" Text="Unknown site...">asp:Label>div>
form>
body>
html>


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

public partial class RedirectToSite : System.Web.UI.Page
{
protected string redirectionEvent = "";
protected void Page_Load(object sender, EventArgs e)
{
//our popup call
string redirectionInfo = "popup('@popurl', 'ad')";
//the popup url
string popurl = "";
//check whether there is a value for our querystring
if (Request.QueryString["site"] != null)
{
//get the siteid
string siteId = "";
siteId = Request.QueryString["site"].ToString();

//if siteid is one then...
if (siteId == "1") { popurl = "http://www.google.com"; }
//if siteid is two then
else if (siteId == "2") { popurl = "http://www.blogger.com"; }

//display our redirect information
lblRedirectStatus.Text = "Redirecting to " + popurl;
//replace the @popurl placeholder with the popurl value
redirectionEvent = redirectionInfo.Replace("@popurl", popurl);
}
}
}

How To: Check if application is already running


Here's a short code that checks to see if the current application is already running.
using System;
using System.Collections.Generic;
using System.Text;
using System.Diagnostics;

namespace KeithRull.CS.Windows.CheckIfAppIsAlreadyRunning
{
class Program
{
static void Main(string[] args)
{
if (IsAppAlreadyRunning())
{
Console.WriteLine("This application is already running... Press any key to exit.");
}
else
{
Console.WriteLine("App now running!");
// ... do whatever you want to do here.
}
Console.ReadLine();
}

public static bool IsAppAlreadyRunning()
{
bool isAlreadyRunning = false;
Process currentProcess = Process.GetCurrentProcess();
Process[] processes = Process.GetProcesses();
foreach (Process process in processes)
{
if (currentProcess.Id != process.Id)
{
if (currentProcess.ProcessName == process.ProcessName)
{
isAlreadyRunning = true;
}
}
}
return isAlreadyRunning;
}
}
}

Monday, September 22, 2008

How To: Create a simple Drill-Down/Master-Detail view with a DataList and DataGrid





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

DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Untitled Pagetitle>
head>
<body>
<form id="Form1" method="post" runat="server">
<asp:DataList ID="folderList" runat="server" BorderColor="#CC9966" BorderStyle="None"
BorderWidth="1px" BackColor="White" CellPadding="4" Font-Names="Arial" Font-Size="X-Small"
GridLines="Both" OnItemCommand="folderList_ItemCommand1">
<SelectedItemStyle Font-Bold="True" ForeColor="#663399" BackColor="#FFCC66">SelectedItemStyle>
<HeaderTemplate>
<b>Full Nameb>
HeaderTemplate>
<SelectedItemTemplate>
<asp:LinkButton ID="Linkbutton2" runat="server" CommandName="Select" CommandArgument='<%# DataBinder.Eval( Container.DataItem, "FullName" ) %>'>
<%# DataBinder.Eval( Container.DataItem, "FullName" ) %>
asp:LinkButton>
<table width="100%" border="0">
<tr>
<td width="30%">

td>
<td width="70%">
<asp:DataGrid ID="Datagrid1" runat="server" AutoGenerateColumns="False" BorderColor="#CC9966"
BorderStyle="None" BorderWidth="1px" BackColor="White" CellPadding="4" Font-Size="X-Small">
<FooterStyle ForeColor="#330099" BackColor="#FFFFCC">FooterStyle>
<SelectedItemStyle Font-Bold="True" ForeColor="#663399" BackColor="#FFCC66">SelectedItemStyle>
<ItemStyle ForeColor="#330099" BackColor="White">ItemStyle>
<HeaderStyle Font-Bold="True" ForeColor="#FFFFCC" BackColor="#990000">HeaderStyle>
<Columns>
<asp:BoundColumn DataField="Name" HeaderText="Name">asp:BoundColumn>
<asp:BoundColumn DataField="Extension" HeaderText="Extension">asp:BoundColumn>
<asp:BoundColumn DataField="LastWriteTime" HeaderText="LastWriteTime">asp:BoundColumn>
Columns>
<PagerStyle HorizontalAlign="Center" ForeColor="#330099" BackColor="#FFFFCC">PagerStyle>
asp:DataGrid>
td>
tr>
table>
SelectedItemTemplate>
<FooterStyle ForeColor="#330099" BackColor="#FFFFCC">FooterStyle>
<ItemStyle ForeColor="#330099" BackColor="White">ItemStyle>
<ItemTemplate>
<asp:LinkButton ID="LinkButton1" runat="server" CommandName="Select" CommandArgument='<%# DataBinder.Eval( Container.DataItem, "FullName" ) %>'>
<%# DataBinder.Eval( Container.DataItem, "FullName" ) %>
asp:LinkButton>
ItemTemplate>
<HeaderStyle Font-Bold="True" ForeColor="#FFFFCC" BackColor="#990000">HeaderStyle>
asp:DataList>form>
body>
html>
The ItemTemplate would serve as the normal view and the SelectedTemplate would server as the view for the page when a selection is done. It is also in this part where we have placed the DataGrid since we want to show the details based on selection. Also note that we have setupped the CommandArgument for The linkbutton to the Fullname column

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

public partial class DrillDown : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindFolderList();
}
}
private void BindFolderList()
{
//set the startup location
string rootFolderLocation = @"C:\";

//create a new DirectoryInfo that would read our rootFolderLocation
DirectoryInfo dInfo = new DirectoryInfo(rootFolderLocation);

//Assign the DataSource and bind it to our DataList
folderList.DataSource = dInfo.GetDirectories();
folderList.DataBind();
}
private void folderList_ItemCommand(object source, DataListCommandEventArgs e)
{


}
protected void folderList_ItemCommand1(object source, DataListCommandEventArgs e)
{ //set the selected index
folderList.SelectedIndex = e.Item.ItemIndex;
//change the background color
folderList.SelectedItemStyle.BackColor = Color.AntiqueWhite;

//initiate the rebind

BindFolderList();

//find the DataGrid from the SelectedItemTemplate of our DataList
Control ctl = folderList.SelectedItem.FindControl("
Datagrid1") as Control;

//Check whether the control is a DataGrid
if (ctl is DataGrid)
{
//create a pointer to our grid
DataGrid fileGrid = (DataGrid)ctl;
//read the selected directory
DirectoryInfo cInfo = new DirectoryInfo(e.CommandArgument.ToString());

//Assign the DataSource and bind it to our DataGrid
fileGrid.DataSource = cInfo.GetFiles();
fileGrid.DataBind();
}
}
}

How To Fetch All Links From a URL





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

DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Untitled Pagetitle>
head>
<body>
<form id="form1" runat="server">
<div>
<table style="width: 50%">
<tr>
<td style="width: 100px">
Enter URLtd>
<td style="width: 100px">
<asp:TextBox ID="TextBox1" runat="server" Width="243px">asp:TextBox>
<asp:Button ID="Button1" runat="server" Text="Fetch Link" OnClick="Button1_Click" />td>
tr>
<tr>
<td style="width: 100px">
td>
<td style="width: 100px">
<asp:GridView ID="GridView1" runat="Server">
asp:GridView>
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.Collections.Generic;
using System.Text.RegularExpressions;
using System.Net;
using System.IO;

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

}
public static List<string> GetAllUrlsFromUri(Uri urlToScrape)
{
//the list that would hold the urls
List<string> listOfUrls = new List<string>();
//the search pattern that we are going to use for our regular expression
string searchPattern = "href\\s*=\\s*(?:(?:\\\"(?[^\\\"]*)\\\")|(?[^\\s]* ))";

//get the contents of the page and put it to a string
string pageContents = GetPageContents(urlToScrape);

//our regular expression should ignore case
Regex regEx = new Regex(searchPattern, RegexOptions.IgnoreCase);

//get all the maching values generated by our regular expression
Match match = regEx.Match(pageContents);

//loop thru all the matching strings
while (match.Success)
{
//assign the match value to a temporary placeholder
string urlFound = match.Value;

//check to see if the url does not include the full path(e.g: default.aspx)
if (listOfUrls.IndexOf(urlFound) < 0)
{
string urlToAdd = urlFound;
if (urlFound.StartsWith("href=\"javascript:"))
{
//do nothing, we need to display it as is.
}
else if (urlFound.StartsWith("href=\"/") || !urlFound.StartsWith("href=\"http://"))
{
//add the scrape url to the beginning of our found string
urlToAdd = urlFound.Insert(6, urlToScrape.OriginalString);
}
//add the url to our list
listOfUrls.Add(urlToAdd);
}
//move to the next match result
match = match.NextMatch();
}

//return the list of urls that we have recovered from the site
return listOfUrls;
}

///
/// Reads a webpage and captures it html representation into a string
///

/// the website you want to read
/// the html representation of the site
private static string GetPageContents(Uri urlToScrape)
{
HttpWebResponse httpWebResponse = null;
StreamReader streamReader = null;
string pageContents = String.Empty;

try
{
//create a webrequest object for the url
WebRequest webRequest = WebRequest.Create(urlToScrape);
//convert the webrequest to an httpwebrequest
HttpWebRequest httpWebRequest = (HttpWebRequest)webRequest;
//assign a timeout value for the process
httpWebRequest.Timeout = 100000;

//create a webresponse object to hold the response generated for our request
WebResponse webResponse = httpWebRequest.GetResponse();
//convert the webresponse to httpwebresponse
httpWebResponse = (HttpWebResponse)webResponse;

//get the response stream and assign it to our streamreader
streamReader = new StreamReader(httpWebResponse.GetResponseStream());

//read the contents of the stream
pageContents = streamReader.ReadToEnd();
}
catch (Exception ex)
{
//buble up the error
throw ex;
}
finally
{
//close our webresponse object
httpWebResponse.Close();
//close our streamreader object
streamReader.Close();
}

//return the page contents
return pageContents;
}

///
/// Saves our list of urls to a text file
///

/// the list containing the urls
/// the filename created for the file
public static string SaveToFile(List<string> listOfUrls)
{
//the file name
string fileName = String.Format("{0}.{1}", Guid.NewGuid(), "txt");

//create a streamwriter for our file
StreamWriter sw = File.CreateText(fileName);

//loop thru each string in our collection
foreach (string url in listOfUrls)
{
//write the string to our file
sw.WriteLine(url);
}

//close oour streamwriter
sw.Close();

//return our filename
return fileName;
}
protected void Button1_Click(object sender, EventArgs e)
{
//the url to scrape
Uri urlToScrape = new Uri(TextBox1.Text);
//the list that would contain the urls recovered from the specified uri
List<string> listOfUrls = GetAllUrlsFromUri(urlToScrape);

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

Creating an AJAX-Enabled Grid With Cell Edit



In this post i will show how to edit the cell of gridview on doubleclicking and also how to update server side data without refreshing the page.

The key advantages of this grid are as follows

* Data will be bind to grid only once, i.e. on page load.
* Only modified data goes to server to update the grid.





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


DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Untitled Pagetitle>

<script type = "text/javascript" >
var ddlId = new Array();
function MakeCellEditable(obj) {
if(!window.document.getElementById(obj.id + "_input")) {
if(document.all) {
obj.innerHTML = " + obj.id + "_input" + " type=text value='" + obj.innerText + "'/>" }
else {
obj.innerHTML = "+ obj.id + "_input" + " type=text value='" + obj.textContent + "'/>" }
}
window.document.getElementById(obj.id + "_input").focus();
}
function UpdateGrid(args) {
<%= ClientScript.GetCallbackEventReference(this, "args", "ShowResult", null) %> ;
}
function JSUpdateTable() {
var ddl = window.document.getElementById('Gridview');
var ddl1 = ddl.getElementsByTagName('input');
var data = "";
for(i = 0 ; i < ddl1.length ; i++) {
ddlId[i] = ddl1[i].id;
//ddlId is a global array in JS we will use it in step 9
if(i == 0 ) data = ddl1[i].id + "|" + ddl1[i].value;
else data = data + "~" + ddl1[i].id + "|" + ddl1[i].value;
}
UpdateGrid('updateTable$' + data);
}
function UpdateGrid(args) {
<%= ClientScript.GetCallbackEventReference(this, "args", "ShowResult", null) %> ;
}
function ShowResult(eventArgument , context) {
//debugger;
formObj = window.document;
if(eventArgument == "SUCCESS") {
for(j = 0 ; j < ddlId.length ; j++) {
var ids = ddlId[j].split("_");
formObj.getElementById(ids[0] + "_" + ids[1]).innerHTML = formObj.getElementById(ddlId[j]).value;
}
document.getElementById('ServerMsg').innerText = "Data has been updated Successfully...";
}
}
script>
head>
<body>
<form id="form1" runat="server">
<div id="Gridview">
<asp:GridView EnableViewState="False" runat="server" ID="_grid" OnRowDataBound="_grid_RowDataBound" CellPadding="4" ForeColor="#333333" GridLines="None">
<FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
<EditRowStyle BackColor="#999999" />
<SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
<PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
<HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<AlternatingRowStyle BackColor="White" ForeColor="#284775" />
asp:GridView>
<span id="ServerMsg">span>
div>
<br />
<input type="button" value="Update" onclick="javascript: JSUpdateTable ();" />
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 AjaxEnabledGrid : System.Web.UI.Page, ICallbackEventHandler
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
_grid.DataSource = _sampleData;
_grid.DataBind();
}
}
string result;
public DataTable _sampleData
{
get
{
DataTable dt = (DataTable)Session["DataTable"];
if (dt == null)
{
dt = new DataTable();
dt.Columns.Add(new DataColumn("Contact Name", typeof(string)));
dt.Columns.Add(new DataColumn("Company Name", typeof(string)));
dt.Columns.Add(new DataColumn("City", typeof(string)));
dt.Columns.Add(new DataColumn("Country", typeof(string)));

dt.Rows.Add(new object[] { "Maria Anders", "Alfreds Futterkiste", "Berlin", "Germany" });
dt.Rows.Add(new object[] { "Ana Trujillo", "Emparedados y helados ", "México D.F.", "Mexico" });
dt.Rows.Add(new object[] { "Antonio Moreno", "Antonio Moreno Taquería", "México D.F.", "Mexico" });
Session["DataTable"] = dt;
}
return dt;
}
set
{
Session["DataTable"] = value;
}
}
int _rowNumber;

protected void _grid_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
for (int i = 0; i < e.Row.Cells.Count; i++)
{
e.Row.Cells[i].Attributes.Add("ondblclick", "javascript:MakeCellEditable(this);");
e.Row.Cells[i].Attributes.Add("id", _rowNumber + "_" + i);
}
_rowNumber += 1;
}
}

public void RaiseCallbackEvent(string eventArgument)
{
string[] args = eventArgument.Split('$');
if (args[0] == "updateTable") updateTable(args[1]);
}

public string GetCallbackResult()
{
return result;
}
private void updateTable(string _data)
{
string[] _NewData = _data.Split('~');
DataTable _tempTable = _sampleData;
for (int i = 0; i < _NewData.Length; i++)
{
string[] _changedTxt = _NewData[i].Split('|');
string[] _rowCol = _changedTxt[0].Split('_');
_tempTable.Rows[Convert.ToInt32(_rowCol[0])][Convert.ToInt32(_rowCol[1])] = _changedTxt[1];
}
_sampleData = _tempTable;
result = "SUCCESS";
}
}

JSON and Web Services





Some APIs now offer JSON as an alternative to XML. All of Yahoo’s Web
Services can return JSON if it’s requested. If you’d like to try using the Yahoo
Search API, sign up for an application ID at http://api.search.yahoo.com/
webservices/register_application.
My own application ID is "Etyl7xbV34Fcahn3QIHzGnpWrqwHyFKsckWdnJtUj82hE6xVTMVHWGqQmxQqlGDHK5QtvjM-". Substitute your own ID in this function:


   1:  function searchYahoo(query) {

   2:  var url = "http://api.search.yahoo.com/NewsSearchService/

   3:  V1/newsSearch?";

   4:  url+= "appid=Etyl7xbV34Fcahn3QIHzGnpWrqwHyFKsckWdnJtUj82hE6xVTMVHWGqQmxQqlGDHK5QtvjM-";

   5:  url+= "&query="+escape(query);

   6:  url+= "&output=json";

   7:  url+= "&callback=parseResponse";

   8:  getScript(url);

   9:  }


The searchYahoo function puts together a URL with the required parameters
for a search. The search term itself is passed as an argument, query. The
other required parameter is the application ID, appid.
There are two optional parameters added to the URL. The first, output, is
given a value of json, indicating that the results should be returned in JSON
rather than XML. The other parameter, callback, indicates that the JSON
data should be evaluated and passed to the function parseResponse.

Checkout this complete code

jsonsearch.js




// JScript File
function getScript(url) {
var scripttag = document.createElement("script");
scripttag.setAttribute("type", "text/javascript");
scripttag.setAttribute("src", url);
document.getElementsByTagName("head")[0].appendChild(scripttag);
}
function searchYahoo(query) {
var url = "http://api.search.yahoo.com/NewsSearchService/V1/newsSearch?";
url += "appid=Etyl7xbV34Fcahn3QIHzGnpWrqwHyFKsckWdnJtUj82hE6xVTMVHWGqQmxQqlGDHK5QtvjM-";
url += "&query=" + escape(query);
url += "&output=json";
url += "&callback=parseResponse";
getScript(url);
}
function parseResponse(data) {
// empty the div
var results = document.getElementById("results");
while (results.hasChildNodes()) {
results.removeChild(results.lastChild);
}
// loop through the search results
for (var i = 0; i < data.ResultSet.Result.length; i++) {
var title = data.ResultSet.Result[i].Title;
var summary = data.ResultSet.Result[i].Summary;
var url = data.ResultSet.Result[i].Url;
// create the headline link
var header = document.createElement("h2");
var link = document.createElement("a");
link.setAttribute("href", url);
var text = document.createTextNode(title);
link.appendChild(text);
header.appendChild(link);
// create the summary paragraph
var para = document.createElement("p");
var paratext = document.createTextNode(summary);
para.appendChild(paratext);
// insert the markup
results.appendChild(header);
results.appendChild(para);
}
}






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>

<script src="Js/jsonsearch.js">script>

<title>Untitled Pagetitle>
head>
<body>
<h1>
Yahoo! News Searchh1>
<form onsubmit="searchYahoo(this.query.value); return false">
<fieldset>
<label>
Search forlabel>
<input type="text" name="query" />
<input type="submit" value="Search" />
fieldset>
<div id="results">
div>
form>
body>
html>

How To Add Mutually Exclusive CheckBox inside GridView





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

DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Untitled Pagetitle>
<script type="text/javascript" language="javascript">
function uncheckOthers(id)
{
var elm = document.getElementsByTagName('input');
for(var i = 0; i < elm.length; i++)
{
if(elm.item(i).id.substring(id.id.lastIndexOf('_')) == id.id.substring(id.id.lastIndexOf('_')))
{
if( elm.item(i).type == "checkbox" && elm.item(i)!=id)
elm.item(i).checked = false;
}
}
}
script>
head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" OnRowDataBound="GridView1_RowDataBound"
CellPadding="4" ForeColor="#333333" GridLines="None">
<Columns>
<asp:TemplateField HeaderText="Select">
<ItemTemplate>
<asp:CheckBox ID="CheckBox1" runat="server" />
ItemTemplate>
asp:TemplateField>
<asp:BoundField DataField="Contact Name" HeaderText="Name" />
Columns>
<FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
<PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
<SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
<HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<EditRowStyle BackColor="#999999" />
<AlternatingRowStyle BackColor="White" ForeColor="#284775" />
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 MutuallyexGrid : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
GridView1.DataSource = _sampleData;
GridView1.DataBind();
}

}
public DataTable _sampleData
{
get
{
DataTable dt = (DataTable)Session["DataTable"];
if (dt == null)
{
dt = new DataTable();
dt.Columns.Add(new DataColumn("Contact Name", typeof(string)));
dt.Columns.Add(new DataColumn("Company Name", typeof(string)));
dt.Columns.Add(new DataColumn("City", typeof(string)));
dt.Columns.Add(new DataColumn("Country", typeof(string)));

dt.Rows.Add(new object[] { "Maria Anders", "Alfreds Futterkiste", "Berlin", "Germany" });
dt.Rows.Add(new object[] { "Ana Trujillo", "Emparedados y helados ", "México D.F.", "Mexico" });
dt.Rows.Add(new object[] { "Antonio Moreno", "Antonio Moreno Taquería", "México D.F.", "Mexico" });
Session["DataTable"] = dt;
}
return dt;
}
set
{
Session["DataTable"] = value;
}
}
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
try
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
string strScript = "uncheckOthers(" + ((CheckBox)e.Row.Cells[0].FindControl("CheckBox1")).ClientID + ");";
((CheckBox)e.Row.Cells[0].FindControl("CheckBox1")).Attributes.Add("onclick", strScript);
}
}
catch (Exception Ex)
{
//report error
}
}
}

How To Enable Disable Textbox in Footer




<%@ 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">
public void Page_Load()
{
if (!IsPostBack)
{
GridView1.DataSource = _sampleData;
GridView1.DataBind();
}
}

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Footer)
{
(e.Row.FindControl("txtDiscountOnTotal") as WebControl).Enabled = (comboDiscountType.SelectedValue == "2");
}
else if (e.Row.RowType == DataControlRowType.DataRow)
{
(e.Row.FindControl("txtDiscountOnItem") as WebControl).Enabled = (comboDiscountType.SelectedValue == "1");
}
}

protected void comboDiscountType_SelectedIndexChanged(object sender, EventArgs e)
{
(GridView1.FooterRow.FindControl("txtDiscountOnTotal") as WebControl).Enabled = (comboDiscountType.SelectedValue == "2");
foreach (GridViewRow row in GridView1.Rows)
{
(row.FindControl("txtDiscountOnItem") as WebControl).Enabled = (comboDiscountType.SelectedValue == "1");
}
}
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", "XX", "12.43", });
dt.Rows.Add(new object[] { "2", "XX1", "11.43", });
dt.Rows.Add(new object[] { "3", "XX2", "13.43", });
Session["DataTable"] = dt;
}
return dt;
}
set
{
Session["DataTable"] = value;

}
}

script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>Untitled Pagetitle>
head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="GridView1" runat="server" OnRowDataBound="GridView1_RowDataBound"
ShowFooter="true" AutoGenerateColumns="false">
<Columns>
<asp:BoundField DataField="Item" HeaderText="Item " />
<asp:BoundField DataField="Price" HeaderText="Price" />
<asp:TemplateField HeaderText="Discount">
<ItemTemplate>
<asp:TextBox ID="txtDiscountOnItem" Width="50px" runat="Server" />
ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtDiscountOnTotal" Width="50px" runat="Server">asp:TextBox>
FooterTemplate>
asp:TemplateField>
Columns>
asp:GridView>
<asp:DropDownList ID="comboDiscountType" runat="server" AutoPostBack="True" OnSelectedIndexChanged="comboDiscountType_SelectedIndexChanged">
<asp:ListItem Value="1">Discount on Itemsasp:ListItem>
<asp:ListItem Value="2">Discount on Totalasp:ListItem>
asp:DropDownList>
div>
form>
body>
html>

How To Read GridView Cell value using Javascript





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

DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Untitled Pagetitle>

<script type="text/javascript"> function Read() {
var oDataGrid = document.getElementById("<%= GridView1.ClientID %>")
var tableRows = oDataGrid.rows;
var rawDataRows = new Array();
//somewhere to put the actual data
for (var i = 0; i < tableRows.length; i++) {
var thisRow = tableRows[i];
for (var j = 0; j < thisRow.cells.length; j++) {
alert(oDataGrid.rows(i).cells(j).innerHTML);
}
}
}
script>

head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:BoundField DataField="Item" HeaderText="Item " />
<asp:BoundField DataField="Price" HeaderText="Price" />
Columns>
asp:GridView>
<asp:Button ID="Button1" runat="server" Text="Button" OnClientClick="Read();" />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 ReadGridView : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
GridView1.DataSource = _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", "XX", "12.43", });
dt.Rows.Add(new object[] { "2", "XX1", "11.43", });
dt.Rows.Add(new object[] { "3", "XX2", "13.43", });
Session["DataTable"] = dt;
}
return dt;
}
set
{
Session["DataTable"] = value;
}
}
}

How To Select GridView Row using Javascript





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


DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Untitled Pagetitle>
<script type="text/javascript">
function rowBind()
{
var navRoot,node,dgRowid = null,tBody,rwVal;
var Prev = null,Curr = null;

if(document.all && document.getElementById)
{
navRoot = document.getElementById('<%=GridView1.ClientID %>');

if(navRoot != null)
{
tBody = navRoot.childNodes[0];

for(i=0;i {
node = tBody.childNodes[i];
if(node.tagName == "TR")
{
node.onmousedown = function()
{
dtRowid = this.rowIndex;
rVal = dtRowid+2;
if(dtRowid < 8)
{
rwVal = 'GridView1$ctl0'+ rVal+'$txtAuId';
}
else
{
rwVal = 'GridView1$ctl0'+rVal+'$txtAuId';
}

var ctrl1 = document.getElementById(rwVal);
if(Prev != null)
{
node.parentElement.children[Prev].style.background = "#FFFFFF";
}
Curr = this.rowIndex;
if(Curr != null)
{
node.parentElement.children[Curr].style.background = "#D8E8FF";
Prev = Curr;
}
alert(ctrl1.value);
}
}
}
}
}
}

script>
head>
<body onload="rowBind();">
<form id="form1" runat="server">
<div>
<asp:GridView ID="GridView1" ShowHeader="false" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:TextBox ID="txtAuId" ReadOnly="true" runat="server"
Text='<%# Bind("Item") %>'
Style="background-color: Transparent; border: 0px;">
asp:TextBox>
ItemTemplate>
asp:TemplateField>
<asp:BoundField DataField="Item" HeaderText="Item " />
<asp:BoundField DataField="Price" HeaderText="Price" />
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 SelectRowUsingJavascript : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
GridView1.DataSource = _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;
}
}
}

How To Create Dynamic Div Using Javascript





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

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>Javascript create new divtitle>
<style type="text/css">
.dynamicDiv {
width : 200px;
height : 100px;
border : solid 1px #c0c0c0;
background - color : #e1e1e1;
font - size : 11px;
font - family : verdana;
color : #000;
padding : 5px;
}
style>

<script type="text/javascript" language="javascript"> function createDiv() {
var divTag = document.createElement("div");
divTag.id = "div1";
divTag.setAttribute("align", "center");
divTag.style.margin = "0px auto";
divTag.className = "dynamicDiv";
divTag.innerHTML = "This HTML Div tag is created using Javascript DOM dynamically.";
document.body.appendChild(divTag);
}
script>

head>
<body>
<input id="btn1" type="button" value="create div" onclick="createDiv();" />
body>
html>


In the above example Javascript code to create new div HTML tag we have used the appendChild method for document body element. appendChild method takes one parameter as the name of the object of newChild that you want insert into the specified HTML tag like body tag in the above example. You can use the document.getElementById method of javascript passing the id value of any HTML tag along with appendChild method to insert the dynamic new HTML element into the specified id of the HTML tag. In the next

Cut, Copy, Paste With Windows Explorer

Hi Experts,

I have created a custom dialog in VB.NET. Can anyone give me a working example of how I can cut, copy & paste files (both ways) between my dialog and the Windows Explorer.

Thanks

Weeks in year using ASP.NET

Hi,

Following code should give the number of weeks in years 1998-2010 for a
Danish calendar (on a Danish box)


Does any one have a solution to this problem.


GregorianCalendar cal = new GregorianCalendar();
for(int i = 1998; i < 2010; i++)
{
DateTime date = new DateTime(i, 12, 31);
int week= cal.GetWeekOfYear(date,
CalendarWeekRule.FirstFourDayWeek,
DayOfWeek.Monday);
Debug.WriteLine( String.Format("Last week in year {0:0} = {1:0}", date.Year,
week));
}

Last week in year 1998 = 53 - OK
Last week in year 1999 = 52 - OK
Last week in year 2000 = 52 - OK
Last week in year 2001 = 53 - Wrong, only 52
Last week in year 2002 = 53 - Wrong, only 52
Last week in year 2003 = 53 - Wrong, only 52
Last week in year 2004 = 53 - OK
Last week in year 2005 = 52 - OK
Last week in year 2006 = 52 - OK
Last week in year 2007 = 53 - Wrong, only 52
Last week in year 2008 = 53 - Wrong, only 52
Last week in year 2009 = 53 - Wrong, only 52

Failed to load database information. Details: The database DLL 'crdb_oracle.dll' could not be loaded

Failed to load database information. Details: The database DLL 'crdb_oracle.dll' could not be loaded. Error in File C:\WINDOWS\TEMP\HotelManagment1 {881E06F4-5020-46E1-B0C5-7B3B34F39BAE}.rpt: Failed
I am Recieving this error while exporting crystal report to adobe acrobat reader and this is my code.

Private Const REPORT_NAME As String = "HotelManagment1.rpt"
Dim objRD As New CRPT.ReportDocument
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Try
If ConfigureCrystalReport() Then
GenerateDesignationReport()
End If
Catch ex As Exception
End Try
End Sub
Private Sub GenerateDesignationReport()
Dim InvoinceNO As String = Request.QueryString("InvoinceNo")
Try
'objRD.SetDatabaseLogon("", "", "", "", False)
objRD.SetParameterValue("InvoiceNo", InvoinceNO)
Response.BufferOutput = False
objRD.ExportToHttpResponse(ExportFormatType.PortableDocFormat, Response, True, InvoinceNO & "-HotelManagment1.pdf")

Catch ex As Exception
Label1.Text = ex.Message.ToString
End Try
End Sub
Private Function ConfigureCrystalReport() As Boolean
Dim sReportPath As String
Dim bStatus As Boolean
sReportPath = MapPath(REPORT_NAME)
objRD = New CRPT.ReportDocument
Try
objRD.Load(sReportPath)
Dim objLI As New CrystalDecisions.Shared.TableLogOnInfo

objLI.ConnectionInfo.ServerName = ""
objLI.ConnectionInfo.UserID = ""
objLI.ConnectionInfo.Password = ""

objRD.Database.Tables("master_hotel").ApplyLogOnInfo(objLI)
objRD.Database.Tables("detail_hotel").ApplyLogOnInfo(objLI)

bStatus = True
Catch ex As Exception
End Try
Return bStatus
End Function
End Class

In-Assembly Request Handling (ASP.NET/VB.NET)

Experts,

I am attempting to develop a .NET assembly for ASP.net to serve up images from a database. I envisage two classes - one a data access object to handle loading/saving images from/to the database; secondly a custom control to render the the image to a page.

The first of these works perfectly, saving and retrieving images to and from the database and providing a data stream as needed. No issues here at all. Currently, however, each separate project that makes use of this class must provide its own custom handler to serve the images for the browser requests.

What I would like is to provide my own custom control that makes use of the database access class. This control would then render an img tag thus:



What can I put in the src attribute to make this work? I need a url that the server will direct to my assembly so that I can serve up the required image. For static images one would use the Web Resource method but I can't see a way of making that work in this case.

This is using .NET Framwork 2.x.

Many thanks for any assistance and pointers.

Grant automatic read-access to a secured file via link

Hi,
I have a web application that requires authentication in order to access some pages. I also have a windows service that sends and email that contains a link to the pages mentioned before; however the user that receives the email shouldn't need to log-on in order to open these files.
How can I grant automatic access to a user via a URL link? I was thinking of creating a GUID for the user, save it in the DB, include it in the URL link and once cliked on it, to validate it agains the user details (userame/password). That looks a bit messy to me and I wonder if theres a better method.
Thanks

MAC error when page is not fully loaded

Hi,
I get a "Validation of viewstate MAC failed." Error when clicking on some asp.net postback button when page is not fully loaded. This started to happen when I've added Banners to the page.
If I wait for the page to be fully loaded then everything's ok. How to fix this error?

Thanks,

Read Reg Binary Registry key using C#

how to Reg_Binary Registry key using c#

Crystal reports .NET - Invalid argument for database - When changing databases

We have some crystal reports that were created in Visual Studio 2005 that have worked very well when they were linked to a Microsoft Access database. Our company's data footprint has grown and we have converted all of our production data to SQL server 2005. Changeing the data sources location inide the crystal reports designer is easy and fairly straightforward. However there is one report that I cannot get to run after I had updated the data sources location. The report has a connection to two tables and also contains a sub-report that is connected to the same two tables. The tables are almost exactly the same as the ones in Access that it was previously connected to. In fact, we used the Access to SQL converter to convert them. We have only added a few fields to it. Why is it that when I run the report in ASP.net it comes up with the error "Invalid Argument provided. Error in File (report).rpt: Invalid argument for database."?

.Net Web Browser Component has problems with pages that Internet Explorer Browser does not, Why is this?

I am completely confused. Seems to be getting a common occurance lately. :)

I have been wanting to embed a web browser inside a C# .Net winforms application. So I started doing some testing and it seems that the .Net WebBrowser component, in both the .Net 2.0 and 3.0 frameworks does not work the same as IE. Although all this is is a wrapper to shdocvw.dll (The IE ActiveX compoent), correct? But the ActiveX has problems too.

I drug the WebBrowser component onto a new form, added a text box and a button to enter a URL.

Then I did some testing against IE. I have found one site that seems to act totally goofy with the .Net componet and works perfectly with the standard IE 6 and 7 browsers.

The site is http://www.zillow.com

The are gobs of issues, but it looks like it may have a problem with scripting. Even though IE works perfectly.

Does anyone have any idea why this site would have problems with the .Net compoent and not with IE? Does this mean that I will have problems using this component on other sites. Some seem to be fine and some don't but this one was the biggest offender.

Finally, does anyone know if there is a good light weight, easy to deploy, third party ActiveX or .Net browser onthe market that we could buy that has a good feature set.

Thanks very much in advance.

The path is already mapped in workspace - Team Foundation Server

I'm getting the following error while trying to build my TFS project in VS 2008. I've tried deleting / recreating the build definition and clearing out my local TFS cache. I've also reset all my TFS workspaces. Any suggestions? My machine name is WKS7104083 and our TFS Server name is TFSPROD

The path F:\bld\vo_dmt\sspt_common_1.0.0\Sources\SSPT_Common\Source is already mapped in workspace EDCWAPPP183V_76.

My machine

Permission to write to EventLog from C# / VB .NET

Hello,
I have application which need to write to windows event log. I've created additional log in windows and granted full control on it to ASPNET user. The developer writing web application reported that he encoutered security problem while trying to write to event log.
So I created windows form application (One form with one button) code below and run on the server.
I got this error:
"Application attepted to perform an operation not allowed by the security policy. To grant this application the request permission, contact your system administrator, or use the Microsoft .NET Framework Configuration tool.
Request for the permission of type
'System.Diagnostics.EventLogPermission,System,Version=2.0.0.0,Culture=neutral,PublicKeyToken=b77a5c561934e089' failed."

What should I do? Please give very detailed information what and how, because I've never used .NET framework configuration.
Best Regards.
FooKy





private void button1_Click(object sender, EventArgs e)
{
counter++;
label1.Text = "NO: " + counter;
System.Diagnostics.EventLog el = new System.Diagnostics.EventLog(textBox1.Text);
el.Source = "MyApp";
el.WriteEntry("MyMessage",System.Diagnostics.EventLogEntryType.Information);
}

UpdatePanel and Placeholder Control Problem

Hello everyone,

I am having some problems with this page that has a Placeholder control inside an UpdatePanel control. When the updatepanel is triggered, then the page seems to do a full postback and I end up with 2 sets of controls added to the page instead of 1.

Here is where I'm creating the updatepanel and placeholder:










Here is the code behind:
protected void Page_Load(object sender, EventArgs e)
{
...
if (!IsPostBack)
{
//Enable Save Buttons
btnSave1.Enabled = true;
btnSave2.Enabled = true;
//Set Course Title
lblCourseTitle.Text = crs.courTitle;
}
//Display Semesters and each Location
ArrayList sems = Semester.getSemesterList(DateTime.Now, sqlCon);
DisplaySemesters(crs, sems, sqlCon);
...
}
private void DisplaySemesters(Course crs, ArrayList Semesters, SqlConnection sqlCon)
{
//Go through each semester, and display all location frequencies
plhSemesters.Controls.Clear();
...
//TextBox for Course Frequency
TextBox txtCFLoc = new TextBox();
txtCFLoc.ID = "txt" + sem.semId + loc.locId;
txtCFLoc.CssClass = "TextBox";
txtCFLoc.MaxLength = 2;
...
if (i % 2 == 0) { plhSemesters.Controls.Add(new LiteralControl("")); }
else { plhSemesters.Controls.Add(new LiteralControl("")); }
plhSemesters.Controls.Add(new LiteralControl("" + loc.locCity + ""));
plhSemesters.Controls.Add(new LiteralControl(""));
plhSemesters.Controls.Add(txtCFLoc);
plhSemesters.Controls.Add(new LiteralControl(""));
plhSemesters.Controls.Add(new LiteralControl(""));
plhSemesters.Controls.Add(new LiteralControl(""));
...
}


When I click on one of the linkbuttons to trigger the updatepanel, I get a full page postback and 2 sets of controls.

Is there a bug with the updatepanel and placeholder controls or am I doing something wrong?

ImageButton in Gridview Template Column

Hello All,
I have a Gridview control (dgDocuments) and in it I have a template column with two images in it. An up arrow and a down arrow. When either of these is clicked it runs the onclick event of the ImageButton. This works fine. My problem is that I want to ascertain the ID of the line on which the Image was clicked. I have tried every version of dgDocuments.SelectedRow.Cells(0).Text etc but I am getting Object reference not set to an instance of an object. Does anyone have any ideas on the correct syntax for this??? Here is my OnClick event:-

Protected Sub imgUpArrow_Click(ByVal sender As System.Object, ByVal e As System.Web.UI.ImageClickEventArgs)
Dim parameterReturn As SqlParameter
Dim ReturnVal As Integer

Try
Open_Connection()
cmd = New SqlCommand("sp_Update_Reference_Documentation_Up", conn)
cmd.CommandType = CommandType.StoredProcedure
cmd.Parameters.AddWithValue("@Id", dgDocuments.SelectedRow.Cells(0).Text)
cmd.Parameters.AddWithValue("@Sort_Order", dgDocuments.SelectedRow.Cells(2).Text)
cmd.Parameters.AddWithValue("@UserId", Session("UserId"))
cmd.Parameters.AddWithValue("@Document_Id", lblDocument_Id.Text)
parameterReturn = New SqlParameter("@ReturnValue", SqlDbType.Int)
parameterReturn.Direction = ParameterDirection.ReturnValue
cmd.Parameters.Add(parameterReturn)
cmd.ExecuteNonQuery()
If ReturnVal = cmd.Parameters("@ReturnValue").Value = 1 Then
FillDocuments()
Else
' do nothing
End If
Catch ex As Exception

End Try
End Sub

Thanks in advance,

Unable to find a version of the runtime to run this application

1. I have installed .NET Framework 1.1 + 2.0 on my Windows XP system.
3. When i first install the framework everything works fine
after few days that the application working i get this message :
".NET Framework initialization error" "Unable to find a version of the runtime to run this application" .
ih the app has a App.Config file that specifies the correct version of the runtime to use ...
What is this problem ??? I've googled lot's of info on the net but haven't been able solve the problem ...

i reinstall the xp and reinstall dotnet framework but the problem comback again

Thanks !!!

ASP.NET 2.0 Gridview UPDATE command. Must declare the scalar variable "@ItemKey".

Ok, I'm trying to use the UPDATE command with the embedded gridview. Upon using the UPDATE command, I need to specify which column is being worked on. The prime candidate for this is a unique identifier field I have called ItemKey. So, here's my statement: UPDATE Items SET ProductName = @ProductName, Category = @Category, Price = @Price, SandH = @SandH, Tax = @Tax WHERE (ItemKey = @ItemKey).
Everything works fine except for when it tries to use the identifying row. "(ItemKey = @ItemKey)". I get the error message "Must declare the scalar variable "@ItemKey"." All the other paramaters seem to magically appear so I can use them, why is @ItemKey not appearing? Thanks, Chris.

Bind datagridview textbox and combobox columns to datatable

Hi,
I have a datagrid