Sie sind auf Seite 1von 233

1.

Development and Deployment Issues FAQ Home

1.1 Why are Server control tags shown in the browser instead of the
controls it represents?

This is because the server control tags were not converted into their respecting HTML element tags by

ASP.Net. This happens when ASP.Net is not properly registered with IIS.

.Net framework provides an Administration utility that manages the installation and uninstallation of multiple

versions of ASP.NET on a single machine. You can find the file in

C:\WINNT\Microsoft.NET\Framework\v**\aspnet_regiis.exe

use the command: aspnet_regiis.exe -u ---> to uninstall current asp.net version.

use the command: aspnet_regiis.exe -i ---> to install current asp.net version.

1.2 How To Repair ASP.Net IIS Mapping After You Remove and Reinstall
IIS?

To reassociate aspx file extensions with ASP.Net runtime, you'll have to run the utlity aspnet_regiis.exe -i

For more information refer to Microsoft Knowledge Base Article - 306005

1.3 Why do I get "HTTP 500" error (or "(DLL) initialization routine
failed") in my browser?

This is because if you have the /3GB boot switch enabled, the ASP.NET worker process (Aspnet_wp.exe) does

not start. For more information see Microsoft Knowledge Base Article - 320353

To create and set the "ASPNETENABLE3GB" environment variable as mentioned in the above article, right

click MyComputer ->Properties->Advanced > Environment Variables > System variables > New.

Add the variable name in the top text box and the value in the lower textbox.

1.4 I have recently move my Web application from Windows 2k to


Windows Server 2003. All works fine in Windows 2K but i am not able to
view pages using Windows Server 2003?

You have to enable the ASP.NET in the Web Server Extensions list

From Start -> Settings -> Control Panel -> Administrative Tools -> double click IIS Manager.

Go to the Web Service Extensions tab, click Active Server Pages, then press the "Allow" button on the left.

1.5 What are the Best practices for side-by-side execution of Framework
1.0 and 1.1?

In ASP.NET, applications are said to be running side by side when they are installed on the same computer,

but use different versions of the .NET Framework. The following article at www.asp.net details the practices

that are recommended ASP.NET Side-by-Side Execution of .NET Framework 1.0 and 1.1
1.6 Can I have VS.NET and the Visual Studio 6.0 installed on the same
machine?

Yes! VS.Net works with the .Net framework, while VS6.0 works with MFC or the Windows API directly, for the

most part. They can be installed and run on the same machine without any considerations.

1.7 How should I check whether IIS is installed or not?

To verify if IIS is installed, go to your 'Add or Remove Programs' utility in the Control panel and click on

the 'Add/Remove Windows Components' in the side menu.

On XP Pro and below, you should see an item called "Internet Information Services (IIS)". If this is checked,

IIS should be installed.

On Win2K3, you'll see "Application Server". If this is checked, select it and then click 'Details'. Another

form should open which will contain "Internet Information Services (IIS)". If it is checked, IIS should be

installed.

1.8 In Visual Studio .NET, how do I create a new ASP.NET application for
an existing ASP.NET project?

First create an IIS application using the IIS MMC. Then in Visual Studio .NET, use the "New Project In Existing

Folder" project template (at the end of the template list). It will first ask you for the project name (use the

same one you created for the IIS application). Click OK button. Then enter in physical folder location.

1.9 Why do I get the error message "Server Application Unavailable The
web application you are attempting to access on this web server is
currently unavailable. Please hit the "Refresh" button in your web
browser to retry your request."?

By default, ASP.NET runs its worker process (Aspnet_wp.exe) with a weak account (the local machine

account, which is named ASPNET) to provide a more secure environment. On a domain controller or on a

backup domain controller, all user accounts are domain accounts and are not local machine accounts.

Therefore, Aspnet_wp.exe fails to start because it cannot find a local account named

"localmachinename\ASPNET". To provide a valid user account on the domain controller, you must specify an

explicit account in the section of the Machine.config file, or you must use the SYSTEM account. For more

details : FIX: ASP.NET Does Not Work with the Default ASPNET Account on a Domain Controller

1.10 In Visual Studio .NET, how do I create a new ASP.NET application


which does not have a physical path under wwwroot?

You must first create an IIS application using the IIS MMC. Then in Visual Studio .NET, create a new ASP.NET

application and give it the same name you used for the IIS application

1.11 Why do I get the "Unable to find script libruary


'WebUIValidation.js'" error ?
When you install the .Net framework on your web server, it installs some script files (including the above)

under the root folder (usually "C:\inetput\wwwroot" if you do a default installation) . You can then find the

above file at "C:\Inetpub\wwwroot\aspnet_client\system_web\1_1_4322", for example.

The above problem could happen if you reconfigured your web root directory to be a different one after you

installed ASP.Net in your web server. If that is the case, then run 'aspnet_regiis -c' (utility is under

%windir%\Microsoft.NET\Framework\v1.1.4322, for example) or copy over manually the above script files

into a similar sub-directory below your current web root directory. Also, if you look at the error message in

detail, you will notice where the file is supposed to be.

1.12 After installing .NET Framework SP1 the client side validations, or
rather validator controls are not working?

The problem seems to be in the javascript file WebValidationUi.js in aspnet_client folder.The changes in that

file prevent a page to be submitted. That could be the reason your javascript validations are not working. As

a workaround, just copy the old WebValidateionUi.js over the new one.

1.13 How to Configure the ASP.NET Version to use for Each


Application(developed using 1.0 or 1.1)?
To configure WebApp1 to use ASP.NET 1.0, follow these steps:

1. Click Start, and then click Run.

2. In the Open text box, type cmd, and then click OK.

3. At the command prompt, locate the following directory:

WindowsDirectory\Microsoft.NET\Framework\v1.0.3705\

4. At the command prompt, type one of the following commands:

o To Install ASP.NET 1.0 recursively

aspnet_regiis -s W3SVC/1/ROOT/WebApp1

o To Install ASP.NET 1.0 non-recursively

aspnet_regiis -sn W3SVC/1/ROOT/WebApp1

To configure WebApp2 to use ASP.NET 1.1, follow these steps:

1. Click Start, and then click Run.

2. In the Open text box, type cmd, and then click OK.

3. At the command prompt, locate the following directory:

WindowsDirectory\Microsoft.NET\Framework\v1.1.4322\

4. At the command prompt, type one of the following commands:

o To Install ASP.NET 1.1 recursively

aspnet_regiis -s W3SVC/1/ROOT/WebApp2

o To Install ASP.NET 1.1 non-recursively

aspnet_regiis -sn W3SVC/1/ROOT/WebApp2

1.14 How to Configure Different Versions of an ASP.NET Application


Running on the Same Web Server?
Here is an exerpt from the KB article: KB 816782

Find the ASP.NET Version Used for the Application View the script map for an ASP.NET application to

determine the version of ASP.NET that the application uses. To view the script map for an ASP.NET

application, follow these steps:

1. Click Start, point to Programs, and then click Control Panel.

2. Double-click Administrative Tools, and then double-click Internet Information Services (IIS).

3. Expand local computer, expand Web Site, and then expand Default Web Site.

4. Locate the folder that contains the ASP.NET application.

5. Right-click the folder that contains the ASP.NET application, and then click Properties.

6. Click the Directory tab, and then click Configuration. The Application Configuration dialog box opens.

7. Click the Mappings tab, and then select an ASP.NET application extension, such as .asmx or .aspx.

The Executable Path column of the dialog box lists the path to the ASP.NET ISAPI version that the

application uses. By default, the ASP.NET ISAPI is installed in

%WindowsDirectory%\Microsoft.NET\Framework\%versionNumber%. The version number in the

path indicates the version number of the ASP.NET ISAPI that the application uses. The ASP.NET ISAPI

version determines the version of the runtime that the application uses.

2. Basic
2.1 What is ASP.NET?

ASP.NET is a programming framework built on the common language runtime that can be used on a server to

build powerful Web applications.

For more details refer

• What is ASP.NET

• ASP.NET OverView
2.2 Why does my ASP.NET file have multiple <form> tag with
runat=server?

This means that ASP.Net is not properly registered with IIS.

.Net framework provides an Administration utility that manages the installation and uninstallation of multiple

versions of ASP.NET on a single machine. You can find the file in

C:\WINNT\Microsoft.NET\Framework\v**\aspnet_regiis.exe

use the command: aspnet_regiis.exe -u ---> to uninstall current asp.net version.


use the command: aspnet_regiis.exe -i ---> to install current asp.net version.

For Windows Server 2003, you must use aspnet_regiis -i -enable

This is because of the "Web Service Extensions" feature in IIS 6

(if you install VS.NET or the framework without IIS installed, and then go back in and install IIS afterwards,

you have to re-register so that ASP.NET 'hooks' into IIS properly."

2.3 How to find out what version of ASP.NET I am using on my machine?

VB.NET

Response.Write(System.Environment.Version.ToString() )

C#

Response.Write(System.Environment.Version.ToString() );

2.4 Is it possible to pass a querystring from an .asp page to aspx page?

Yes you can pass querystring from .asp to ASP.NET page .asp

<%response.redirect "webform1.aspx?id=11"%>

.aspx

VB.NET
Response.Write (Request("id").ToString ())

C#

Response.Write (Request["id"].ToString ());

2.5 How to comment out ASP.NET Tags?

<%--<asp:Label id="Label1" style="Z-INDEX: 101; LEFT: 8px; POSITION: absolute; TOP: 48px"
runat="server">Label</asp:Label>--%>

2.6 What is a ViewState?

In classic ASP, when a form is submitted the form values are cleared. In some cases the form is submitted

with huge information. In such cases if the server comes back with error, one has to re-enter correct

information in the form. But submitting clears up all form values. This happens as the site does not maintain

any state (ViewState).

In ASP .NET, when the form is submitted the form reappears in the browser with all form values. This is

because ASP .NET maintains your ViewState. ViewState is a state management technique built in ASP.NET. Its

purpose is to keep the state of controls during subsequent postbacks by the same user. The ViewState

indicates the status of the page when submitted to the server. The status is defined through a hidden field

placed on each page with a <form runat="server"> control.

<input type="hidden" name=


"__VIEWSTATE"value="dDwyNTA3OTU0NDM7Oz7t5TntzkOUeB0QVV6FT2hvQwtpPw==" />

If you want to NOT maintain the ViewState, include the directive <%@ Page

EnableViewState="false"%> at the top of an .aspx page If you do not want to maintain Viewstate for any

control add the attribute EnableViewState="false" to any control. For more details refer The ASP.NET View

State

2.7 Where can I get the details on Migration of existing projects using
various technologies to ASP.NET?
Microsoft has designed Migration Assistants to help us convert existing pages and applications to ASP.NET. It

does not make the conversion process completely automatic, but it will speed up project by automating some

of the steps required for migration.

Below are the Code Migration Assistants

• ASP to ASP.NET Migration Assistant

• PHP to ASP.NET Migration Assistant

• JSP to ASP.NET Migration Assistant

Refer Migrating to ASP.Net

2.8 What is the equivalent of date() and time() in ASP.NET?

VB.NET

System.DateTime.Now.ToShortDateString()
System.DateTime.Now.ToShortTimeString()

C#

System.DateTime.Now.ToShortDateString();
System.DateTime.Now.ToShortTimeString();

2.9 How to prevent a button from validating it's form?

Set the CauseValidation property of the button control to False

2.10 How to get the IP address of the host accessing my site?

VB.NET

Response.Write (Request.UserHostAddress.ToString ())

C#
Response.Write (Request.UserHostAddress.ToString ());

2.11 How to access the Parameters passed in via the URL?

Call the Request.QueryStringmethod passing in the key. The method will return the parameter value

associated with that key. VB.NET

Request.QueryString("id")

C#

Request.QueryString["id"];

2.12 How to Set Focus to Web Form Controls By Using Client-Side Script?

<script language="javascript">
function SetFocus()
{
// W3C approved DOM code that will work in all modern browsers
if (document.getElementById)
document.getElementById('txt2').focus();
else
// To support older versions of IE:
if (document.all)
document.all("txt2").focus();
return false;
}
</script>

<body MS_POSITIONING="GridLayout" onload="SetFocus()">


<form id="Form1" method="post" runat="server">
Enter 1:
<asp:TextBox ID="txt1" Runat="server" Width="50" />
<br>
Enter 2:
<asp:TextBox ID="txt2" Runat="server" Width="50" />
<br>
<asp:Button id="Button1" runat="server" Text="Button1"></asp:Button>
</form>
</body>

Refer Sample IE Code

2.13 How to display a Wait page while a query is running?

Refer Asynchronous Wait State Pattern in ASP.NET

2.14 How to implement Form based Authentication in ASP.NET


application?

For

• VB.NET

• C#

2.15 How to catch the 404 error in my web application and provide more
useful information?

In the global.asax Application_error Event write the following code

VB.NET

Dim ex As Exception = Server.GetLastError().GetBaseException()


If TypeOf ex Is System.IO.FileNotFoundException Then
'your code
'Response.Redirect("err404.aspx")
Else
'your code
End If

C#

Exception ex = Server.GetLastError().GetBaseException();
if (ex.GetType() == typeof(System.IO.FileNotFoundException))
{
//your code
Response.Redirect ("err404.aspx");
}
else
{
//your code
}

2.16 Is there a method similar to Response.Redirect that will send


variables to the destination page other than using a query string or the
post method?

Server.Transfer preserves the current page context, so that in the target page you can extract values and

such. However, it can have side effects; because Server.Transfer doesnt' go through the browser, the browser

doesn't update its history and if the user clicks Back, they go to the page previous to the source page.

Another way to pass values is to use something like a LinkButton. It posts back to the source page, where

you can get the values you need, put them in Session, and then use Response.Redirect to transfer to the

target page. (This does bounce off the browser.) In the target page you can read the Session values as

required.

Refer to Passing Values Between Web Forms Pages for more information.

2.17 What are the differences between HTML versus Server Control?

Refer

• ASP.NET Server Controls Recommendations

• Introduction to ASP.NET Server Controls

2.18 How can I change the action of a form through code?

You can't change it. The action attribute is owned by ASP.NET. Handle Events and Transfer.

For work around refer to Paul Wilson's Multiple Forms and Non-PostBack Forms - Solution

2.19 Is there any control that allows user to select a time from a clock -
in other words is there a clock control?

Peter Blum has developed some controls. Check out Peter's Date Package: TimeOfDayTextBox and

DurationTextBox Controls
2.20 How to Compare time?

VB.NET

Dim t1 As String = DateTime.Parse("3:30 PM").ToString("t")


Dim t2 As String = DateTime.Now.ToString("t")
If DateTime.Compare(DateTime.Parse(t1), DateTime.Parse(t2)) < 0 Then
Response.Write(t1.ToString() & " is < than " & t2.ToString())
Else
Response.Write(t1.ToString() & " is > than " & t2.ToString())
End If

C#

string t1 = DateTime.Parse("3:30 PM").ToString("t");


string t2 = DateTime.Now.ToString("t");
if (DateTime.Compare(DateTime.Parse (t1), DateTime.Parse (t2)) < 0 )
{
Response.Write(t1.ToString() + " is < than " + t2.ToString());
}
else
{
Response.Write(t1.ToString() + " is > than " + t2.ToString());
}

2.21 How To work with TimeSpan Class?

VB.NET

Dim adate As DateTime = DateTime.Parse("06/24/2003")


Dim bdate As DateTime = DateTime.Parse("06/28/2003")
Dim ts As New TimeSpan(bdate.Ticks - adate.Ticks)
Response.Write(ts.TotalDays & "<br>")
Response.Write(ts.TotalHours & ":" & ts.TotalMinutes & ":" & ts.TotalSeconds & ":" & ts.TotalMilliseconds)

C#

DateTime adate = DateTime.Parse("06/24/2003");


DateTime bdate = DateTime.Parse("06/28/2003");
TimeSpan ts = new TimeSpan (bdate.Ticks - adate.Ticks);
Response.Write(ts.TotalDays.ToString () + "<br>");
Response.Write(ts.TotalHours.ToString() + ":" + ts.TotalMinutes.ToString() + ":" + ts.TotalSeconds.ToString()
+ ":" + ts.TotalMilliseconds.ToString() );
2.22 Where can I get information on Cookies in ASP.NET?

Refer Mike Pope's article Basics of Cookies in ASP.NET

2.23 Does ASP.Net still recognize the global.asa file?

ASP.Net does not recognize the standard ASP global.asa file. Instead it uses a file named global.asax with the

same - plus additional - functionality.

2.24 How should I destroy my objects in ASP.Net?

ASP.Net actually has very solid internal garbage collection. So this is not an issue as it was in previous

versions of Active Server Pages.

Link to more information: <gcConcurrent> Element

2.25 Are there resources online with tips on ASP to ASP.Net conversions?

Microsoft has deisnged The ASP to ASP.NET Migration Assistant help us convert ASP pages and applications to

ASP.NET. It does not make the conversion process completely automatic, but it will speed up project by

automating some of the steps required for migration.

The following Code Migration Assistants are discussed in the link below.

• ASP to ASP.NET Migration Assistant

• PHP to ASP.NET Migration Assistant

• JSP to ASP.NET Migration Assistant

Refer Migrating to ASP.Net

Also refer:

• Microsoft's ASP to ASP.NET Code Migration Assistant

• John Peterson's article Microsoft's ASP to ASP.NET Migration Assistant

• Paolo Cavone's article From ASP to ASP.NET... Painlessly!


2.26 How do I publish my ASP.NET application to my ISP's web server?

Your ISP must first create an IIS application and apply the Front Page Server Extensions to it. Then in Visual

Studio .NET, select the "Project | Copy Project" menu. Then enter the URL and select the FrontPage web

access method. The "Copy Project" feature copies all of the necessary files to your ISP's machine for your

ASP.NET application to run.

You can also FTP your files to your ISP web server. But you must know which files to upload. For more details

refer PRB: Remote ASP.NET Projects Require IIS on the Client Computer or FrontPage Server Extensions on

the Server Computer

2.27 Why do i get error message "Could not load type" whenever I
browse to my ASP.NET web site?

Your code-behind files for either your .aspx or the global.aspx page have not been complied. Use Visual

Studio .NET's "Build | Build Solution" menu, or run the command line compiler.

For more details refer PRB: "Could not load type" error message when you browse to .aspx page

2.28 Will the WebMatrix SqlDataSourceControl work with a MySQL


connection?

SqlDataSourceControl lets you connect and work with MS SQL DB, while AccessDataSourceControl do the

same thing but for MS Access DB. Therefore SqlDataSourceControl can't help you in your MySql connectivity .

For Connectivity with MySql refer Accessing MySQL Database with ASP.NET

2.29 Can I combine classic ASP and ASP.NET pages?

No.

ASP pages can run in the same site as ASP.NET pages, but you can't mix in a page. Also ASP and ASP.NET

won't share their session.

2.30 What is the difference between src and Code-Behind?

Src attribute means you deploy the source code files and everything is compiled JIT (just-in-time) as needed.

Many people prefer this since they don't have to manually worry about compiling and messing with dlls -- it

just works. Of course, the source is now on the server, for anyone with access to the server -- but not just
anyone on the web.

CodeBehind attribute doesn't really "do" anything, its just a helper for VS.NET to associate the code file with

the aspx file. This is necessary since VS.NET automates the pre-compiling that is harder by hand, and

therefore the Src attribute is also gone. Now there is only a dll to deploy, no source, so it is certainly better

protected, although its always decompilable even then.

2.31 How can I get the value of input box with type hidden in code-
behind?

You can set the runat= server for the hidden control and you can use ControlName.Value to get its value in

CodeBehind file

2.32 I have created a .NET user control page (.ascx) but I cannot compile
and run it.

User control (ascx) can't be run on it own, but you can drag it onto any web page (aspx) and then run it.

2.33 What is a .resx file?

The .resx resource file format consists of XML entries, which specify objects and strings inside XML tags. This

is useful for localization. For more details refer Resources in .resx files

2.34 Is it possible to use a style sheet class directly on a control instead


of using inline or page-level formatting ?

Every WebControl derived control has a CssClass property which allows you to set it's format to a style sheet.

2.35 Can I recieve both HTML markup for page and code in the ASP.NET
web page's source code portion in the Web browser?

No. The Web browser recieves only HTML markup.

No source code or web control syntax is passed back to the web browser.

2.36 Why can't I put <%@ Page Language="C " %> where at the top of
an ASPX file and write my server-side scripts in C ?

The parsers ASP.NET uses to extract code from ASPX files understand C#, Visual Basic.NET, and JScript.NET.

You can write server-side scripts in any language supported by a .NET compiler.
2.37 ASP pages that worked pefectly on Windows 2000 Server and IIS
5.0 do not work on Windows 2003 Server with IIS 6.0. ASP.NET pages
work fine. Why?

Start -> Settings -> Control Panel -> Administrative Tools -> and double clicking IIS Manager.

Go to the Web Service Extensions tab, click Active Server Pages, then press the "Allow" button on the left

2.38 Why do I get error message "Error creating assembly manifest:


Error reading key file 'key.snk' -- The system cannot find the file
specified"?

Check the location of the key.snk file relative to the assembly file. Provide an explicit path or a relative path.

<Assembly: AssemblyKeyFileAttribute("Drive:\key.snk")>

2.39 How to get URL without querystring?

VB.NET

Dim stringUri As String = "http://www.syncfusion.com/?id=1&auid=16"


Dim weburi As Uri = New Uri(stringUri)
Dim query As String = weburi.Query
Dim weburl As String = stringUri.Substring(0, stringUri.Length - query.Length)
Response.Write(weburl)

C#

string stringUri = "http://www.syncfusion.com/?id=1&auid=16";


Uri weburi = new Uri(stringUri);
string query = weburi.Query;
string weburl = stringUri.Substring(0, stringUri.Length - query.Length);
Response.Write (weburl);

2.40 What is the best way to output only time and not Date?

Use DateTime as follows VB.NET

Response.Write(DateTime.Now.ToString("hh:mm:ss"))
C#

Response.Write(DateTime.Now.ToString("hh:mm:ss"));

2.41 Do I have to compile code if I am changing the content of my


aspx.cs file?

Yes if you have used Codebehind="my.aspx.cs".

Not if you used src="my.aspx.cs" in your page declaration.

2.42 How to grab the referring URL?

VB.NET

Response.Write ( Request.UrlReferrer.ToString())

C#

Response.Write ( Request.UrlReferrer.ToString());

2.43 My ASP code gives an error "Compiler Error Message: BC30289:


Statement cannot appear within a method body. End of method
assumed" when changed to .aspx?

Use a <script runat=server> block instead of the <% %> syntax to define Subs.

Make sure you have proper events associated with the code and have start and end of procedure or function

wirtten properly.

2.44 How can I save images ?

You need a stream to read the response, WebResponse.GetResponseStream(), and a stream to write it to the

hard drive. FileStream should do the trick. You'll have to write to the filestream what you read from the

response stream.

2.45 How can I logout when using FormsAuthentication?


VB.NET

FormsAuthentication.SignOut()

C#

FormsAuthentication.SignOut();

2.46 Why do I get a blank page when I use


Server.Transfer("page1.htm") to transfer to a different page?

Server.Transfer only works with .aspx pages

You can't use Transfer method with HTML pages

2.47 How to detect the User's culture?

VB.NET

Dim sLang As String


sLang = Request.UserLanguages(0)
Response.Write(sLang)

C#

string sLang ;
sLang = Request.UserLanguages[0];
Response.Write (sLang);

2.48 What is the difference between CurrentCulture property and the


CurrentUICulture property?

• CurrentCulture property : affects how the .NET Framework handles dates, currencies, sorting and

formatting issues

• CurrentUICulture property : determines which satellite assembly is used when loading resources
2.49 Can I read the hard disk serial # of the client computer using
ASP.NET?

No. Such information is not passed to the server with a http request.

2.50 What is xxx(src As Object, e As EventArgs)?

xxx is an event handler

src is the object that fires the event

e is an event argument object that contains more information about the event

An event handler is used when one object wants to be notified when an event happens in another object

2.51 What is the difference between Absolute vs Relative URLs?

Absolute /Fully Qualified URLs:

• Contain all information necessary for the browser(or other client program) to locate the resource

named in the URL

o This includes protocol moniker used( i.e http://, ftp://..etc..), Server's Domain name or IP

address and the file path

o Absolute URL looks as http://localhost/megasolutions/page1.aspx

Relative URLs:

• Only provide information necessary to locate a resource relative to the current document(document

relative) or current server or domain(root relative)

o Document relative URL - page1.aspx

o Root Relative URL - /megasolutions/Admin/pagelog.aspx

2.52 What is the difference between URL and URI?

A URL is the address of some resource on the Web, which means that normally you type the address into a
browser and you get something back. There are other type of resources than Web pages, but that's the

easiest conceptually. The browser goes out somewhere on the Internet and accesses something.

A URI is just a unique string that uniquely identifies something, commonly a namespace. Sometimes they

look like a URL that you could type into the address bar of your Web browser, but it doesn't have to point to

any physical resource on the Web. It is just a unique set of characters, that, in fact, don't even have to be

unique.

URI is the more generic term, and a URL is a particular type of URI in that a URL has to uniquely identify

some resource on the Web.

2.53 How to convert milliseconds into time?

VB.NET

dim ts as TimeSpan = TimeSpan.FromMilliseconds(10000)


Response.Write (ts.ToString () )

C#

TimeSpan ts = TimeSpan.FromMilliseconds(10000);
Response.Write (ts.ToString () );

2.54 How to include multiple vb/cs files in the source?

You can do this using assembly directives.

<%@ assembly src="test1.vb" %>


<%@ assembly src="test2.vb" %>

or

<%@ assembly src="test1.cs" %>


<%@ assembly src="test2.cs" %>

However, note that each source file will be compiled individually into its own assembly, so they cannot have

dependencies on each other.


2.55 How to convert a string to Proper Case?

Use the namespace System.Globalization

VB.NET

Dim myString As String = "syncFusion deVeloPer sUppOrt"


' Creates a TextInfo based on the "en-US" culture.
Dim TI As TextInfo = New CultureInfo("en-US", False).TextInfo
Response.Write(TI.ToTitleCase(myString))

C#

string myString = "syncFusion deVeloPer sUppOrt";


// Creates a TextInfo based on the "en-US" culture.
TextInfo TI = new CultureInfo("en-US",false).TextInfo;
Response.Write (TI.ToTitleCase( myString ));

For more details refer TextInfo.ToTitleCase()

2.56 How can I ensure that application-level variables are not updated
by more than one user simultaneously?

Use the HttpApplicationState's Lock and UnLock methods.

For more details refer : MSDN: Application State

2.57 Why do I get the error message


"System.InvalidOperationException: It is invalid to show a modal dialog
or form when the application is not running in UserInteractive mode.
Specify the ServiceNotification or DefaultDesktopOnly style to display a
...."?

You can't use MsgBox or MessageBox.Show in ASP.NET WebForm. You maybe use:

VB.NET

Response.Write("<script>alert('Hello');</script>")

C#

Response.Write("<script>alert('Hello');</script>") ;
2.58 How to validate that a string is a valid date?

VB.NET

Dim blnValid As Boolean = False


Try
DateTime.Parse(MyString)
blnValid = True
Catch
blnValid = False
End Try

C#

bool blnValid=false;
try
{
DateTime.Parse(MyString);
blnValid=true;
}
catch
{
blnValid=false;
}

2.59 Are namespaces and Class names Case Sensitive?

Namespaces and Class names are case Sensitive. Namespaces imported using the @ Import Directive will

cause an error if the correct case is not used.

2.60 How to convert string to a DateTime and compare it with another


DateTime?

VB.NET

Dim blntimeIsOk As Boolean = DateTime.Parse("15:00") < DateTime.Parse("08:00")


Response.Write(blntimeIsOk)

C#
bool blntimeIsOk = (DateTime.Parse("15:00") < DateTime.Parse("08:00"));
Response.Write (blntimeIsOk);

2.61 How to get the url of page dynamically?

Use Request.Url property

2.62 How to convert user input in dMy format to Mdy?

VB.NET

Dim dt As DateTime = DateTime.ParseExact("0299", New String() {"My", "M/y"}, Nothing,


System.Globalization.DateTimeStyles.None)

C#

DateTime dt = DateTime.ParseExact("0299", new string[] {"My","M/y"},


null,System.Globalization.DateTimeStyles.None);

For more details refer DateTime.ParseExact

2.63 When the User is prompted a File Download dialogbox, if the user
selects "Save" then the "Save as" dialog box is displayed. Is there any
way for me to retrieve the filename and directory path specified by the
user on the File Download dialog box?

Clients do not report information back about where the user selects to save the content, so there isn't an

easy way to do this. Instead, you would need to ask the user before using the content-disposition for a file

path, and then you could specify the filename parameter for the content-disposition header. Still, the user is

free to change that path when actually downloading.

2.64 How to hide or show Controls in server side code?

In any appropriate event write

VB.NET

TextBox1.Visible =not TextBox1.Visible


C#

TextBox1.Visible =!TextBox1.Visible ;

2.65 How to check if the user is using a secure or non secure connection?

The Request Object defines a Property called IsSecureConnection, that will indicate whether http:// or

https:// has been used.

2.66 Is it possible to write code in many languages in one ASP.NET


project?

You cannot write the code-behind files in different languages in the same project, but you can write the aspx

pages and ascx controls in different languages.

2.67 What is the difference between Response.Redirect() and


Server.Transfer().

Response.Redirect

• Tranfers the page control to the other page, in other words it sends the request to the other page.

• Causes the client to navigate to the page you are redirecting to. In http terms it sends a 302

response to the client, and the client goes where it's told.

Server.Transfer

• Only transfers the execution to another page and during this you will see the URL of the old page

since only execution is transfered to new page and not control.

• Occurs entirely on the server, no action is needed by the client

Sometimes for performance reasons, the server method is more desirable

2.68 How to get the hostname or IP address of the server?

You can use either of these:


• HttpContext.Current.Server.MachineName

• HttpContext.Current.Request.ServerVariables["LOCAL_ADDR"]

The first one should return the name of the machine, the second returns the local ip address.
Note that name of the machine could be different than host, since your site could be using host headers

2.69 What is the meaning of validateRequest=true in .net framework1.1?

The value of validateRequest is set to 'true' by default, which means that the framework will automatically

deny submission of the '<' and '>' characters.

2.70 What is the different between <%# %> and <%= %>?

The <%# %> is used for databinding where as <%= %> is used to output the result of an expression. The

expression inside <%# %> will be executed only when you call the page's or control's DataBind method. The

expression inside <%= %> will be executed and displayed as and when it appears in the page.

2.71 What permissions do ASP.NET applications posses by default?

By default ASP.NET Web applications run as ASP.NET user. This user has limited permissions equivalent to the

User Group.

2.72 How can I specify the relative path for a file?

Suppose you have following file hierarchy:

default.aspx
Admin/login.aspx
Misc/testpage.aspx

And you are on the login.aspx and want your user to navigate to the default.aspx (or testpage.aspx) file.

Then you can use

• Response.Redirect ("../default.aspx")
• Response.Redirect ("../Misc/testpage.aspx")

2.73 How can I specify the "upload a file" input textbox in a form to be
read only so that the user can click on the browse button and pick a file
but they cannot type anything into the textbox next to the browse
button.

<input id="File1" type="file" contenteditable=false />

2.74 How to change the Page Title dynamically?

<TITLE id="Title1" runat =server ></TITLE>

VB.NET

'Declare
Protected WithEvents Title1 As System.Web.UI.HtmlControls.HtmlGenericControl

'In Page_Load
Title1.InnerText ="Page 1"

C#

//Declare
protected System.Web.UI.HtmlControls.HtmlGenericControl Title1 ;

//In Page_Load
Title1.InnerText ="Page 1" ;

2.75 Why do I get the error message "Object must implement


IConvertible". How can I resolve it?

The common cause for this error is specifying a control as a SqlParameter's Value instead of the control's text

value.
For example, if you write code as below you'll get the above error:

VB.NET

Dim nameParameter As SqlParameter = command.Parameters.Add("@name", SqlDbType.NVarChar, 50)


nameParameter.Value = txtName

C#

SqlParameter nameParameter = command.Parameters.Add("@name", SqlDbType.NVarChar, 50);


nameParameter.Value = txtName ;

To resolve it, specify the control's Text property instead of the control itself.

VB.NET

nameParameter.Value = txtName.Text

C#

nameParameter.Value =txtName.Text;

2.76 Why is default.aspx page not opened if i specify http://localhost. I


am able to view this page if i hardcode it as
http://localhost/default.aspx?

If some other default page comes higher in the list, adjust the default.aspx to be the number one entry inside

the IIS configuration. If you have multiple websites inside IIS, make sure the configuration is applied on the

right website (or on all websites by applying the configuration on the server-level using the properties dialog,

configure WWW service).

2.77 Can ASP.NET work on an NT server?

No. For more details refer ASP 1.1 version

2.78 Is it possible to migrate Visual InterDev Design-Time Controls to


ASP.NET?
Refer INFO: Migrating Visual InterDev Design-Time Controls to ASP.NET

2.79 How to automatically get the latest version of all the asp.net
solution items from Source Safe when opening the solution?

In VS.NET you can go to Tools > Options > Source Control > General and check the checkbox for Get

everything when a solution opens.

This retrieves the latest version of all solution items when you open the solution.

2.80 How to convert the datetime into a string for use in the SQL '
statement?

<asp:label id="Label2" runat="server">Select a culture: </asp:label>


<asp:dropdownlist id="ddlCulture" runat="server" autopostback="True"></asp:dropdownlist>
<P></P>
<asp:label id="Label3" runat="server">DateTime in Selected Culture</asp:label>
<asp:textbox id="TextBox1" runat="server"></asp:textbox>
<p>
<asp:label id="Label1" runat="server"></asp:label>

VB.NET

Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load


'Put user code to initialize the page here
If Not Page.IsPostBack Then
Dim cInfo As CultureInfo
For Each cInfo In CultureInfo.GetCultures(CultureTypes.SpecificCultures)
ddlCulture.Items.Add(cInfo.Name)
Next
End If
End Sub

Private Sub ddlCulture_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As


System.EventArgs) Handles ddlCulture.SelectedIndexChanged
' Get a CultureInfo object based on culture selection in dropdownlist
Dim cInfo As CultureInfo = New CultureInfo(ddlCulture.SelectedItem.Text)
' Get a CultureInfo object based on Invariant culture
Dim cInfoNeutral As CultureInfo = New CultureInfo("")
' Display the datetime based on the formatting of the selected culture
TextBox1.Text = Convert.ToString(Now, cInfo.DateTimeFormat)
' Create a DateTime variable to hold the Invariant time
Dim dt As DateTime
dt = Convert.ToDateTime(TextBox1.Text, cInfo.DateTimeFormat)
'Convert the datetime into a string for use in the SQL statement
Label1.Text = "... WHERE ([Date] < '" & _
Convert.ToString(dt, cInfoNeutral.DateTimeFormat) & "')"
End Sub
C#

private void Page_Load(object sender, System.EventArgs e)


{
// Put user code to initialize the page here
if (!Page.IsPostBack )
{
foreach(CultureInfo cInfo in CultureInfo.GetCultures(CultureTypes.SpecificCultures))
{
ddlCulture.Items.Add(cInfo.Name);
}
}
}

private void ddlCulture_SelectedIndexChanged(object sender, System.EventArgs e)


{
// Get a CultureInfo object based on culture selection in dropdownlist
CultureInfo cInfo = new CultureInfo(ddlCulture.SelectedItem.Text);
// Get a CultureInfo object based on Invariant culture
CultureInfo cInfoNeutral = new CultureInfo("");
// Display the datetime based on the formatting of the selected culture
TextBox1.Text = Convert.ToString(DateTime.Now , cInfo.DateTimeFormat);
// Create a DateTime variable to hold the Invariant time
DateTime dt ;
dt = Convert.ToDateTime(TextBox1.Text, cInfo.DateTimeFormat);
//Convert the datetime into a string for use in the SQL statement
Label1.Text = "... WHERE ([Date] < '" + Convert.ToString(dt, cInfoNeutral.DateTimeFormat) + "')";
}

2.81 How to make VS.Net use FlowLayout as the default layout rather
than the GridLayout?

For VB.NET, go to path C:\Program Files\Microsoft Visual Studio

.NET\Vb7\VBWizards\WebForm\Templates\1033

Change the following line in the existing WebForm1.aspx

<body MS_POSITIONING="[!output DEFAULT_HTML_LAYOUT]">

to

For C#, go to path C:\Program Files\Microsoft Visual Studio .NET

2003\VC#\VC#Wizards\CSharpWebAppWiz\Templates\1033
Change the following line in the existing WebForm1.aspx

<body MS_POSITIONING="[!output DEFAULT_HTML_LAYOUT]">

to

Note:Before changing any templates it's a good idea to make backup copies of them

Or rather than above approach you can change the behavior for new files on a per project basis in Visual

Studio by:

1. Right clicking on the project name (Ex: "WebApplication1)" in Solution Explorer, and select

"Properties".

2. From project properties window, under Common Properties>Designer Defaults>Page Layout change

"Grid" to "Flow".

2.82 Can I use a DataReader to update/insert/delete a record?

No. DataReader provides a means of reading a forward-only stream of rows from a database.

2.83 What is the difference between Server.Transfer and Server.Execute?

• Server.Transfer is used to End the current weform and begin executing a new webform. This method

works only when navigating to a Web Forms page (.aspx)

• Server.Execute is used to begin executing a new webform while still displaying the current web form.

The contents of both forms are combined. This method works only when navigating to a webform

page(.aspx)

2.84 How to create a login screen in ASP.NET?


Here is a sample login screen:

<TABLE id="Table1" cellSpacing="1" cellPadding="1" width="300" border="1">


<TR>
<TD>
<asp:Label id="Label1" runat="server">User Name</asp:Label></TD>
<TD>
<asp:TextBox id="txtUserName" runat="server"></asp:TextBox></TD>
<TD>
<asp:RequiredFieldValidator id="RequiredFieldValidator1" runat="server" ErrorMessage="*"
ControlToValidate="txtUserName"></asp:RequiredFieldValidator></TD>
</TR>
<TR>
<TD>
<asp:Label id="Label2" runat="server">Password</asp:Label></TD>
<TD>
<asp:TextBox id="txtPassword" runat="server"></asp:TextBox></TD>
<TD>
<asp:RequiredFieldValidator id="RequiredFieldValidator2" runat="server" ErrorMessage="*"
ControlToValidate="txtPassword"></asp:RequiredFieldValidator></TD>
</TR>
<TR>
<TD></TD>
<TD>
<asp:Button id="btnLogin" runat="server" Text="Login"></asp:Button></TD>
<TD></TD>
</TR>
</TABLE>

VB.NET

Dim myconnection As SqlConnection


Dim mycmd As SqlCommand
Dim strSql As String
Dim myReader As SqlDataReader

Private Sub btnLogin_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles


btnLogin.Click
myconnection=NewSqlConnection("Server=localhost;uid=sa;password=;database=northwind;")
strSql = "Select * from usertbl where username=" & "'" & txtUserName.Text & "'" & " and userpassword=" &
"'" & txtPassword.Text & "'"
mycmd = New SqlCommand(strSql, myconnection)
myconnection.Open()
myReader = mycmd.ExecuteReader(CommandBehavior.CloseConnection)
If myReader.Read() Then
Response.Write("Welcome")
Else
Response.Write("Access Denied")
End If

End Sub
C#

SqlConnection myconnection ;
SqlCommand mycmd ;
string strSql ;
SqlDataReader myReader ;
private void btnLogin_Click(object sender, System.EventArgs e)
{
myconnection=newSqlConnection("Server=localhost;uid=sa;password=;database=northwind;");
strSql = "Select * from usertbl where username=" + "'" + txtUserName.Text + "'" + " and
userpassword=" + "'" + txtPassword.Text + "'";
mycmd = new SqlCommand(strSql, myconnection);
myconnection.Open();
myReader = mycmd.ExecuteReader(CommandBehavior.CloseConnection);
if (myReader.Read() )
{
Response.Write("Welcome");
}
else
{
Response.Write("Access Denied");
}
}

2.85 How to format a Telphone number in the xxx-xxx-xxxx format?

VB.NET

Dim Telno As Double = Double.Parse(ds.Tables(0).Rows(0)("TelNo").ToString())


Response.Write(Telno.ToString("###-###-####"))

C#

double Telno= double.Parse(ds.Tables[0].Rows[0]["TelNo"].ToString());


Response.Write(Telno.ToString("###-###-####"));

2.86 Can two different programming languages be mixed in a single


ASPX file?

No. ASP.NET uses parsers to strip the code from ASPX files and copy it to temporary files containing derived

Page classes, and a given parser understands only one language

2.87 Can I use custom .NET data types in a Web form?


Yes. Place the DLL containing the type in the application root's bin directory and ASP.NET will automatically

load the DLL when the type is referenced. This is also what happens when you add a custom control from the

toolbox to your web form.

2.88 How can I have a particular Web page in an ASP.NET application


which displays its own error page.

This can be done by setting the ErroPage attribute of Page Directive or ErrorPage property of Page Class to

the desired Custom Error Page

<%@Page Language="C#" ErrorPage="specificerropage.htm"%>

In web.config

<customErrors mode="On" />


FAQ Home
3. Debugging and Error Handling

3.1 Why do I get Error message "Unable to Start Debugging" Error


Message When You Send Debug HTTP Request?

This problem can occur if there is some error in the web.config file. To resolve this check for the well-

formedness of this document.

For more details refer PRB: "Unable to Start Debugging" Error Message When You Send Debug HTTP Request

3.2 Why do I get the error message "Unable to start debugging on the
web server..." when I debug?

There is a possibility that there is no web.config file for the project or there is no Execute permission for the

project.

If you already have a web.config file, double check it's well-formedness.

If the web.config file is missing, add one to the directory that contains the ASP.NET application. You can copy

one from the numerous samples applications available with the framework installation.

Make sure that the following section reads like this:

COMPILATION
defaultLanguage="c#"
debug="true"
/>
On the other hand, if your project already has a Web.config file, and the above section is set as specified,

follow these steps to set the Execute Permissions property for the project folder:

1. Start Internet Services Manager, and then click the project that you are trying to debug.

2. Right-click the project, and then click Properties.

3. Click the Directory tab.

4. If None is selected in the Execute Permissions list, click Scripts only, and then click Apply

3.3 When I Debug ASP.NET Applications I get error message "Access Is


Denied. Check the DCOM Configuration Settings for the Machine Debug
Manager"?

You can get this error if you are user who is trying to remotely debug and you are not a member of the

Debugger Users group on the Microsoft Internet Information Server (IIS) server. To add the appropriate user

to the Debugger Users group, follow these steps on the Web server:

1. From the Windows Start menu, point to Programs, point to Administrative Tools, and then click

Computer Management.

2. In the left pane, click to expand the Computer Management, System Tools, and Local Users and

Groups nodes.

3. Click Groups, and then double-click Debugger Users.

4. In the Debugger Users Properties dialog box, click Add.

5. In the Select Users or Groups dialog box, select the appropriate user, and then click OK.

6. Click OK to exit the Debugger Users Properties dialog box.

7. Close the Computer Management explorer.

3.4 On Trying to Debug an application, by the F5 key I get the error:


"Error while trying to run project: Unable to start debugging on the web
server. Catastrophic failure"?
This issue occurs if the account that is used to run the ASP.NET Worker process (by default, the ASPNET user

account) is not assigned the "Impersonate a client after authentication" user right in the "Local Security

Policy" settings. This issue may occur when you install Microsoft Visual Studio .NET after you install Windows

2000 Service Pack 4 (SP4) on the computer. In this situation, the ASPNET account is not assigned the

"Impersonate a client after authentication" user right in the "Local Security Policy" settings.To resolve it,

please use the method at: To work around the problem, manually assign Impersonate a client after

authentication to the IWAM account. To do so, follow these steps:

1. Click Start, point to Programs, point to Administrative Tools, and then click Domain Controller

Security Policy.

2. Click Security Settings.

3. Click Local Policies, and then click User Rights Assignment.

4. In the right pane, double-click Impersonate a client after authentication.

5. In the Security Policy Setting window, click Define these policy settings.

6. Click Add, and then click Browse.

7. In the Select Users or Groups window, select the IWAM account name, click Add, and then click OK.

8. Click OK, and then click OK again.

9. To enforce an update of computer policy, type the following command: secedit /refreshpolicy

machine_policy /enforce

10. At a command prompt, type iisreset. In case your server is a Domain Controller Refer PRB:
"Catastrophic Failure" Error Message When You Try to Debug an ASP.NET Application on Windows

2000 Domain Controller

3.5 How to configure my project for debugging ASP Code?

Access the Project properties window.

Select the Configuration Properties for debugging then in right Pane, under the debugger node select true for

Enable ASP debugging.


3.6 In Visual Studio .NET, whenever I try to debug my ASP.NET
application I'm not able to stop the debugger on my breakpoints. Why?

Your ASP.NET project is not setup for debugging.

1. Open up the project's properties window and set the "Enable ASP.NET Debugging" option.

2. Open up your web.config file and make sure the Compilation tag's debug attribute is set to true.

<compilation defaultLanguage="vb" debug="true" />

3. Make sure the account you are logged in as and the ASP.NET Worker process is in the local

"Debugger Users" group.

For more information refer :

• PRB: Visual Studio .NET Debugger Does Not Stop on Breakpoints When You Debug ASP.NET Pages

• INFO: Common Errors When You Debug ASP.NET Applications in Visual Studio .NET

3.7 Why do I get error message "Unable to start debugging on the web
server. The debugger is not properly installed. Run setup to install or
repair the debugger. Would you like to disable future attempts to debug
ASP.NET pages for this project ? "?

If someone has run a lockdown or other security tool on the Web server, the DEBUG method may have been

removed.

Go into IIS manager to the Web application's properties and Directory >Configuration (button) > Mappings >

Application mappings.

Check that for .aspx extensions, you allow GET,HEAD,POST,DEBUG

Of course you need to be a member of the Debuggers group on the remote server. To resolve error

1. Right-click the Project Name in Solution Explorer, and then click Properties.

2. In the left pane of Properties, click to select Configuration Properties.

3. Click to select Debugging.

4. In the right pane, change the value of Enable Unmanged Debugging to True (on the drop-down list).

For more details refer PRB: Error Message: Unable to Start Debugging. Unable to Start Program ...

3.8 How do I debug JavaScript and other script code in my application


using Visual Studio .Net?
1) In IE go to Tools/Internet Options.../Advanced Tab and clear the "Disable Script Debugging"

check box options.

2) In VS.Net in your project properties dialog, select "Debugging" under "Configuration Properties" and make

sure that "Enable ASP.Net Debugging" is turned on.

3) You can then set break points in script code in VS.Net in custom script files or the application aspx file.

4) VS.Net should give you detailed debugging information for variables in the scope just like other high-level

languages.

3.9 What are the different exception-handling approaches that can be


used in ASP.NET?

• Using try, catch and finally block in the code

• Using the Error event procedures at the Page, Application or Global levels

• Using the Server Object's GetLastError and ClearError methods

3.10 Why do I get error message "Login failed for user '(null)'. Reason:
Not associated with a trusted SQL Server connection"?

This error usually indicates that SQLServer (or MSDE) is configured to use Windows Authentication. If you

want to use a SQL login, you will need to enable SQL Authentication (mixed mode authentication). For more

details refer PRB: ASP/ODBC/SQL Server Error 0x80040E4D "Login Failed for User '(Null)'"

3.11 Why do I get the Error Message "System.OutOfMemoryException:


Exception of type System.OutOfMemoryException was thrown."?

It means that the server is out of available memory. You probably have an infinite loop somewhere that's

frantically creating large objects, or you forgot to dispose of disposable objects and memory slowly leaked.

3.12 Why do I get the error message "Sql Server does not exists or
access denied " whenever I try to access the data on Sql server?
• The ASP.NET worker process doesn't have the correct permissions to connect to or write to the SQL

Server database. Either enable impersonation for users, or configure the ASP.NET worker process to

run under the SYSTEM account.

• The ASPNET account cannot establish a named pipes connection to the database server. Try using

TCP/IP instead of the Named Pipes protocol to connect to the database by adding "Network Library

=dbmssocn" in your connection string

For more information refer

• BUG: Named pipes do not work when worker process runs under ASPNET account

• Process and request identity in ASP.NET

3.13 Why do I get error message "It is already opened exclusively by


another user, or you need permission to view its data." when I try to
open Access mdb?

The ASPNET worker process doesn't have the correct permissions to connect to or write to the Access

database.

Either enable impersonation for users or configure the ASP.NET worker process to run under the SYSTEM

account. You can also grant read and write permissions for the "Everyone" group on the database and the

database folder.

For more details refer

• PRB: Cannot connect to Access database from ASP.NET

• Process and request identity in ASP.NET

3.14 Why do I get the "HTTP 404 - File not found." error message as
"The page cannot be found.The page you are looking for might have been
removed, had its name changed, or is temporarily unavailable "?
The reason for this error can be

• The requested file has been renamed.

• The requested file has been moved to another location and/or deleted.

• The requested file is temporarily unavailable due to maintenance, upgrades, or other unknown

causes.

• The requested file does not exist.

• IIS 6.0: The appropriate Web service extension or MIME type is not enabled.

To resolve this refer Common reasons IIS Server returns "HTTP 404 - File not found" error

3.15 When I install the Microsoft .NET Framework 1.1 on a computer that
is running Windows XP, and then you start Windows, the Welcome
screen appears. This screen prompts me to click your user name to start
Windows.Why?

When you install the .NET Framework 1.1, a hidden local user account that is named ASPNET is created.

When you start Windows, Windows treats the ASPNET local user account as an additional user account,

although the ASPNET user account is hidden. Therefore, the Welcome screen appears and prompts you to

click your user name.

For more details refer KB 827072

3.16 Why do I get the error message


"System.InvalidOperationException: Application is restarting"?

This problem occurs because of some antivirus applications write back information to the files that they scan.

Every time a user changes the Web.config configuration file, the Global.asax file, or the contents of the Bin

folder, the application should restart to incorporate these changes. Because antivirus scanning changes

cannot be distinguished from the user's file changes, the application restarts when the antivirus software

scans these folders.

Note This problem may occur even when no error is returned. If the virus-scanning software triggers change

notifications, every change notification is doubled at the very least: one real change notification and an

additional change notification from the antivirus software some time later. For more information refer PRB:

Random application restarts with "Application is restarting" error in ASP.NET

3.17 How can I see the Trace messages?

For Page Level Tracing specify the Page Directive as


<%@ Page Trace="true" %>

You can view the page on which trace is enabled to true to see the details.

For Application Level Tracing modify web.config as

<configuration>
<system.web>
<trace enabled="true" requestLimit="10" pageOutput="false" traceMode="SortByTime"
localOnly="true" />
</system.web>
</configuration>

You can view the Trace at http://<server>/<webApplicationNam>/trace.axd

3.18 I have installed ASP.NET hotfix and I find that Startup Type of the
ASP.NET Session State Service is set to Manual.Why?

Microsoft has acknowledged this as a Bug

To set the StartUp Type as desired refer following steps

1. In Control Panel, open Administrative Tools.

2. Click Services. The Services window appears.

3. Expand the Name column so that the complete name of each service appears.

Note A Startup Type column displays the current Startup Type value for each service.

4. Double-click the ASP.NET State Service service. The ASP.NET State Service Properties window

appears.

5. On the General tab, click one of the following options in the Startup type list:

o Manual

o Automatic

o Disabled

6. Click Apply, and then click OK to save your settings.

In the Services window, notice your changes to the Startup Type in the Startup Type column.
3.19 Why do I get the error message "aspnet_wp.exe (PID: XXXX) was
recycled because it was suspected to be in a deadlocked state "?

This problem might occur because ASP.NET limits the number of worker threads and completion port threads

that a call can use to execute requests. For more details refer PRB: Contention, poor performance, and

deadlocks when you make Web service requests from ASP.NET applications

You could control the deadlock detection by changing machine.config setting in

<processModel responseDeadlockInterval="..." ... />

3.20 How to display errors using Page_Error event of Page Object?

VB.NET

Private Sub Page_Error(ByVal sender As Object, ByVal e As System.EventArgs) Handles MyBase.Error


Response.Write(Server.GetLastError().ToString)
Server.ClearError()
End Sub

C#

//In InitializeComponent
this.Error += new System.EventHandler (this.Page_Error );

//
private void Page_Error(object sender, System.EventArgs e )
{
Response.Write(Server.GetLastError().ToString());
Server.ClearError ();
}

In the Same manner handle the Errors in the Application_Error event in global.asax

3.21 How to redirect the user to the friendly error-handler page when an
Application error occurs?

Modify web.config as

<customErrors mode="On" defaultRedirect="errorpage.aspx" />

The configuration section supports an inner <error> tag that associates HTTP status codes with custom error

pages. For example:

<customErrors mode="On" defaultRedirect="genericerror.htm">


<error statusCode="404" redirect="pagenotfound.aspx"/>
<error statusCode="403" redirect="noaccess.aspx"/>
</customErrors>
For more details refer <customErrors> Element

3.22 How to Enable Remote Debugging on Windows XP Service Pack 2?

To enable remote debugging on Microsoft® Windows® XP SP2 platforms, the Internet Connection Firewall

(ICF) must be configured as follows:

• If ICF is in Shielded mode, you will need to perform appropriate actions so that it is no longer in

Shielded mode.

• If ICF is on, a few ports need to be opened and permissions must be granted to Microsoft® Visual

Studio® and other executables that are involved in the remote debugging.

• If IFC is off, no firewall configuration is necessary.

• In addition, if the user running Visual Studio is not an Administrator on the remote machine, DCOM

settings need to be configured.

Refer How to Enable Remote Debugging on Windows XP Service Pack 2

3.23 Why do I get error message ""Parser Error Message: Access is


denied: Source Error: Line xxx : ""?
The actual problem is because of the Microsoft Indexing Services which scans the Temporary ASP.NET Files

and while doing so, the system puts a lock on the same.

To resolve this, the following steps need to be carried out:-

1. Start - Settings - Control Panel - Administrative Tools - Computer mangement.

2. Expand the services and applications node and select the Indexing service node.

3. Expand the Indexing Service Node and then select and expand the System Node.

4. Right click on Directories and select new directory. browse the path to the temporary asp.net files

c:\winnt\microsoft.net\framework\v1.1.4322\.

5. Select the temporary asp.net files. give ok and then select the "NO" in the Include in index

radiobutton.

6. give ok and then stop and start the indexing service.

3.24 Why do I get the error message "A potentially dangerous


Request.Form value was detected from the client "?

Sounds like you are running version 1.1 of ASP.NET / .NET Framework, which added a new security feature

called request validation. Request validation looks at every request and determines if it could be a possible

CSS (Cross Site Scripting) attack. By default Request Validation is on for every page.

If you wish to allow users to post arbitrary HTML to you site you need to turn off request validation:

<%@Page ValidateRequest="false" %>

For more information check out : Protecting Against Script Exploits in a Web Application on MSDN

3.25 How can I test performance of the Web application?

One approach is to use the Microsoft Web Application Stress tool. It allows you to simulate load on a web

server and can be used to test performance. The following kb article covers how to use it (including where to

download it from). http://support.microsoft.com/default.aspx?scid=kb;en-us;313559

3.26 How can I resolve the error message "Cannot access file '...'
because it is being used by another process"?
You receive this error message if the following conditions are true:

• The assembly that is specified in the error message is a signed assembly and is not installed in the

Global Assembly Cache (GAC); instead, the assembly is in the Bin directory of the ASP.NET Web

application. -and-

• Your ASP.NET Web application has just been restarted.

For more details refer PRB: "Can not Access File 'AssemblyName' Because It Is Being Used by Another
Process" Error Message in ASP.NET

3.27 Why do I get the Compiler Error Message: "CS0246: The type or
namespace name '...' could not be found (are you missing a using
directive or an assembly reference?) "?

This problem typically comes when:

• You do not have class with that name in your project

• You add the class later on and run the project without compiling

• You have the class but you do not specify the namespace via Imports or using keyword

3.28 Why do I get the error message "Compiler Error Message: CS1595"?

This problem occurs because the C# compiler does not have permission to access the folders in the path to

the mscorlib.dll assembly

To resolve this problem, modify the compiler definition for the C# compiler to include the /nostdlib option.

The /nostdlib option prevents the import of the mscorlib.dll assembly, which defines the entire System

namespace. To include the /nostdlib option in the C# compiler definition on a computer, follow these steps:

1. Open the Machine.config file, and then locate the section.

2. In the definition for C#, add the compilerOptions attribute with a value of /nostdlib. For example:

<compiler language="c#;cs;csharp"
extension=".cs"
type="Microsoft.CSharp.CSharpCodeProvider, System,
Version=1.0.3300.0,
Culture=neutral,
PublicKeyToken=b77a5c561934e089"
warningLevel="1"
compilerOptions="/nostdlib" />

For more details refer PRB: "Compiler Error Message: CS1595" Error Message When You Use the C# Compiler

to Compile an ASP.NET Resource

3.29 I get error message at runtime "Value null was found where an
instance of an object was required" when using Application state
variables. why?

Application State variables must be initialized in C# before any operation is performed on them. For

example.:

You need to assign value to Counter state variable before performing the case (int)Session["Counter"].

3.30 I installed Windows 2003 Standard Edition, then VS.NET and SQL
Server 2K with SP3. When I build web project connecting to the database
in VS.NET, the compliler gives me the following error:Login failed for
user 'NT AUTHORITY\NETWORK SERVICE',why?

Add NT AUTHORITY\NETWORK SERVICE account to SQL Server , which will be in the local group. Make sure

to give it the required database access and permissions

3.31 Why do I get error message


"System.Threading.ThreadAbortException: Thread was being aborted"
while using Response.Redirect?

Response.Redirect will cause a ThreadAbort exception. To resolve this use

VB.NET

Response.Redirect(url,false)

C#

Response.Redirect(url,false) ;

3.32 Why do I get the error message "BC30451: Name


'ConfigurationSettings' is not declared"?

This is because you have not added namespace System.Configuration

3.33 What is a parser error?

Its basically a syntax error in your ASPX page. It happens when your page is unreadable for the part of

ASP.NET that transforms your code into an executable.

3.34 Whenever I browse to one of my ASP.NET web pages, Internet


Explorer keeps on asking me if I want to download it, or it just displays
the ASPX source. Why?
IIS does not have the correct mapping for the ASPX file extension. This can happen if you install IIS after

installing the .NET Framework, or if you uninstalled and reinstalled IIS.

To repair IIS mappings for ASP.NET, you can run the Aspnet_regiis.exe utility.

For more information check out KB306005

3.35 Why am I getting the error: "Type '(OleDb or SQL)Connection' is not


defined."?

You get this error when you have not imported the following namespaces in your code in the aspx file:

System.Data.SqlClient or System.Data.OleDb.

3.36 Why do I get the Error message "Operation must use an updateable
query"?

If you're getting an error when Inserting or Updating an MS Access Database ('Operation must use an

updateable query'), that's because the ASPNet user account needs the correct permissions on the directory

where the database resides To fix this in Windows 2K:

• (Go into Accessories/Computer Management/Local Users & Groups/users You will see that there's an

ASPNet user. )

• Right click on the directory where your database is - choose properties - Then the security tab - then

click on permissions.

• Add the ASPNet user to the shared section

• Then, make sure it has 'Change' rights -

• Click Apply and you should be working fine then.

3.37 When compiling I get "Could not copy temporary files to the output
directory" or "The process cannot access the file because it is being used
by another process" error messages. Why?

Visual Studio .NET is unable to copy your DLLs from Bin directory to a temporary ASP.NET files folder. This is

due to having a trailing backslash in root web application, or in a virtual directory with child directories

marked as Web applications. For more information refer KB Q319991

3.38 Why do I get error message "Failed to Start Monitoring Directory


Changes" when i try to browse ASP.NET page?
1. The ASPNET worker process doesn't have "Read & Execute", " List Folder Contents", " Read

permissions" permissions to detect file changes in Web.Config, Machine.config, Bin files, or Cach

dependency files.

2. Or one of the directory names in the hierarchy of that file path is greater than eight characters long.

For more information refer

• PRB: "Failed to Start Monitoring Directory Changes" Error Message When You Browse to ASP.NET

Page

• FIX: "Failed to start monitoring directory changes" error message when you browse to an ASP.NET

page

3.39 Why do I get Compilation error "<Control> is not a member of


<Page>"?

You may get this error if you have not give runat=server for a tag

3.40 How to see the Message in the Output window using ASP.NET?

VB.NET

System.Diagnostics.Trace.Write("Your message")

C#

System.Diagnostics.Trace.Write("Your message");

3.41 How can I use Tracing in Custom Components?

In Custom Components, you can use tracing if you reference the System.Web namespace and use the

HttpContext.Current object to get a reference to the current context. Eg:

VB.NET

System.Web.HttpContext.Current.Trace("xxx", "Message")

C#

System.Web.HttpContext.Current.Trace("xxx", "Message");
Also make sure to set the following directives:

For Page Level Tracing set Page Directive as

<%@ Page Trace="true" %>

For Application Level Tracing modify corresponding web.config as

<configuration>
<system.web>
<trace enabled="true" requestLimit="10" pageOutput="false" traceMode="SortByTime"
localOnly="true" />
</system.web>
</configuration>

FAQ Home
4. Miscellaneous
4.1 How to get the currently logged in user?

To get the user ID of the user who is currently logged in, you would get it using this:

System.Web.HttpContext.Current.User.Identity.Name VB.NET

'Displays the currently logged in user


Response.Write(User.Identity.Name.ToString())

C#

//Displays the currently logged in user


Response.Write(User.Identity.Name.ToString());

4.2 How to specify a line break in a Label's Text?

Use the "<br>" tag to specify line breaks. For example:

VB.NET

Label1.Text = "<sometag1>" + "<br>" + "<sometag1>"

C#
Label1.Text = "<sometag1>" + "<br>" + "<sometag1>";

4.3 How to convert a string to HTML format?

Use namespace System.Web.HttpUtility

VB.NET

Dim mystring as string =”Tom & Jerry”


Response.Write (HttpUtility.HtmlDecode (mystring))

C#

string mystring=”Tom & Jerry”;


Response.Write (HttpUtility.HtmlDecode (mystring));

4.4 How do I determine if the user clicked a "Submit" button twice in the
page?

Check out Andy Smith's OneClick Control

4.5 How to write date-time values of fields in a dataset into xml in a


specific format?

Refer Format DateTime Values in XML extracted from Dataset

4.6 What does "~" mean in ASP.NET applications?

The tilde (~) in front of URLs means that these URLs point to the root of your web application.

Web developers are familiar with using relative paths for all links, including hyperlinks, images, and

stylesheets, to be able to move around web pages collectively.

In ASP.NET when using User controls the relative paths can be difficult to use. The typical solution to this is to

use web-root absolute paths instead here, resulting in the hard-coded sub-directories that are common on

ASP.NET sites.
The correct solution to this problem is to use app-relative paths instead, which ASP.NET nicely makes possible

through the use of the tilde (~) prefix. Instead of <a href="/UC/Page.aspx">, use <a href="~/Page.aspx"

runat="server">. The same ~ notation works for images also, as long as you add runat="server". There is

also a ResolveUrl method that allows you to use ~ in your own code, which is one possible way to get

stylesheet paths app-relative. Refer Tilde: Reference the Application Root

4.7 How can I reference simple DLL which contains one class but has no
namespace assigned to it in an .aspx page?

You don't need a namespace to reference it; anything in the bin folder is implicitly in the same namespace as

the page being compiled. So if your class looks like this:

Public Class MyClass1


Public Sub New()
End Sub

public Function getTheName(byval strval as string) as string


Return "Hello" + strval
End function
End Class

VB.NET

Dim mc As New MyClass1


Response.Write(mc.getTheName)

C#

MyClass1 mc = new MyClass1();


Response.Write(mc.getTheName);

4.8 How do I specify the Japanese locale for the controls in my Japanese
localized page?

Just set the locale to Japanese in the Page directive.

i. e Set the Culture= "ja-JP" for the Page Directive.

• ASP.NET pages support Culture and UICulture attributes to support independent localized pages.
• Controls on pages can pick the culture of the page and can render culture-dependent content.

4.9 Why do some of the events on my page fire twice?

This is probably because you explicitly subscribed to the events in code and also specified the

AutoEventWireUp of Page to true (it's true by default). If so, the Page_Load, for example, will be fired once

for your event subscription and once because the Page subscribed it for you (by looking for a specific event

handler method signature).

To avoid this turn off AutoEventWireUp or remove your subscription code.

4.10 How to remove the spaces in a given string?

Use the Namespace System.Text.RegularExpressions VB.NET

Dim strval As String = "Jack and Jill"


Dim strnewval As String = Regex.Replace(strval, " ", "")
Response.Write(strnewval)

C#

string strval = "Jack and Jill";


string strnewval = Regex.Replace(strval, " ", "");
Response.Write(strnewval) ;

4.11 I get the error System.__ComObject when using recordset?

This error occurs if you are trying to fetch the recordset value as follows

rs.Fields("productname")

To avoid this error try VB.NET


rs.Fields("productname").Value.ToString()

C#

rs.Fields["productname").Value.ToString() ;

4.12 Why do I get error "A generic error occurred in GDI+." when trying
to save the bitmap file?

May be the path of the file you are giving is wrong or you do not have write permissions on the specific folder.

4.13 How can I force a Save As dialog box from an ASP.NET Web page.

VB.NET

Response.Clear()
Response.AppendHeader("content-disposition", "attachment; filename=document1.doc")
Response.ContentType = "text/plain"
Response.WriteFile(Server.MapPath("document1.doc"))
Response.Flush()
Response.End()

C#

Response.Clear();
Response.AppendHeader("content-disposition", "attachment; filename=document1.doc");
Response.ContentType = "text/plain";
Response.WriteFile(Server.MapPath("document1.doc"));
Response.Flush();
Response.End();

4.14 In ASP.NET is there a control similar to Combobox in Windows


forms?

Check out Andy Smith's ComboBox Control

Also an useful article by Khoi ComboBox WebControl

4.15 How to do text encryption and decryption?


Here are some interesting articles that talk about encryption and decryption:

• Encrypting Cookie Data with ASP.NET

• Using MD5 to Encrypt Passwords in a Database

• String Encryption With Visual Basic .NET

4.16 How can I trigger a submit on my form when the enter key is
pressed?

Add this to the body element:

<body MS_POSITIONING= "GridLayout"onkeypress="if(window.event.keyCode==13){


document.Form1.submit();}">
...
</body>

Also check out Andy Smith's DefaultButton Control which triggers submit selectively on one of many buttons

based on the context.

4.17 How to get list of all files in the directory?

To get the list of aspx files under your app directory:

Use namespace System.IO

VB.NET

Dim dirInfo As New DirectoryInfo(Server.MapPath(""))


DataGrid1.DataSource = dirInfo.GetFiles("*.aspx")
DataGrid1.DataBind()

C#

DirectoryInfo dirInfo = new DirectoryInfo(Server.MapPath(""));


DataGrid1.DataSource = dirInfo.GetFiles("*.aspx");
DataGrid1.DataBind();
The following aspx code will display the resultant files list in the DataGrid in a proper format:

<asp:DataGrid runat="server" id="DataGrid1" AutoGenerateColumns="False">


<Columns>
<asp:HyperLinkColumn DataNavigateUrlField="Name" DataTextField="Name" HeaderText="File
Name"></asp:HyperLinkColumn>
<asp:BoundColumn DataField="LastWriteTime" HeaderText="Last Write Time"
DataFormatString="{0:d}"></asp:BoundColumn>
<asp:BoundColumn DataField="Length" HeaderText="File Size" DataFormatString="{0:#,###
bytes}"></asp:BoundColumn>
</Columns>
</asp:DataGrid>

4.18 What is HttpHandler?

An HttpHandler is a class that handles HTTP requests. In ASP.Net a Page class, for example, is the default

HttpHandler for files with a .aspx extension. You can map different file extensions to different HttpHandlers in

ASP.Net. When the web server receives a request for a file, it looks in its configuration to find out whether a

special HttpHandler has been designated for that file extension. ASP.Net provides the HttpHandler class to

extend the functionality of ASP.net to be able to handle requests for other file types (extensions). In IIS, you

make ASP.Net the HttpHandler for the type of file that you desire, and use the web.config file for your web to

identify what DLL (Class Library) is used to handle specific file extensions.

The HttpHandler is a class that handles the request. It has access to the same HttpContext (Request,

Response, Cookies, Session, Application, Server, etc) that the Page class does. For more detailed information,

see: HttpHandlers

4.19 How to get the size of a byte array?

VB.NET

myByteArray.Length

C#

myByteArray.Length;
4.20 How to know the width and height in pixels of a given image
programmatically?

You will have to create a Bitmap instance from the image file and then query the Width and Height as follows:

VB.NET

Dim bm As Bitmap = New Bitmap(Server.MapPath("b2346.jpg"))


Response.Write("Height :" + bm.Height.ToString())
Response.Write("<br> Width :" + bm.Width.ToString())

C#

Bitmap bm = new Bitmap( Server.MapPath("b2346.jpg"));


Response.Write ("Height :" + bm.Height.ToString() );
Response.Write ("<br> Width :" +bm.Width.ToString() );

4.21 When using FormsAuthentication, how can I redirect a user to a


different page other than the default page?

When FormsAuthentication is used in ASP.NET, by default, it gets redirected to the default.aspx page.

To redirect it to some other page other than default.aspx you have to use the code below.

VB.NET

FormsAuthentication.SetAuthCookie(txtUsername.Text,false)
Response.Redirect("someotherpage.aspx")

C#

FormsAuthentication.SetAuthCookie(txtUsername.Text,false);
Response.Redirect("someotherpage.aspx");

4.22 Is there a control in ASP.NET for geting HTML like the ASPHTTP for
the classic asp.

Use System.Net.HttpWebRequest

4.23 Why do I get error message "System.Web.HttpException: Request is


not available in this context" " when using Cookies?

Try using "System.Web.HttpContext.Current.Request.Cookies" instead of "Request.Cookies" in your code.

4.24 How to save the Output of ASP.NET to HTML?

Use the namespaces

• System.Net which have classes WebRequest and WebResponse.

o WebRequest is the abstact base class for the .NET Framework's request/response model for

accessing data from the internet and

o WebResponse is the abstract base class from which protocol specific response classes are

derived.

• System.IO which have classes StreamReader and StreamWriter.

o StreamReader designed for character input in a particular encoding.

o StreamWriter designed for character output in a particular encoding.

VB.NET

Dim mywebReq As WebRequest


Dim mywebResp As WebResponse
Dim sr As StreamReader
Dim strHTML As String
Dim sw As StreamWriter
Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
'Give the Appropriate URL for .aspx page. in this case its "http://www.syncfusion.com/faq.asp"
mywebReq = WebRequest.Create("http://www.syncfusion.com/faq.asp")
mywebResp = mywebReq.GetResponse()
sr = New StreamReader(mywebResp.GetResponseStream)
strHTML = sr.ReadToEnd
sw = File.CreateText(Server.MapPath("temp.html"))
sw.WriteLine(strHTML)
sw.Close()
Response.WriteFile(Server.MapPath("temp.html"))
End Sub

C#
WebRequest mywebReq ;
WebResponse mywebResp ;
StreamReader sr ;
string strHTML ;
StreamWriter sw;
private void Page_Load(object sender, System.EventArgs e)
{
// Put user code to initialize the page here
mywebReq = WebRequest.Create("http://www.syncfusion.com/faq.asp");
mywebResp = mywebReq.GetResponse();
sr = new StreamReader(mywebResp.GetResponseStream());
strHTML = sr.ReadToEnd();
sw = File.CreateText(Server.MapPath("temp.html"));
sw.WriteLine(strHTML);
sw.Close();
Response.WriteFile(Server.MapPath("temp.html"));
}

Note:For creating the file (in above case "temp.html") give appropriate rights (modify and write) to the

ASPNET user.

To specify the Encoding specify the second parameter of the StreamReader accordingly

VB.NET

sr = New StreamReader(mywebResp.GetResponseStream, System.Text.Encoding.ASCII)

C#

sr = new StreamReader(mywebResp.GetResponseStream(), System.Text.Encoding.ASCII);

4.25 Why do I get ViewState error when upgrading my application from a


single web server to a web farm?

This usually happens when encryption is enabled for ViewState in all your pages but the different server

machines use different Validation Keys for encrypting. Ensure that all the machines has the same validation

key specified in their machine.config file. For example, add the following key:

<machinekey validation='3DES'>
4.26 How to convert Color to it's corresponding Hexadecimal value?

VB.NET

Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load


'Put user code to initialize the page here
Response.Write(ToHexColor(Color.Blue))
End Sub

Function ToHexColor(ByVal c As Color) As String


Return "#" + c.ToArgb().ToString("x").Substring(2)
End Function

C#

private void Page_Load(object sender, System.EventArgs e)


{
// Put user code to initialize the page here
Response.Write(ToHexColor(Color.Blue));
}
string ToHexColor(Color c )
{
return "#" + c.ToArgb().ToString("x").Substring(2);
}

4.27 How to Select a record using Listbox and edit/update it's fields
using textboxes?

<TABLE class="cdb-AltRow2" id="Table1" style="Z-INDEX: 101; LEFT: 189px; POSITION: absolute; TOP:
20px" cellSpacing="1" cellPadding="1" width="300" border="0">
<TR>
<TD>ProductID</TD>
<TD><asp:textbox id="txtProductId" runat="server" Enabled="False"></asp:textbox></TD>
</TR>
<TR>
<TD>Qunatity per unit</TD>
<TD><asp:textbox id="txtQuantity" runat="server"></asp:textbox></TD>
</TR>
<TR>
<TD>UnitPrice</TD>
<TD><asp:textbox id="txtUnitPrice" runat="server"></asp:textbox></TD>
</TR>
<TR>
<TD></TD>
<TD><asp:button id="btnUpdate" runat="server" Text="Update"></asp:button></TD>
</TR>
<TR>
<TD></TD>
<TD><asp:label id="lblError" runat="server" Visible="False"></asp:label></TD>
</TR>
</TABLE>
<asp:listbox id="ListBox1" style="Z-INDEX: 102; LEFT: 8px; POSITION: absolute; TOP: 12px"
runat="server" AutoPostBack="True"></asp:listbox>

VB.NET

Dim productid As String


Dim strSQL As String
Dim strConn As String
Dim dr, dr1 As SqlDataReader
Dim mycn As SqlConnection
Dim mycmd As SqlCommand

Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load


strConn="server=localhost;uid=sa;database=northwind;pwd=;"
lblError.Visible = False
' Put user code to initialize the page here
If Not Page.IsPostBack Then
mycn = New SqlConnection(strConn)
strSQL = "Select * from Products"
mycmd = New SqlCommand(strSQL, mycn)
mycn.Open()
dr = mycmd.ExecuteReader(CommandBehavior.CloseConnection)
ListBox1.DataSource = dr
ListBox1.DataTextField = "ProductID"
ListBox1.DataValueField = "ProductID"
ListBox1.DataBind()
End If
End Sub 'Page_Load

Private Sub btnUpdate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles


btnUpdate.Click
Try
lblError.Visible = False
Dim updateCmd As String = "UPDATE Products SET QuantityPerUnit = @QuantityPerUnit ," + "UnitPrice =
@UnitPrice where ProductId=@ProductId"
Dim cn As New SqlConnection(strConn)
Dim myCommand As New SqlCommand(updateCmd, cn)
myCommand.Parameters.Add(New SqlParameter("@QuantityPerUnit", txtQuantity.Text))
myCommand.Parameters.Add(New SqlParameter("@UnitPrice", Convert.ToDouble(txtUnitPrice.Text)))
myCommand.Parameters.Add(New SqlParameter("@ProductId", Convert.ToInt16(txtProductId.Text)))
cn.Open()
myCommand.ExecuteNonQuery()
lblError.Visible = True
lblError.Text = "Record Updated successfully"
Catch ex As Exception
lblError.Visible = True
lblError.Text = ex.Message
End Try
End Sub 'btnUpdate_Click

Private Sub ListBox1_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs)


Handles ListBox1.SelectedIndexChanged
productid = ListBox1.SelectedItem.Value
txtProductId.Text = productid.ToString()
strSQL = "Select * from Products where productid =" + productid
mycn = New SqlConnection(strConn)
mycmd = New SqlCommand(strSQL, mycn)
mycn.Open()
dr1 = mycmd.ExecuteReader(CommandBehavior.CloseConnection)
If dr1.Read() Then
txtProductId.Text = dr1("ProductId").ToString()
txtQuantity.Text = dr1("QuantityPerUnit").ToString()
txtUnitPrice.Text = dr1("UnitPrice").ToString()
Else
Response.Write("No data found")
End If
End Sub 'ListBox1_SelectedIndexChanged

C#

string productid;
string strSQL;
string strConn;
SqlDataReader dr,dr1;
SqlConnection mycn;
SqlCommand mycmd;

private void Page_Load(object sender, System.EventArgs e)


{
strConn="server=localhost;uid=sa;database=northwind;pwd=;";
lblError.Visible =false;
// Put user code to initialize the page here
if (!Page.IsPostBack )
{
mycn = new SqlConnection(strConn);
strSQL ="Select * from Products";
mycmd = new SqlCommand (strSQL, mycn);
mycn.Open ();
dr=mycmd.ExecuteReader(CommandBehavior.CloseConnection );
ListBox1.DataSource = dr;
ListBox1.DataTextField ="ProductID";
ListBox1.DataValueField ="ProductID";
ListBox1.DataBind ();
}
}

private void btnUpdate_Click(object sender, System.EventArgs e)


{
try
{
lblError.Visible =false;

string updateCmd = "UPDATE Products SET QuantityPerUnit = @QuantityPerUnit ,"


+ "UnitPrice = @UnitPrice where ProductId=@ProductId";

SqlConnection cn = new SqlConnection (strConn);


SqlCommand myCommand = new SqlCommand(updateCmd, cn);
myCommand.Parameters.Add(new SqlParameter("@QuantityPerUnit", txtQuantity.Text ));
myCommand.Parameters.Add(new SqlParameter("@UnitPrice", Convert.ToDouble( txtUnitPrice.Text
)));
myCommand.Parameters.Add(new SqlParameter("@ProductId", Convert.ToInt16
( txtProductId.Text)));
cn.Open ();
myCommand.ExecuteNonQuery ();
lblError.Visible =true;
lblError.Text ="Record Updated successfully";
}
catch(Exception ex)
{
lblError.Visible =true;
lblError.Text =(ex.Message );
}
}

private void ListBox1_SelectedIndexChanged(object sender, System.EventArgs e)


{
productid = ListBox1.SelectedItem.Value ;
txtProductId.Text =productid.ToString ();
strSQL = "Select * from Products where productid =" + productid ;
mycn = new SqlConnection(strConn);
mycmd = new SqlCommand (strSQL, mycn);
mycn.Open ();
dr1=mycmd.ExecuteReader(CommandBehavior.CloseConnection );
if(dr1.Read() )
{
txtProductId.Text = dr1["ProductId"].ToString ();
txtQuantity.Text = dr1["QuantityPerUnit"].ToString ();
txtUnitPrice.Text = dr1["UnitPrice"].ToString ();
}
else
{
Response.Write ("No data found");
}
}

4.28 How to select a value from a child form and send it to parent form?

page1.aspx

<asp:TextBox id="txtSelect" style="Z-INDEX: 101; LEFT: 186px; POSITION: absolute; TOP: 19px"
runat="server"></asp:TextBox>
<ahref="javascript:my_window=window.open('page2.aspx?formname=Form1.txtSelect','my_window','width=300,height=
Select CategoryName</a>

page2.aspx

<asp:DropDownList id="DropDownList1" style="Z-INDEX: 101; LEFT: 180px; POSITION: absolute; TOP:


66px"
runat="server" AutoPostBack="True">
<asp:Label id="Label1" style="Z-INDEX: 102; LEFT: 16px; POSITION: absolute; TOP: 66px"
runat="server">Select Category Name
<asp:Literal id="Literal1" runat="server">

VB.NET
Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
'Put user code to initialize the page here
If Not Page.IsPostBack Then
'Fill DataSet ....
DropDownList1.DataSource = ds.Tables(0)
DropDownList1.DataTextField = "CategoryName"
DropDownList1.DataValueField = "CategoryId"
DropDownList1.DataBind()
End If
End Sub

Private Sub DropDownList1_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As


System.EventArgs) Handles DropDownList1.SelectedIndexChanged
Try
Dim strjscript As String = "<script language=""javascript"">"
strjscript = strjscript & "window.opener." & HttpContext.Current.Request.QueryString("formname") &
".value = '" & DropDownList1.SelectedItem.Text & "';window.close();"
strjscript = strjscript & "</script>"
Literal1.Text = strjscript
Catch ex As Exception
Response.Write(ex.Message)
End Try
End Sub

C#

private void Page_Load(object sender, System.EventArgs e)


{
// Put user code to initialize the page here
if (!Page.IsPostBack )
{
//Fill DataSet
DropDownList1.DataSource = ds.Tables[0];
DropDownList1.DataTextField = "CategoryName";
DropDownList1.DataValueField = "CategoryId";
DropDownList1.DataBind();
}
}

private void DropDownList1_SelectedIndexChanged(object sender, System.EventArgs e)


{
try
{
string strjscript = @"<script language=""javascript"">";
strjscript = strjscript + "window.opener." +
HttpContext.Current.Request.QueryString["formname"].ToString () + ".value = '" +
DropDownList1.SelectedItem.Text + "';window.close();";
strjscript = strjscript + "</script>";
Literal1.Text = strjscript;
}
catch(Exception ex)
{
Response.Write (ex.Message );
}
}
4.29 How to read the comma seperated values from a string?

VB.NET

Dim myString As String = "A, B, C, D"


Dim delimStr As String = " ,"
Dim delimiter As Char() = delimStr.ToCharArray()
Dim s As String
For Each s In myString.Split(delimiter)
Response.Write((s.ToString() + "<br>"))
Next

C#

string myString = "A, B, C, D";


string delimStr = " ,";
char[] delimiter = delimStr.ToCharArray();
foreach (string s in myString.Split(delimiter))
{
Response.Write (s.ToString ()+ "<br>");
}

4.30 How do I make my TextBox positioned below a DataGrid move up or


down in position as the height of the DataGrid changes?

Specify the pageLayout of the Document from GridLayout to FlowLayout, this will position the controls

automatically and optimally.

4.31 How to stamp Date-Time on all the pages in an application when


requested?

Use the global.asax file and listen to the PostRequestHandlerExecute event of the Global object.

In the handler Global_PostRequestHandlerExecute write the following code

VB.NET

Response.Write("This page is updated on " & DateTime.Now.ToString())

Response.Write("This page is updated on " + DateTime.Now.ToString());


4.32 How can I have multiple command buttons map to the same event
or function?

Simply use the same handler for the different button Click events.

<asp:Button id="Button1" runat="server" Text="Button"></asp:Button>


<asp:Button id="Button2" style="Z-INDEX: 103; LEFT: 8px; POSITION: absolute; TOP: 80px" runat="server"
Text="Button"></asp:Button>

VB.NET

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles


Button1.Click, Button2.Click
Response.Write("hi you clicked " + CType(sender, Button).ID)
End Sub

C#

// In InitializeComponent
this.Button1.Click += new System.EventHandler(this.Button1_Click);
this.Button2.Click += new System.EventHandler(this.Button1_Click);

private void Button1_Click(object sender, System.EventArgs e)


{
Response.Write("hi you clicked " + ((Button)sender).ID );
}

4.33 How to use a RangeValidator to select Colors from a specific range?

<asp:dropdownlist id="DropDownList1" runat="server">


<asp:ListItem Value ="#000000">#000000</asp:ListItem>
<asp:ListItem Value ="#ff0000">#ff0000</asp:ListItem>
<asp:ListItem Value ="#0000ff">#0000ff</asp:ListItem>
<asp:ListItem Value ="#00aacc">#00aacc</asp:ListItem>
<asp:ListItem Value ="#0000cc">#0000cc</asp:ListItem>
<asp:ListItem Value ="#cc0000">#cc0000</asp:ListItem>
<asp:ListItem Value ="#00ff00">#00ff00</asp:ListItem>
</asp:dropdownlist>
<asp:rangevalidator id="RangeValidator1" runat="server"
ErrorMessage="Select a color between #00ff00 to #ff0000" ControlToValidate="DropDownList1"
MaximumValue="#ff0000" MinimumValue="#00ff00">
</asp:rangevalidator>

4.34 How to restore the browser's scroll position after a postback?

Set the SmartNavigation attribute to true.

4.35 Is there something as RecordSet we had in ASP that can be used in


ASP.NET?

You can make use of a DataReader.

Refer How to display data in Textboxes using DataReader?

4.36 How to set a <link> tag's href attribute at runtime using a value
specified in the web.config file?

web.config

<configuration>
<appSettings>
<add key="CSS1" value="StyleSheet1.css" />
</appSettings>
</configuration>

.aspx

<link id="link1" runat="server"/>

VB.NET

Dim lnk As New System.Web.UI.HtmlControls.HtmlGenericControl("lnk")


lnk = CType(Me.Page.FindControl("link1"), System.Web.UI.HtmlControls.HtmlGenericControl)
lnk.Attributes.Add("rel", "stylesheet")
lnk.Attributes.Add("href", ConfigurationSettings.AppSettings("CSS1").ToString())
lnk.Attributes.Add("type", "text/css")

C#

System.Web.UI.HtmlControls.HtmlGenericControl lnk =new System.Web.UI.HtmlControls.HtmlGenericControl


("lnk") ;
lnk =(System.Web.UI.HtmlControls.HtmlGenericControl ) this.Page.FindControl( "link1") ;
lnk.Attributes.Add ("rel", "stylesheet");
lnk.Attributes.Add ("href", ConfigurationSettings.AppSettings["CSS1"].ToString()) ;
lnk.Attributes.Add ("type","text/css");

4.37 How to call the Page_load procedure from any event on the page?

VB.NET

Dim strval As String = "a"


If strval = "a" Then
Call Page_Load(sender, e)
End If

C#

string strval ="a";


if( strval =="a")
{
Page_Load(sender,e);
}

4.38 How to add login user (ASPNET) to MS SQL 2000 Desktop Engine
server?

Go to drive:\Program Files\Microsoft SQL Server\80\Tools\binn

Use OSQL, a command line tool.

osql -S servername\instancename -E -q
--Line numbers will appear
EXEC sp_grantlogin 'machinename\ASPNET'
go

use
go

EXEC sp_grantdbaccess 'machinename\ASPNET'


go

EXEC sp_addrolemember 'db_owner', 'machinename\ASPNET'


go

4.39 How to get the count of rows in a Excel file?


Add reference -> COM tab ->Microsoft Excel 11.0 Object Library

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

VB.NET

Dim excelApp As New Microsoft.Office.Interop.Excel.Application


excelApp.Workbooks.Open(Server.MapPath("excel1.xls"))
Label1.Text = excelApp.ActiveSheet.Usedrange.count.ToString
excelApp.Workbooks.Close()

C#

Microsoft.Office.Interop.Excel.Application excelApp = new Microsoft.Office.Interop.Excel.Application();


excelApp.Workbooks.Open ( Server.MapPath ("excel1.xls"), Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing, Type.Missing, Type.Missing );
Microsoft.Office.Interop.Excel.Worksheet wks;
wks =(Microsoft.Office.Interop.Excel.Worksheet)excelApp.ActiveSheet;
Label1.Text =wks.UsedRange.Count.ToString();
excelApp.Workbooks.Close();

4.40 What are the pros and cons of using Session or Cache to save
intermediate state?

To store in Session:

Pros:

• It's stored per user session

• It's just a handle to a live object, if using InProc

• If you use StateServer or SQLServer mode, you can access your session state across the webfarm.

(can't use InProc mode in webfarm)

Cons:

• If you use StateServer or SQLServer mode, your object must be serializable, and you pay the

performance cost of network traffic + serialization cost

To use cache:
Pros:

• It's always stored as just a handle to the live object

• Can use cache dependencies or other cache features to control its lifetime

• Can be shared by all users on that web server

Cons:

• It's per app-domain per web server.

4.41 How to mirror (align elements Right to Left) a form or control on a


form?

Process of switching of User Interface between left to right i.e English, German ...and right to left such as

Hebrew/Arabic is called Mirroring.

To mirror a form

<html dir="rtl">

To mirror individual control in a form set dir=rtl for individual controls.

4.42 How can I Enable ASPX Compression in IIS?

You can use Http Compression to compress static aspx files. Refer Microsoft Knowledge Base Article -

322603

4.43 How to run an exe from a ASP.NET page?

For security reasons, you can't force a user to run any executable.

Instead give user the option to click on it and download the executable, and execute it if he wants to. All you

can do is put .exe in a directory on your web site and put a hyperlink to it on some page.

Note : Be sure to secure this directory by deactivating all execution permissions both in the IIS console and

in the directory ACL


For more details refer INFO: Executing Files by Hyperlink and the File Download Dialog Box

4.44 Why does FormsAuthentication.Decrypt crashes when moving to


another Server?

The reason why the encrypted data couldn't be decrypted on another machine is because the validation key

in the original machine's machine.config is set to AutoGenerate. This means that the generated keys are

unique to each machine. A better solution will be to specify the validation key, so you can decrypt it across

any machine with the same validation key. For more details on solutioon refer following article :

• Microsoft Knowledge Base Article - 313091

• Microsoft Knowledge Base Article - 312906

4.45 Why do I get error message "Login failed for user


DOMAIN\USERNAME"?

You'll have to create an account in SQL Server for the aspnet user.

• Start enterprise manager-> expand the server-> select security->Right-click in the right view and

select new login,

• enter the DOMAIN\USERNAME and select your database as the default database of the user at the

bottom of the page,

• Select last tab Database Access -> select your database, and add the db_datareader and

db_datawriter policies to your user.

4.46 How to check if the current User has been Authenticated?

VB.NET

If User.Identity.IsAuthenticated Then
'Your code
End If
C#

if (User.Identity.IsAuthenticated )
{
//Your code
}

4.47 How to get the Computer Name on which the code is running?

This will return the information of the server computer, not the client browser computer.

Add reference to System.Windows.Forms.dll.

VB.NET

Response.Write(System.Windows.Forms.SystemInformation.ComputerName)

C#

Response.Write(System.Windows.Forms.SystemInformation.ComputerName);

4.48 How to pass argument to accessdatasourcecontrol selectcommand


statement?

VB.NET

AccessDataSourceControl1.SelectCommand = "SELECT * FROM <tablename> WHERE <fieldname> = " &


Request("CustID")

C#

AccessDataSourceControl1.SelectCommand = "SELECT * FROM <tablename> WHERE <fieldname> = "+


Request["CustID"]

4.49 How to compile CS/VB file and place new DLL in bin subdirectory?
You can build a dll using the following command line .

Assuming your command window has the appropriate path set to use the following exes:

VB.NET compiler vbc.exe

vbc.exe /out:SyncVB.dll /target:library SyncVB.vb

C# compiler csc.exe

csc.exe /out:SyncCS.dll /target:library SyncCS.cs

To reference it within the .aspx page use the Import directive:

<%@ Import Namespace="SyncVB" %>

or

<%@ Import Namespace="SyncCS" %>

4.50 Can I use a src attribute with a Web Service?

The .aspx pages are the only ones that support the Src attribute, and therefore it's the only file type that

supports JIT compilation of separate source files.By using the Src attribute in the page directive, you can

specify which file the ASP.NET engine should compile.

It cannot be used with a WebService.

This means that you must precompile the code behind class that is to be used as the basis for the Web

Service, either manually using the Command-line compiler or by building a Visual Studio.NET Web Service

Application.

4.51 How to display random images on a web page from a set of images
in a directory?

<table id="Table1" cellspacing="1" cellpadding="1" border="1">


<tr>
<td id="TD1" width="100" runat="server">

</td>
</tr>
</table>

VB.NET (Add reference to Microsoft Visual Basic .NET Runtime)

Dim dirInfo As New System.IO.DirectoryInfo("c:\inetpub\wwwroot\syncfusion\images") 'This is your path to


the bmp's
Dim fileInfo() As IO.FileInfo
Dim strRandomImage As String
Dim i As Integer
Dim rnd As Random
fileInfo = dirInfo.GetFiles("*") 'Gets an array of file info
rnd = New Random
Randomize()
i = CInt(rnd.NextDouble * UBound(fileInfo)) ' gets a random index
strRandomImage = "images/" + fileInfo(i).Name ' Returns the random string
TD1.Attributes.Add("background", strRandomImage)

C#

System.IO.DirectoryInfo dirInfo =new


System.IO.DirectoryInfo(@"c:\inetpub\wwwroot\SyncnewCsharp\images") ;//This is your path to the bmp's
System.IO.FileInfo[] fileInfo ;
string strRandomImage;
int i ;
Random rnd ;
fileInfo = dirInfo.GetFiles("*"); //Gets an array of file info
rnd = new Random();
Microsoft.VisualBasic.VBMath.Randomize ();
i = Convert.ToInt32 (rnd.NextDouble() * fileInfo.GetUpperBound(0));// gets a random index
strRandomImage = "Images/" + fileInfo[i].Name ;// Returns the random string
TD1.Attributes.Add ("background", strRandomImage);

4.52 How can I scan a string to determine if it contains DBCS chars?

VB.NET

Public Shared Function IsAsciiString(s As [String]) As Boolean


Dim i As Integer
For i = 0 To s.Length - 1
Dim ch As Char = s(i)
If ch < 0 Or ch > 127 Then
Return False
End If
Next
Return True
End Function 'IsAsciiString

'In Page_Load
dim originalString as string = "a±"
Response.Write (IsAsciiString(originalString))

C#

public static bool IsAsciiString(String s)


{
for (int i = 0; i < s.Length; i++)
{
char ch = s[i];
if (ch < 0 || ch > 127) return false;
}
return true;
}
//In Page_Load
String originalString = "a±" ;
Response.Write (IsAsciiString(originalString));

4.53 Request.ServerVariables("LOGON_USER") always returns empty


string in Framework 1.1 . Why? It worked fine in ASP?

If Request.ServerVariables("LOGON_USER") is returning an empty string, the problem is probably that your

app allows anonymous users. To change this:

• Open IIS manager

• right-click on your app name and choose properties

• Click on directory security tab

• Edit Authentication and Access Control

• Uncheck 'Enable anonymous'.

4.54 Is there a way to specify CSS only if the browser is IE?

You can examine the Request.UserAgent to check if the browser was IE, define a custom HtmlGenericControl

type representing your stylesheet link and set the href property on it depending on if the browser was IE.

<LINK rel=stylesheet runat="server" id="lnkStyle">


Where LINK is a HtmlGenericControl. You could then do something like this:

VB.NET

lnkStyle.Attributes("href") = "ie/styles.css"

C#

lnkStyle.Attributes["href"] = "ie/styles.css" ;

4.55 How to create Custom Application Settings in the web.config?

In the web.config file add a key-value pair as follows:

<configuration>
<appSettings>
<add key="PageSize" value="10">
</add>
</appSettings>
</configuration>

Then you can access the settings as follows in code:

VB.NET

Response.Write (ConfigurationSettings.AppSettings("PageSize"))

C#

Response.Write (ConfigurationSettings.AppSettings["PageSize"] );

4.56 Why do I get "do not have permissions" error when accessing a
Access mdb file in my local system?

This could be because of security concerns. Please check this KB for resolutions:
KB 316675

4.57 How can I access an MS Access database in my ASPX page, if the db


is on a remote server?

To access an MS Access database from your ASP.Net page, you must use the UNC format in the path, like:

\\Servername\yourpath\your.mdb

To fully use the database, grant permissions to the ASPNet user account equal to 'modify', for the

folder/directory where the database exists.

5. Calendar FAQ Home

5.1 How to display multiple dates selected in Calendar Control?

Set the SelectionMode property of Calendar Control to DayWeek/ DayWeekMonth.

Code for the OnSelectionChanged as follows:

VB.NET

Dim day As DateTime


Dim strval As String
For Each day In Calendar1.SelectedDates
strval += (day.Date.ToShortDateString() & "<br>")
Next
Response.Write(strval)

C#

string strval="" ;
foreach (DateTime day in Calendar1.SelectedDates)
{
strval += (day.Date.ToShortDateString() + "<br>");
}
Response.Write(strval);
}

5.2 How to reset the selected date in the calendar control?


VB.NET

Calendar1.VisibleDate = DateTime.Today
Calendar1.SelectedDates.Clear()

C#

Calendar1.VisibleDate = DateTime.Today;
Calendar1.SelectedDates.Clear();

5.3 How to Customize Individual Days in a Calendar Web Server Control?

Refer Customizing Individual Days in a Calendar Web Server Control

5.4 Is there a way to click an image and let the calendar Control appear?

Refer to these articles:

• Mike's Popup Calendar

Other links

• Matt Hawley's Calendar Popup control

• Peter Blum's Date Package

5.5 How to Programmatically change backgroundcolor of a Calendar


Control using Dropdown List?

<asp:Calendar id="Calendar1" style="Z-INDEX: 101; LEFT: 40px; POSITION: absolute; TOP: 48px"
runat="server"></asp:Calendar>
<asp:DropDownList id="DropDownList1" style="Z-INDEX: 102; LEFT: 40px; POSITION: absolute; TOP: 24px"
runat="server" AutoPostBack="True">
<asp:ListItem Value="Red">Red</asp:ListItem>
<asp:ListItem Value="Green">Green</asp:ListItem>
<asp:ListItem Value="Blue">Blue</asp:ListItem>
</asp:DropDownList>
VB.NET

Private Sub DropDownList1_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As


System.EventArgs) Handles DropDownList1.SelectedIndexChanged
Dim colorName As String = DropDownList1.SelectedItem.Text
Dim objBackColor As System.Drawing.Color = System.Drawing.Color.FromName(colorName)
Calendar1.BackColor = objBackColor
End Sub

C#

private void DropDownList1_SelectedIndexChanged(object sender, System.EventArgs e)


{
string colorName = DropDownList1.SelectedItem.Text;
System.Drawing.Color objBackColor = System.Drawing.Color.FromName(colorName);
Calendar1.BackColor = objBackColor;
}

5.6 How can I change the month and Weekdays to Japanese characters
for a Calendar Control?

Set the Culture= "ja-JP" for the Page.

• ASP.NET pages support Culture and UICulture attributes to support independent localized pages.

• Controls on pages can pick the culture of the page and can render culture-dependent content.

5.7 How can I use a Calendar Control to show specific dates highlighted
and display relevant data for that date?

<asp:Calendar id="Calendar1" OnDayRender ="CalDayRender" runat="server"></asp:Calendar>

Dim ds As DataSet
Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
'Put user code to initialize the page here
'Fill the DataSet
End Sub

Protected Sub CalDayRender(ByVal sender As Object, ByVal e As DayRenderEventArgs)


Dim strName As New StringBuilder
strName.Append("
")
Dim theDay As DateTime = e.Day.Date
Dim sql As String = "hiredate='" + DateTime.Parse(theDay.ToString("d")) + "' "
Dim dr As DataRow() = ds.Tables(0).Select(sql)
Dim drRow As DataRow
For Each drRow In dr
strName.Append("
e.Cell.BackColor = Color.Teal
e.Cell.ForeColor = Color.Wheat
Next drRow
strName.Append("")
e.Cell.Controls.Add(New LiteralControl(strName.ToString()))
End Sub 'CalDayRender

C#

DataSet ds ;
private void Page_Load(object sender, System.EventArgs e)
{
// Put user code to initialize the page here
//Populate the DataSet
}

protected void CalDayRender(object sender, DayRenderEventArgs e)


{
StringBuilder strName = new StringBuilder();
strName.Append("
");
DateTime theDay = e.Day.Date;
string sql ="hiredate='" + DateTime.Parse ( theDay.ToString("d")) + "' ";
DataRow [] dr = ds.Tables[0].Select(sql);
foreach(DataRow drRow in dr)
{
strName.Append("
e.Cell.BackColor = Color.Teal;
e.Cell.ForeColor = Color.Wheat;
}
strName.Append("");
e.Cell.Controls.Add(new LiteralControl(strName.ToString()));
}

5.8 How to clear the Calendar Control Selection?

VB.NET

Calendar1.SelectedDate =new DateTime()

C#
Calendar1.SelectedDate =new DateTime();

5.9 How can I set the Selection of the Calendar Control to date or week
or month?

Set the SelectionMode =DayWeekMonth

You can set it to any of the following:

• Day

• DayWeek

• DayWeekMonth

• None

5.10 How can I display the calendar control in different languages


according to the navigator culture?

Use namespace

• System.Threading

• System.Globalization

<p>
<asp:dropdownlist id="DropDownlist1" runat="server"></asp:dropdownlist></p>
<p>
<asp:Button id="Button1" runat="server" Text="Button"></asp:Button></p>
<asp:calendar id="Calendar1" runat="server"></asp:calendar>

VB.NET

Dim userLang() As String


Dim strLang As String
Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
'Put user code to initialize the page here
userLang = Request.UserLanguages
ViewState("userLanguage") = userLang(userLang.GetUpperBound(0))
If ViewState("userLanguage") = "" Then
ViewState("userLanguage") = "en-US"
End If
Dim ci As CultureInfo
For Each ci In CultureInfo.GetCultures(CultureTypes.AllCultures)
If Not ci.IsNeutralCulture Then
DropDownlist1.Items.Add(ci.ToString)
End If
Next
Dim dtNow As Date = DateTime.Now
strLang = ViewState("userLanguage")
Thread.CurrentThread.CurrentUICulture = New CultureInfo(strLang, False)
Thread.CurrentThread.CurrentCulture = New CultureInfo(strLang)
Calendar1.SelectedDate = dtNow
Calendar1.VisibleDate = dtNow
End Sub

Private Sub Calendar1_SelectionChanged(ByVal sender As System.Object, ByVal e As System.EventArgs)


Handles Calendar1.SelectionChanged
strLang = ViewState("userLanguage")
Thread.CurrentThread.CurrentUICulture = New CultureInfo(strLang, False)
Thread.CurrentThread.CurrentCulture = New CultureInfo(strLang)
End Sub

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles


Button1.Click
strLang = DropDownlist1.SelectedItem.Text
ViewState("userLanguage") = strLang
Thread.CurrentThread.CurrentUICulture = New CultureInfo(strLang, False)
Thread.CurrentThread.CurrentCulture = New CultureInfo(strLang)
End Sub

C#

string[] userLang;
string strLang;
private void Page_Load(object sender, System.EventArgs e)
{
// Put user code to initialize the page here
userLang = Request.UserLanguages;
ViewState["userLanguage"] = userLang[userLang.GetUpperBound(0)];
if( ViewState["userLanguage"].ToString () == "" )
{
ViewState["userLanguage"] = "en-US";
}
foreach(CultureInfo ci in CultureInfo.GetCultures(CultureTypes.AllCultures))
{
if(!ci.IsNeutralCulture)
{
DropDownlist1.Items.Add(ci.ToString());
}
}
DateTime dtNow = DateTime.Now;
strLang =(string) ViewState["userLanguage"];
Thread.CurrentThread.CurrentUICulture = new CultureInfo(strLang, false);
Thread.CurrentThread.CurrentCulture =new CultureInfo(strLang);
Calendar1.SelectedDate = dtNow;
Calendar1.VisibleDate = dtNow;
}

private void Calendar1_SelectionChanged(object sender, System.EventArgs e)


{
strLang =(string) ViewState["userLanguage"].ToString ();
Thread.CurrentThread.CurrentUICulture = new CultureInfo(strLang, false);
Thread.CurrentThread.CurrentCulture = new CultureInfo(strLang);
}

private void Button1_Click(object sender, System.EventArgs e)


{
strLang = DropDownlist1.SelectedItem.Text;
ViewState["userLanguage"] = strLang;
Thread.CurrentThread.CurrentUICulture =new CultureInfo(strLang, false);
Thread.CurrentThread.CurrentCulture = new CultureInfo(strLang);
}

5.11 How to display full day names in a Calendar Control?

Set the DayNameFormat= Full for the Calendar Control

5.12 How to hide the WeekDay Header in the Calendar control?

In the Calendar PreRender Event

VB.NET

Calendar1.ShowDayHeader = False

C#

Calendar1.ShowDayHeader = false;

5.13 How to hide "other months" in a Calendar Control?

In the Calendar DayRender Event

VB.NET

If e.Day.IsOtherMonth = True Then


e.Cell.Text = ""
End If
C#

if (e.Day.IsOtherMonth = true)
{
e.Cell.Text = "";
}

5.14 How to highlight today's date in Calendar Control in different color?

In Calendar DayRender Event

VB.NET

If e.Day.IsToday Then
e.Cell.ForeColor = Color.Blue
e.Cell.BackColor = Color.Pink
End If

C#

if (e.Day.IsToday)
{
e.Cell.ForeColor = Color.Blue;
e.Cell.BackColor = Color.Pink;
}

5.15 How can I use a Calendar Control in readonly mode. i.e no links for
the day and month cells.

In the DayRender Event of calendar Control

VB.NET

If e.Day.IsOtherMonth Then
e.Cell.Text = " "
Else
e.Cell.Text = e.Day.DayNumberText
End If

C#
if (e.Day.IsOtherMonth )
{
e.Cell.Text = " ";
}
else
{
e.Cell.Text = e.Day.DayNumberText;
}

5.16 How to change the Calendar Dates using a Dropdownlist?

<asp:DropDownList id="ddlMonth" style="Z-INDEX: 101; LEFT: 64px; POSITION: absolute; TOP: 24px"
runat="server"
AutoPostBack="True"></asp:DropDownList>
<asp:Label id="Label1" style="Z-INDEX: 103; LEFT: 8px; POSITION: absolute; TOP: 24px"
runat="server">Month</asp:Label>
<asp:DropDownList id="ddlYear" style="Z-INDEX: 102; LEFT: 200px; POSITION: absolute; TOP: 24px"
runat="server"
AutoPostBack="True"></asp:DropDownList>
<asp:Label id="Label2" style="Z-INDEX: 104; LEFT: 152px; POSITION: absolute; TOP: 24px"
runat="server">Year</asp:Label>
<asp:Calendar id="Calendar1" style="Z-INDEX: 105; LEFT: 16px; POSITION: absolute; TOP: 72px"
runat="server"></asp:Calendar>

VB.NET

Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load


' Put user code to initialize the page here
If Not Page.IsPostBack Then
'Populate month in the dropdownlist
Dim strMonth As String = ""
Dim i As Integer
For i = 1 To 12
If i.ToString().Length < 2 Then
strMonth = "0" + i.ToString()
ddlMonth.Items.Add(New ListItem(strMonth, strMonth))
Else
ddlMonth.Items.Add(New ListItem(strMonth, strMonth))
End If
Next

ddlMonth.Items.FindByValue(DateTime.Now.ToString("MM")).Selected = True
'Populate year in the dropdownlist
Dim j As Integer
For j = 1900 To 2050
ddlYear.Items.Add(New ListItem(j.ToString(), j.ToString()))
Next
ddlYear.Items.FindByText(DateTime.Now.ToString("yyyy")).Selected = True
End If
End Sub 'Page_Load

Private Sub ddlMonth_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs)


Handles ddlMonth.SelectedIndexChanged
SetCalendarDate()
End Sub 'ddlMonth_SelectedIndexChanged

Private Sub ddlYear_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs)


Handles ddlYear.SelectedIndexChanged
SetCalendarDate()
End Sub 'ddlYear_SelectedIndexChanged

Sub SetCalendarDate()
Dim dtNewDate As DateTime
dtNewDate = DateTime.Parse((Int16.Parse(ddlMonth.SelectedItem.Text) & "/1/" &
Int16.Parse(ddlYear.SelectedItem.Text)))
Calendar1.TodaysDate = dtNewDate
End Sub 'SetCalendarDate

C#

private void Page_Load(object sender, System.EventArgs e)


{
// Put user code to initialize the page here
if (!Page.IsPostBack )
{
//Populate month in the dropdownlist
string strMonth="";
for(int i = 1 ;i<=12;i++)
{
if (i.ToString().Length <2 )
{
strMonth ="0" + i.ToString ();
ddlMonth.Items.Add (new ListItem(strMonth,strMonth )) ;
}
else
{
ddlMonth.Items.Add (new ListItem(strMonth,strMonth )) ;
}
}
ddlMonth.Items.FindByValue ( DateTime.Now.ToString ("MM")).Selected =true;
//Populate year in the dropdownlist
for(int j = 1900 ;j<=2050;j++)
{
ddlYear.Items.Add (new ListItem(j.ToString(),j.ToString () )) ;
}
ddlYear.Items.FindByText (DateTime.Now.ToString ("yyyy")).Selected =true;
}
}

private void ddlMonth_SelectedIndexChanged(object sender, System.EventArgs e)


{
SetCalendarDate();
}
private void ddlYear_SelectedIndexChanged(object sender, System.EventArgs e)
{
SetCalendarDate();
}
void SetCalendarDate()
{
DateTime dtNewDate;
dtNewDate =DateTime.Parse (Int16.Parse(ddlMonth.SelectedItem.Text) + "/1/" + Int16.Parse(
ddlYear.SelectedItem.Text));
Calendar1.TodaysDate=dtNewDate ;
}

6. User Controls FAQ Home

6.1 How can I include an Asp.NET page in many other Asp.Net pages so
that I don't need to rewrite the code?

One of the approaches is to write and use a UserControl. You can define the user interface, handle events and

expose properties in a UserControl, and then mark a reference and reuse these Controls in any page of your

Web application.

Here is some Sample code

6.2 Is there anything similar to web templates in ASP that I can use in
ASP.Net?

In ASP.NET, you would typically use a User Control to create reusable controls.

6.3 Are there any settings on the application level to make certain
elements appear on every page without having to manually insert code
or insert UserControls?

You can use HttpHandlers and/or HttpModules to insert information on all pages transparently. Check out

Bipin Joshi's article Extending ASP.NET with HttpHandlers and HttpModules

6.4 How to pass a parameter to a user control?

Create a User Control

Below Code goes in User Control

<asp:ImageButton id="ImageButton1" runat="server"></asp:ImageButton>

Create a property called source

VB.NET

Public Property source() As String


Get
Return ImageButton1.ImageUrl
End Get
Set(ByVal Value As String)
ImageButton1.ImageUrl = Value
End Set
End Property

C#

public string source


{
get
{
return ImageButton1.ImageUrl;
}
set
{
ImageButton1.ImageUrl = value;
}
}

Now in your webform:

Drag and drop User Control and set the source property.

<uc1:UCImageButton source="b2346.jpg" id="UCImageButton1" runat="server"></uc1:UCImageButton>

6.5 How to add user control dynamically into another usercontrol?

Here is an example of adding one UserControl into another:

uc1.ascx:
<asp:Label runat="server" text="uc1" ID="Label1" />
<asp:Panel runat="server" id="p1" >Panel UC1</asp:Panel>

uc2.ascx:
<br><asp:Label runat="server" text="uc2" ID="Label1" />

VB.NET

Dim uc1 As UserControl = CType(LoadControl("uc1.ascx"), UserControl)


Controls.Add(uc1)
Dim uc2 As Control = uc1.LoadControl("uc2.ascx")
Dim p1 As Control = uc1.FindControl("p1")
p1.Controls.Add(uc2)
C#

UserControl uc1 = (UserControl)LoadControl("uc1.ascx");


Controls.Add(uc1);
Control uc2 = uc1.LoadControl("uc2.ascx");
Control p1 = uc1.FindControl("p1");
p1.Controls.Add(uc2);

6.6 I have a function inside of the .ascx file. How can I call it from the
web application page(the .aspx file)?

All you need to do is give your user control an ID in the aspx. e.g.

<myTagTest:MarcTest id=myUC runat="server">


</myTagTest:MarcTest>

Then in your aspx code, you can simply use the id to call public methods (and properties) defined by the

ascx. e.g. VB.NET

myUC.writeData(...)

C#

myUC.writeData(...)

6.7 How to dynamically load User Controls?

Create a User Control

<P>
<asp:Button id="Button1" runat="server" Text="Button"></asp:Button></P>
<P>
<asp:Label id="Label1" runat="server"></asp:Label></P>

On button Click

VB.NET
Label1.Text = "Hello"

C#

Label1.Text = "Hello" ;

Create a Webform to use a UserControl

<asp:Panel id="Panel1" runat="server"></asp:Panel>

VB.NET

Dim myControl As Control = CType(Page.LoadControl("UC1.ascx"), Control)


Panel1.Controls.Add(myControl)

C#

Control myControl =(Control)Page.LoadControl("UC1.ascx");


Panel1.Controls.Add(myControl);

6.8 How to change the imageurl of the image control that exists in a
usercontrol?

In the .ascx:

<asp:Image id="Image1" runat="server"></asp:Image>

In .aspx

VB.NET

<uc1:UCImage id="UCImage1" source="b2346.jpg" runat="server"></uc1:UCImage>

Dim UC As UserControl
Dim imgUC As System.Web.UI.WebControls.Image
UC = Page.FindControl("UCImage1")
imgUC = UC.FindControl("Image1")
imgUC.ImageUrl = "b2346.jpg"

C#

UserControl UC ;
System.Web.UI.WebControls.Image imgUC ;
UC = (UserControl)Page.FindControl("UCImage1");
imgUC =(System.Web.UI.WebControls.Image)UC.FindControl("Image1");
imgUC.ImageUrl = "b2346.jpg";

7.1 Why is the DataList not displayed on the web page?

You must have missed the <ItemTemplate> tag

<asp:DataList id="DataList1" runat="server">


<ItemTemplate>
<%#DataBinder.Eval(Container.DataItem, "FieldName").ToString()%>
</ItemTemplate>
</asp:DataList>

7.2 How to change the colors of a row to indicate its the Birthday of the
Employee (for example) in a DataList?

<asp:datalist id="DataList1" OnItemDataBound ="ItemDB" GridLines="Both" RepeatColumns="2"


runat="server" ShowHeader="true">
<HeaderStyle Font-Bold="True" HorizontalAlign="Center" Font-Name="verdana" Font-
Size="10pt"></HeaderStyle>
<ItemStyle Font-Size="10pt"></ItemStyle>
<Headertemplate>
Employee Details
</Headertemplate>
<ItemTemplate>
<%#DataBinder.Eval(Container.DataItem,"LastName")%>
,
<%#DataBinder.Eval(Container.DataItem,"FirstName")%>
<br>
HireDate :
<%#DataBinder.Eval(Container.DataItem,"HireDate")%>
<br>
</ItemTemplate>
</asp:datalist>

VB.NET

Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load


'Put user code to initialize the page here
'Populate the DataList with DataSet
End Sub

Protected Sub ItemDB(ByVal sender As Object, ByVal e As


System.Web.UI.WebControls.DataListItemEventArgs) Handles DataList1.ItemDataBound
Dim drv As DataRowView = CType(e.Item.DataItem, DataRowView)
Dim BDate As DateTime
If e.Item.ItemType = ListItemType.Item Or e.Item.ItemType = ListItemType.AlternatingItem Then
'To check if the BirthDate has null values
If Not drv.Row("BirthDate").ToString = DBNull.Value.ToString Then
'Assign the BirthDate to variable BDate
BDate = DateTime.Parse(drv.Row("BirthDate").ToString)
End If

'If the Employee BirthDay is Today


'Change the row Text Color to blue
If BDate.ToString("dd/MM") = DateTime.Now.ToString("dd/MM") Then
e.Item.ForeColor = Color.Blue
e.Item.Font.Bold = True
End If
End If
End Sub

C#

private void Page_Load(object sender, System.EventArgs e)


{
// Put user code to initialize the page here
DataList1.DataSource =BindDataClass.BindData ();
DataList1.DataBind ();
}

protected void ItemDB(Object sender , System.Web.UI.WebControls.DataListItemEventArgs e )


{
DataRowView drv = (DataRowView)e.Item.DataItem;
DateTime BDate=Convert.ToDateTime (null) ;
if ((e.Item.ItemType == ListItemType.Item )||( e.Item.ItemType == ListItemType.AlternatingItem))
{ //To check if the BirthDate has null values
if( drv.Row["BirthDate"].ToString() != DBNull.Value.ToString())
{
//Assign the BirthDate to variable BDate
BDate = DateTime.Parse(drv.Row["BirthDate"].ToString());
}
//If the Employee BirthDay is Today
//Change the row Text Color to blue
if (BDate.ToString("dd/MM") == DateTime.Now.ToString("dd/MM"))
{
e.Item.ForeColor = Color.Blue;
e.Item.Font.Bold = true;
}
}
}

7.3 How to group the data in the DataList?


<asp:DataList id="DataList1" runat="server" onItemDataBound="ItemDB">
<HeaderTemplate >
<table width=100%>
</HeaderTemplate>
<ItemTemplate>
<tr><td>
<asp:Label Runat=server
text=<%#DataBinder.Eval(Container.DataITem, "Title")%> ID="lblTitle">
</asp:Label>
<td><asp:Label Runat=server
text=<%#DataBinder.Eval(Container.DataITem, "LastName")%> ID="lblLastName">
</asp:Label>
</ItemTemplate>
<FooterTemplate>
</table>
</FooterTemplate>
</asp:DataList>

VB.NET

Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles MyBase.Load


If Not Page.IsPostBack Then
BindTitle()
End If
End Sub

'Bind Data to DataList Populating the Dataset


Sub BindTitle()
Dim ds As New DataSet
Dim sqlStmt As String = "SELECT * FROM Employees order by title"
DimconStringAsString="server=localhost;database=Northwind;uid=sa;pwd=;"
Dim myda As SqlDataAdapter = New SqlDataAdapter(sqlStmt, conString)
myda.Fill(ds, "Table")
DataList1.DataSource = ds
DataList1.DataBind()
End Sub

'The ItemDataBound Event


Protected Sub ItemDB(ByVal sender As Object, ByVal e As
System.Web.UI.WebControls.DataListItemEventArgs)
If e.Item.ItemType = ListItemType.AlternatingItem Or e.Item.ItemType = ListItemType.Item Then
Dim strval As String = CType(e.Item.FindControl("lblTitle"), Label).Text
Dim title As String = ViewState("title")
If title = strval Then
CType(e.Item.FindControl("lblTitle"), Label).Text = ""
e.Item.Visible = False
Else
title = strval
ViewState("title") = title
CType(e.Item.FindControl("lblTitle"), Label).Text = title
e.Item.Visible = True
End If
End If
End Sub
C#

void Page_Load(object sender, EventArgs e)


{
if (!(Page.IsPostBack))
{
BindTitle();
}
}

void BindTitle()
{
DataSet ds = new DataSet();
string sqlStmt = "SELECT * FROM Employees order by title";
stringconString="server=localhost;database=Northwind;uid=sa;pwd=;";
SqlDataAdapter myda = new SqlDataAdapter(sqlStmt, conString);
myda.Fill(ds, "Table");
DataList1.DataSource = ds;
DataList1.DataBind();
}

protected void ItemDB(object sender, System.Web.UI.WebControls.DataListItemEventArgs e)


{
if (e.Item.ItemType == ListItemType.AlternatingItem | e.Item.ItemType == ListItemType.Item)
{
string strval = ((Label)(e.Item.FindControl("lblTitle"))).Text;
string title = ViewState("title");
if (title == strval)
{
((Label)(e.Item.FindControl("lblTitle"))).Text = "";
e.Item.Visible = false;
}
else
{
title = strval;
ViewState("title") = title;
((Label)(e.Item.FindControl("lblTitle"))).Text = title;
e.Item.Visible = true;
}
}
}

7.4 Which control should I use when binding a multidimensional array?

Use a DataList as follows. .aspx

<asp:datalist id="DataList1" runat="server">


<ItemTemplate>
<asp:repeater datasource="<%#Container.DataItem%>" runat=server ID="Repeater1" >
<ItemTemplate>
<%# Container.DataItem %>
</ItemTemplate>
</asp:repeater>
</ItemTemplate>
</asp:datalist>

VB.NET

Private Sub Page_Load(sender As Object, e As System.EventArgs)


' Put user code to initialize the page here
' Create and populate a multi-dimensional array
Dim MyArray(4) As Integer()
Dim i As Integer
For i = 0 To 3
MyArray(i) = New Integer(5) {}
Dim x As Integer
For x = 0 To 4
MyArray(i)(x) = x + 5 * i
Next
Next
DataList1.DataSource = MyArray
DataList1.DataBind()
End Sub 'Page_Load

C#

private void Page_Load(object sender, System.EventArgs e)


{
// Put user code to initialize the page here
// Create and populate a multi-dimensional array
int [][] MyArray = new int[4][];
for (int i=0; i<4; i++)
{
MyArray[i] = new int[5];
for (int x=0; x<5; x++)
{
MyArray[i][x] = x+(5*i);
}
}
DataList1.DataSource = MyArray;
DataList1.DataBind();
}

7.5 How to display data in multiple columns for a specific Column in a


table in an ASP.NET page?

Use a DataList control and set RepeatColumns= n

n=>Number of columns

7.6 How to use a Hyperlink in a DataList?


<asp:DataList id="DataList1" runat="server">
<ItemTemplate>
<asp:HyperLink Runat =server NavigateUrl ='<%#"webform1.aspx?id=" +
DataBinder.Eval(Container.DataItem, "productid").ToString()%>' ID="Hyperlink1">
<%#DataBinder.Eval(Container.DataItem, "ProductName")%>
</asp:HyperLink>
</ItemTemplate>
</asp:DataList>

7.7 How to do Paging in DataList?

<asp:datalist id="DataList1" runat="server">


<ItemTemplate>
<%#DataBinder.Eval(Container.DataItem, "ProductID").ToString()%>
<%#DataBinder.Eval(Container.DataItem, "ProductName").ToString()%>
</ItemTemplate>
</asp:datalist>
<table width="50%" border="0">
<tr>
<td><asp:LinkButton id="lnkPrevious" runat="server"><<</asp:LinkButton>
<td><asp:LinkButton id="lnkNext" runat="server">>></asp:LinkButton>
</tr>
</table>

VB.NET

Dim intStart As Integer


Dim intpageSize As Integer
Dim cn As SqlConnection
Dim da As SqlDataAdapter
Dim ds As DataSet
Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
'Put user code to initialize the page here
If Not Page.IsPostBack Then
ViewState("Start") = 0
bindList()
End If
End Sub

Sub bindList()
cn=NewSqlConnection("server=localhost;uid=sa;pwd=;database=northwind")
da = New SqlDataAdapter("Select * from Products ", cn)
ds = New DataSet
intStart = ViewState("Start")
ViewState("pageSize") = 14
da.Fill(ds, intStart, ViewState("pageSize"), "Table")
DataList1.DataSource = ds
DataList1.DataBind()
End Sub

Private Sub lnkPrevious_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles


lnkPrevious.Click
intStart = ViewState("Start")- ViewState("pageSize")
ViewState("Start") = intStart
If intStart <= 0 Then
ViewState("Start") = 0
End If
bindList()
End Sub

Private Sub lnkNext_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles


lnkNext.Click
Dim dlistcount As Integer = DataList1.Items.Count
intStart = ViewState("Start") + ViewState("pageSize")
ViewState("Start") = intStart
If dlistcount < ViewState("pageSize") Then
ViewState("Start") = ViewState("Start") - ViewState("pageSize")
End If
bindList()
End Sub

Private Sub lnkFirst_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)


If intStart <= 0 Then
ViewState("Start") = 0
End If
bindList()
End Sub

C#

int intStart ;

SqlConnection cn ;
SqlDataAdapter da ;
DataSet ds ;
private void Page_Load(object sender, System.EventArgs e)
{
// Put user code to initialize the page here
if(!Page.IsPostBack )
{
ViewState["Start"] = 0;
bindList();
}
}

void bindList()
{
cn=newSqlConnection("server=localhost;uid=sa;pwd=;database=northwind");
da = new SqlDataAdapter("Select * from Products ", cn);
ds = new DataSet();
intStart = (int)ViewState["Start"];
ViewState["pageSize"] = 14;
da.Fill(ds, intStart,(int) ViewState["pageSize"], "Table");
DataList1.DataSource = ds;
DataList1.DataBind();
}

private void lnkPrevious_Click(object sender, System.EventArgs e)


{
intStart = (int) ViewState["Start"] -(int) ViewState["pageSize"];
ViewState["Start"] = intStart;
if (intStart <= 0 )
{
ViewState["Start"] = 0;
}
bindList();
}

private void lnkNext_Click(object sender, System.EventArgs e)


{
int dlistcount = DataList1.Items.Count;
intStart = (int) ViewState["Start"]+(int) ViewState["pageSize"];
ViewState["Start"] = intStart;
if ( dlistcount < (int)ViewState["pageSize"] )
{
ViewState["Start"] = (int)ViewState["Start"] - (int)ViewState["pageSize"];
}
bindList();
}

7.8 How to hide and show data in the DataList?

<asp:Datalist runat="server" OnItemCommand ="ItemCmd" id="Datalist1" Font-Size="10pt" Font-


Name="Verdana">
<ItemTemplate>
<asp:LinkButton style="text-decoration:none" runat="server" id="btnDetails" Text="+"
CommandName="Show" Font-Name="Verdana" />
<b>
<%# DataBinder.Eval(Container.DataItem, "employeeid") %>
</b>
<br />
<asp:label id="lblEID" Visible="False" runat="Server" Text='<%#
DataBinder.Eval(Container.DataItem, "Employeeid") %>' />
<asp:DataGrid runat="server" id="Datagrid1" Font-Name="Verdana" Font-Size="10pt"
HorizontalAlign="Center"
Visible="False" Width="85%">
</ItemTemplate>
</asp:Datalist>

VB.NET

Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles MyBase.Load


If Not Page.IsPostBack Then
'Bind data to DataList
End If
End Sub

Private Sub Datalist1_ItemCommand(ByVal source As Object, _


ByVal e As System.Web.UI.WebControls.DataListCommandEventArgs)
If e.CommandName = "Show" Then
Dim EmpIDlabel As Label = e.Item.FindControl("lblEID")
Dim strEmpID As String = EmpIDlabel.Text
CType(e.Item.FindControl("Datagrid1"), DataGrid).DataSource = GetEmpDetails(strEmpID)
CType(e.Item.FindControl("Datagrid1"), DataGrid).DataBind()
CType(e.Item.FindControl("Datagrid1"), DataGrid).Visible = True
CType(e.Item.FindControl("btnDetails"), LinkButton).Text = "-"
CType(e.Item.FindControl("btnDetails"), LinkButton).CommandName = "Hide"
End If
If e.CommandName = "Hide" Then
CType(e.Item.FindControl("Datagrid1"), DataGrid).Visible = False
CType(e.Item.FindControl("btnDetails"), LinkButton).Text = "+"
CType(e.Item.FindControl("btnDetails"), LinkButton).CommandName = "Show"
End If
End Sub

Function GetEmpDetails(ByVal Employeeid As String) As SqlDataReader


ConststrConnStringAsString="server=localhost;uid=sa;pwd=;database=northwind"
Dim objConn As New SqlConnection(strConnString)
Dim strSQL As String
strSQL = "SELECT FirstName , LastName ,Title, Address FROM Employees " & _
"WHERE Employeeid = @Employeeid"
Dim objCmd As New SqlCommand(strSQL, objConn)
Dim paramEmployeeid As SqlParameter
paramEmployeeid = New SqlParameter("@Employeeid", SqlDbType.VarChar, 10)
paramEmployeeid.Value = Employeeid
objCmd.Parameters.Add(paramEmployeeid)
objConn.Open() 'Open the connection
Return objCmd.ExecuteReader(CommandBehavior.CloseConnection)
End Function

C#

private void Page_Load(object sender, System.EventArgs e)


{
// Put user code to initialize the page here
if(!Page.IsPostBack )
{
//Bind data to Datalist1
}
}

protected void ItemCmd(object source , System.Web.UI.WebControls.DataListCommandEventArgs e )


{
if( e.CommandName == "Show" )
{
Label EmpIDlabel =(Label) e.Item.FindControl("lblEID");
string strEmpID = EmpIDlabel.Text;
((DataGrid)e.Item.FindControl("Datagrid1")).DataSource = GetEmpDetails(strEmpID);
((DataGrid)e.Item.FindControl("Datagrid1")).DataBind();
((DataGrid)e.Item.FindControl("Datagrid1")).Visible = true;
((LinkButton)e.Item.FindControl("btnDetails")).Text = "-";
((LinkButton)e.Item.FindControl("btnDetails")).CommandName = "Hide";
}
if( e.CommandName == "Hide" )
{
((DataGrid)e.Item.FindControl("Datagrid1")).Visible = false;
((LinkButton )e.Item.FindControl("btnDetails")).Text = "+";
((LinkButton)e.Item.FindControl("btnDetails")).CommandName = "Show";
}
}

protected SqlDataReader GetEmpDetails(string Employeeid )


{
stringstrConnString="server=localhost;uid=sa;pwd=;database=northwind";
SqlConnection objConn = new SqlConnection(strConnString);
string strSQL ;
strSQL = "SELECT FirstName , LastName ,Title, Address FROM Employees WhERE Employeeid =
@Employeeid";
SqlCommand objCmd = new SqlCommand(strSQL, objConn);
SqlParameter paramEmployeeid ;
paramEmployeeid = new SqlParameter("@Employeeid", SqlDbType.VarChar, 10);
paramEmployeeid.Value = Employeeid;
objCmd.Parameters.Add(paramEmployeeid);
objConn.Open() ;// Open the connection;
return objCmd.ExecuteReader(CommandBehavior.CloseConnection);
}

7.9 How to add a Templatecolumn dynamically to a DataList?

<asp:DataList id="DataList1" runat="server"></asp:DataList>

VB.NET

In class

Public Class DatalistLabelColumn


Implements ITemplate

Public Sub New()


End Sub 'New

Public Sub InstantiateIn(ByVal container As Control) Implements System.Web.UI.ITemplate.InstantiateIn


Dim label1 As New Label
AddHandler label1.DataBinding, AddressOf Me.BindLabelColumn
container.Controls.Add(label1)
End Sub 'InstantiateIn

Public Sub BindLabelColumn(ByVal sender As Object, ByVal e As EventArgs)


Dim lbl As Label = CType(sender, Label)
Dim container As DataListItem = CType(lbl.NamingContainer, DataListItem)
Dim strVals As [String] = Convert.ToString(DataBinder.Eval(CType(container, DataListItem).DataItem,
"LastName")) + ", " + Convert.ToString(DataBinder.Eval(CType(container, DataListItem).DataItem,
"FirstName"))
lbl.Text = strVals
End Sub 'BindLabelColumn

End Class 'DatalistLabelColumn

Dim ds As DataSet = 'Fill the dataset


DataList1.ItemTemplate = New DatalistLabelColumn
DataList1.DataSource = ds
DataList1.DataBind()

C#

In class

public class DatalistLabelColumn : ITemplate


{
public DatalistLabelColumn()
{
//Add constructor stuff here
}

public void InstantiateIn(Control container)


{
Label label1 = new Label();
label1.DataBinding += new EventHandler(this.BindLabelColumn);
container.Controls.Add(label1);
}

public void BindLabelColumn(object sender, EventArgs e)


{
Label lbl = (Label)sender;
DataListItem container = (DataListItem)lbl.NamingContainer ;
String strVals =Convert.ToString(DataBinder.Eval(((DataListItem)container).DataItem, "LastName"))
+ ", " +
Convert.ToString(DataBinder.Eval(((DataListItem)container).DataItem, "FirstName")) ;
lbl.Text = strVals;

}
}

DataSet ds = //Assign appropriate value;


DataList1.ItemTemplate = new DatalistLabelColumn();
DataList1.DataSource =ds;
DataList1.DataBind();

7.10 How to create a File Picker in ASP.NET?

Use namespace System.IO

<asp:label id="lblHeader" runat="server"></asp:label><br>


<b>Get Information on Directory:</b><br>
<p><asp:textbox id="txtPath" runat="server"></asp:textbox>
<p></p>
<asp:button id="btnSubmit" runat="server" text="Go!" type="Submit"></asp:button>
<p></p>
<div style="width:100%; height:200; overflow:auto;">
<asp:datalist id="DataList1" runat="server" DataKeyField="FullName"
OnSelectedIndexChanged="SelectedIndexChanged">
<ItemTemplate>
<li>
<%# DataBinder.Eval(Container.DataItem, "Name") %>
<br>
<font size="-1">[
<asp:linkbutton Text="View Contents" CommandName="Select" runat="server" ID="Linkbutton1" />]
|[
<%# DataBinder.Eval(Container.DataItem, "Length") %>
bytes] </font>
<p>
</ItemTemplate>
</asp:datalist>
</div>
<p>
<hr>
</p><asp:label id="lblFileContents" runat="server"></asp:label>

VB.NET

Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load


'Put user code to initialize the page here
If Request("txtPath") <> "" Then
Dim strDir As String = Request("txtPath")
lblHeader.Text = "File Listing for " & strDir & ""
Dim dirInfo As New DirectoryInfo(strDir)
' Get the files for the directory strDir
Dim fInfos As FileInfo() = dirInfo.GetFiles("*.*")
DataList1.DataSource = fInfos
DataList1.DataBind()
End If
End Sub

Protected Sub SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles


DataList1.SelectedIndexChanged
Dim strFilePath As String = DataList1.DataKeys(DataList1.SelectedItem.ItemIndex).ToString()
Dim fInfo As FileInfo = New FileInfo(strFilePath)
Dim objStream As StreamReader = fInfo.OpenText()
Dim strContents As String = objStream.ReadToEnd()
objStream.Close()

lblFileContents.Text = "Contents of " & fInfo.Name & ":" & _


"
" & vbCrLf & strContents & vbCrLf &
"
"
End Sub

C#

private void Page_Load(object sender, System.EventArgs e)


{
// Put user code to initialize the page here
if (Request["txtPath"]!= null)
{
string strDir = Request["txtPath"];
lblHeader.Text = "File Listing for " + strDir + "";
DirectoryInfo dirInfo =new DirectoryInfo(strDir);

// Get the files for the directory strDir


FileInfo[] fInfos = dirInfo.GetFiles("*.*");
DataList1.DataSource = fInfos;
DataList1.DataBind();
}
}

protected void SelectedIndexChanged(Object sender , System.EventArgs e )


{
string strFilePath = DataList1.DataKeys[(int)DataList1.SelectedItem.ItemIndex].ToString();
FileInfo fInfo = new FileInfo(strFilePath);
StreamReader objStream = fInfo.OpenText();
string strContents = objStream.ReadToEnd();
objStream.Close();
lblFileContents.Text = "Contents of " + fInfo.Name + ":" + "
" + "

" + strContents + "

" + "
";
}

7.11 How can I get a list of all the environment variables?

VB.NET

<asp:DataList id="DataList1" runat="server">


<HeaderTemplate>
<table>
</HeaderTemplate>
<ItemTemplate>
<tr>
<td>
<%# CType(Container.DataItem, DictionaryEntry).Key %>
</td>
<td>
<%# CType(Container.DataItem, DictionaryEntry).Value%>
</td>
</tr>
</ItemTemplate>
<FooterTemplate>
</table>
</FooterTemplate>
</asp:DataList>

Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load


'Put user code to initialize the page here
DataList1.DataSource = System.Environment.GetEnvironmentVariables()
DataList1.DataBind()
End Sub

C#

<asp:DataList id="DataList1" runat="server">


<HeaderTemplate>
<table>
</HeaderTemplate>
<ItemTemplate>
<tr>
<td>
<%# ((DictionaryEntry)Container.DataItem).Key %>
</td>
<td>
<%# ((DictionaryEntry)Container.DataItem).Value %>
</td>
</tr>
</ItemTemplate>
<FooterTemplate>
</table>
</FooterTemplate>
</asp:DataList>

private void Page_Load(object sender, System.EventArgs e)


{
// Put user code to initialize the page here
DataList1.DataSource = System.Environment.GetEnvironmentVariables();
DataList1.DataBind();
}

7.12 How to display checkbox in a DataList and highlight a row if the


value of checkbox is true?

<asp:datalist id="DataList1" OnItemDataBound ="ItemDB" runat="server">


<ItemTemplate >
<asp:CheckBox id="chkDiscontinued" Runat =server
checked=<%#Convert.ToBoolean(DataBinder.Eval(Container.DataItem , "Discontinued").ToString())%>>
</asp:CheckBox>
<asp:label ID="lblName" runat=server text=<%#DataBinder.Eval(Container.DataItem ,
"ProductName").ToString() %>></asp:label>
</ItemTemplate>
</asp:datalist>

VB.NET
'Populate the DataList in the Page_Load Event
Protected Sub ItemDB(ByVal sender As Object, ByVal e As
System.Web.UI.WebControls.DataListItemEventArgs)
If e.Item.ItemType = ListItemType.Item Or e.Item.ItemType = ListItemType.AlternatingItem Then
If CType(e.Item.FindControl("chkDiscontinued"), CheckBox).Checked Then
e.Item.BackColor = Color.CadetBlue
End If
End If
End Sub

C#

//Bind the DataList in the Page_Load Event


protected void ItemDB(object sender , System.Web.UI.WebControls.DataListItemEventArgs e )
{
if(( e.Item.ItemType == ListItemType.Item)||( e.Item.ItemType == ListItemType.AlternatingItem) )
{
if( ((CheckBox)(e.Item.FindControl("chkDiscontinued"))).Checked )
{
e.Item.BackColor = Color.CadetBlue;
}
}
}

7.13 How to display all System Colors in a DataList?

<asp:DataList id="DataList1" runat="server" >


<HeaderTemplate ><table></HeaderTemplate>
<ItemTemplate >
<tr>
<td bgcolor =<%#Container.DataItem%> runat=server id="td">
<%#Container.DataItem%>
</td>
</tr>
</ItemTemplate>
<FooterTemplate></table></FooterTemplate>
</asp:DataList>

VB.NET

Dim arrlist As New ArrayList


Dim enumColor As New KnownColor
Dim Colors As Array = [Enum].GetValues(enumColor.GetType())
Dim clr As Object
For Each clr In Colors
If Not Color.FromKnownColor(CType(clr, KnownColor)).IsSystemColor Then
arrlist.Add(clr.ToString())
End If
Next
DataList1.DataSource = arrlist
DataList1.DataBind()

C#

ArrayList arrlist = new ArrayList ();


KnownColor enumColor = new KnownColor();
Array Colors = Enum.GetValues(enumColor.GetType());
foreach(object clr in Colors)
{
if (!Color.FromKnownColor((KnownColor)clr).IsSystemColor)
arrlist.Add ( clr.ToString());
}
DataList1.DataSource = arrlist;
DataList1.DataBind();
8.1 How to display alphabetically sorted data in Repeater?

<asp:Repeater id="Repeater1" runat="server">


<ItemTemplate >
<b>
<u><p>
<%#GetFirstAlphabet(DataBinder.Eval(Container.DataItem, "LastName").ToString())%>
</p></u>
</b>
<%#DataBinder.Eval(Container.DataItem, "LastName").ToString()%>
,<%#DataBinder.Eval(Container.DataItem, "FirstName").ToString()%><br>
</ItemTemplate>
</asp:Repeater>

VB.NET

If Not Page.IsPostBack Then


'Populate the Data in the Repeater
End If

protected function GetFirstAlphabet(ByVal strval As String) As String


Dim alphabet As String = ViewState("alphabet")
If alphabet = Left(strval, 1) Then
Return ""
Else
alphabet = Left(strval, 1)
ViewState("alphabet") = alphabet
Return alphabet
End If
End Function

C#

if(!Page.IsPostBack)
{
//Populate the Data in the Repeater
}

protected string GetFirstAlphabet(string strval)


{
string alphabet =(string) ViewState["alphabet"];
if( alphabet == strval.Substring(0,1) )
{
return "";
}
else
{
alphabet = strval.Substring(0,1);
ViewState["alphabet"] = alphabet;
return alphabet;
}
}

8.2 How to display the Directory names in the Repeater Control?

Use namespace System.IO

<asp:Repeater id="Repeater1" runat="server">


<ItemTemplate >
<%# DataBinder.Eval(Container.DataItem, "Name").ToString() %>
</ItemTemplate>
</asp:Repeater>

VB.NET

Dim dir As New DirectoryInfo(Server.MapPath("."))


Repeater1.DataSource = dir.GetDirectories
Repeater1.DataBind()

C#

DirectoryInfo dir = new DirectoryInfo(Server.MapPath("."));


Repeater1.DataSource = dir.GetDirectories();
Repeater1.DataBind();

8.3 How to define HeaderTemplate and ItemTemplate to the Repeater at


runtime TBD?

VB.NET
Dim ds As DataSet
Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
ds = 'Assign proper value to dataset
Dim dc As DataColumn
Dim dr As DataRow
Dim rpthdr As New TemplateBuilder
Dim rptitem As New TemplateBuilder
Dim strval As String
For Each dc In ds.Tables(0).Columns
If strval = "" Then
strval = dc.ColumnName & " "
Else
strval = strval & dc.ColumnName & " "
End If
Next
rpthdr.AppendLiteralString(strval)
Repeater1.HeaderTemplate = rpthdr
Repeater1.DataSource = ds
Repeater1.DataBind()
End Sub

Function getData(ByVal objContainer As System.Web.UI.WebControls.RepeaterItem) As String


Dim i As Integer
Dim strval As String = "<br>"
For i = 0 To ds.Tables("table").Columns.Count - 1
If strval = "" Then
strval = objContainer.DataItem(i).ToString & " "
Else
strval &= objContainer.DataItem(i).ToString & " "
End If
Next
strval = strval & "<br>"
Return strval
End Function

C#

DataSet ds;
private void Page_Load(object sender, System.EventArgs e)
{
ds = something;
DataColumn dc;
DataRow dr;
TemplateBuilder rpthdr = new TemplateBuilder();
TemplateBuilder rptitem = new TemplateBuilder();
string strval;
foreach (int dc in ds.Tables(0).Columns)
{
if (strval == "")
{
strval = dc.ColumnName + " ";
}
else
{
strval = strval + dc.ColumnName + " ";
}
}
rpthdr.AppendLiteralString(strval);
Repeater1.HeaderTemplate = rpthdr;
Repeater1.DataSource = ds;
Repeater1.DataBind();
}

string getData(System.Web.UI.WebControls.RepeaterItem objContainer)


{
int i;
string strval = "<br>";
for (int i = 0; i <= ds.Tables("table").Columns.Count - 1; i++)
{
if (strval == "")
{
strval = objContainer.DataItem(i).ToString + " ";
}
else
{
strval += objContainer.DataItem(i).ToString + " ";
}
}
strval = strval + "<br>";
return strval;
}

8.4 How to add a TemplateColumn dynamically to Repeater?

Refer : How to add Templatecolumn dynamically to DataList?

Now, instead of DataList use Repeater and make below changes

VB.NET

Public Sub BindLabelColumn(sender As Object, e As EventArgs)


Dim lbl As Label = CType(sender, Label)
Dim container As RepeaterItem = CType(lbl.NamingContainer, RepeaterItem)
Dim strVals As String = Convert.ToString(DataBinder.Eval(CType(container, RepeaterItem).DataItem,
"LastName")) + ", " + Convert.ToString(DataBinder.Eval(CType(container, RepeaterItem).DataItem,
"FirstName"))
lbl.Text = strVals
End Sub 'BindLabelColumn

C#

public void BindLabelColumn(object sender, EventArgs e)


{
Label lbl = (Label)sender;
RepeaterItem container = (RepeaterItem)lbl.NamingContainer ;
String strVals =Convert.ToString(DataBinder.Eval(((RepeaterItem)container).DataItem, "LastName"))
+ ", " +
Convert.ToString(DataBinder.Eval(((RepeaterItem)container).DataItem, "FirstName")) ;
lbl.Text = strVals;

8.5 How to implement sorting using Repeater?

<asp:Repeater ID="Repeater1" Runat="server" EnableViewState="False">


<ItemTemplate>
<table width="100%" cellspacing="0" cellpadding="0">
<tr>
<td width=25%><%# DataBinder.Eval(Container.DataItem, "Employeeid") %></td>
<td width=25% ><%# DataBinder.Eval(Container.DataItem, "FirstName") %></td>
<td width=25% ><%# DataBinder.Eval(Container.DataItem, "LastName") %></td>
<td width=25% ><%# DataBinder.Eval(Container.DataItem, "Title") %></td>
</tr>
</table>
</ItemTemplate>
<HeaderTemplate>
<table width="100%" cellspacing="0" cellpadding="0">
<tr>
<td width=25%>
<asp:LinkButton ID="lnkEmployeeid" Runat="server"
OnClick="SortEmployeeIdClick">Employeeid</asp:LinkButton>
</td>
<td width=25%>
<asp:LinkButton ID="lnkFirstName" Runat="server"
OnClick="SortFirstNameClick">FirstName</asp:LinkButton>
</td>
<td width=25%>
<asp:LinkButton ID="lnkLastName" Runat="server"
OnClick="SortLastNameClick">LastName</asp:LinkButton>
</td>
<td width=25% >
<asp:LinkButton ID="lnkTitle" Runat="server" OnClick="SortTitleClick">Title</asp:LinkButton>
</td>
</tr>
</table>
</HeaderTemplate>
</asp:Repeater>

VB.NET

Dim SortField As String


Dim myconnection As SqlConnection
Dim myda As SqlDataAdapter
Dim ds As DataSet
Dim strConn As String
Dim SQLStmt As String = "Select * from Employees "

Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load


' Put user code to initialize the page here
BindData()
End Sub 'Page_Load

Sub BindData()
strConn="Server=localhost;uid=sa;password=;database=northwind;"
myconnection = New SqlConnection(strConn)
myda = New SqlDataAdapter(SQLStmt, myconnection)
ds = New DataSet
myda.Fill(ds, "AllTables")
Repeater1.DataSource = ds
Repeater1.DataBind()
End Sub 'BindData

Sub SortData(ByVal SortExpression As String)


If ViewState("SortOrder") Is Nothing Then
ViewState("SortOrder") = " ASC"
Else
If ViewState("SortOrder").ToString() = " ASC" Then
ViewState("SortOrder") = " DESC"
Else
ViewState("SortOrder") = " ASC"
End If
End If
SQLStmt = SQLStmt + " ORDER BY " + SortExpression.ToString() + " " + ViewState("SortOrder")
BindData()
End Sub 'SortData

Protected Sub SortEmployeeIdClick(ByVal sender As Object, ByVal e As EventArgs)


SortField = "EmployeeId"
SortData(SortField)
End Sub 'SortEmployeeIdClick

Protected Sub SortFirstNameClick(ByVal sender As Object, ByVal e As EventArgs)


SortField = "FirstName"
SortData(SortField)
End Sub 'SortFirstNameClick

Protected Sub SortLastNameClick(ByVal sender As Object, ByVal e As EventArgs)


SortField = "LastName"
SortData(SortField)
End Sub 'SortLastNameClick

Protected Sub SortTitleClick(ByVal sender As Object, ByVal e As EventArgs)


SortField = "Title"
SortData(SortField)
End Sub 'SortTitleClick

C#

string SortField;
SqlConnection myconnection ;
SqlDataAdapter myda ;
DataSet ds ;
String strConn ;
string SQLStmt= "Select * from Employees ";

private void Page_Load(object sender, System.EventArgs e)


{
// Put user code to initialize the page here
BindData();
}

void BindData()
{
strConn="Server=localhost;uid=sa;password=;database=northwind;";
myconnection =new SqlConnection(strConn);
myda = new SqlDataAdapter(SQLStmt, myconnection);
ds = new DataSet();
myda.Fill(ds, "AllTables");
Repeater1.DataSource = ds;
Repeater1.DataBind();
}

void SortData(string SortExpression)


{
if (ViewState["SortOrder"] ==null)
{
ViewState["SortOrder"] = " ASC";
}
else if (ViewState["SortOrder"].ToString () == " ASC" )
{
ViewState["SortOrder"] = " DESC";
}
else
{
ViewState["SortOrder"] = " ASC";
}
SQLStmt = SQLStmt + " ORDER BY " + SortExpression.ToString () + " " + ViewState["SortOrder"];
BindData();
}

protected void SortEmployeeIdClick(object sender ,EventArgs e )


{
SortField = "EmployeeId";
SortData (SortField);
}

protected void SortFirstNameClick(object sender ,EventArgs e )


{
SortField = "FirstName";
SortData (SortField);
}

protected void SortLastNameClick(object sender ,EventArgs e )


{
SortField = "LastName";
SortData (SortField);
}

protected void SortTitleClick(object sender ,EventArgs e )


{
SortField = "Title";
SortData (SortField);
}

8.6 Can I specify ItemStyle to a Repeater Control?


The Repeater class is not derived from the WebControl class, like the DataGrid and DataList. Therefore, the

Repeater lacks the stylistic properties common to both the DataGrid and DataList. What this boils down to is

that if you want to format the data displayed in the Repeater, you must do so in the HTML markup. i.e using

<b>/<u>.. tags

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

<asp:Repeater ID="Repeater1" Runat="server" EnableViewState="False">


<HeaderTemplate>
<table>
</HeaderTemplate>
<ItemTemplate>
<tr <%# FormatColorRow(DataBinder.Eval(Container.DataItem,"UnitPrice").ToString()) %> >
<td >
<%# DataBinder.Eval(Container.DataItem,"UnitPrice").ToString() %>
</td>
</ItemTemplate>
<FooterTemplate>
</table>
</FooterTemplate>
</asp:Repeater>

VB.NET

Protected Function FormatColorRow(strUnitPrice As String) As String


Dim unitprice As Double = Double.Parse(strUnitPrice)
If unitprice <= 15 Then
Return "style='backGround-color:red'"
Else
Return "style='backGround-color:green'"
End If
End Function 'FormatColorRow

C#

protected string FormatColorRow(string strUnitPrice)


{
double unitprice =double.Parse ( strUnitPrice);
if ( unitprice <= 15)
{
return "style='backGround-color:red'";
}
else
{
return "style='backGround-color:green'";
}
}
9.1 What is the difference between authentication and authorization?

Authentication is the process of identifying and verifying who the client accessing the server is.

For example, if you use

• Windows authentication and are browsing an ASP.NET page from server -- ASP.NET/IIS would

automatically use NTLM to authenticate you as SYNCFUSION\user1 (for example).

• Forms based authentication, then you would use an html based forms page to enter

username/password -- which would then check a database and authenticate you against the

username/password in the database.

Authorization is the process of determining whether an authenticated user has access to run a particular page
within an ASP.NET web application. Specifically, as an application author decide to grant or deny the
authenticated user "SYNCFUSION\user1" access to the admin.aspx page. This could be done either by
explictly granting/denying rights based on the username -- or use role based mappings to map authenticated
users into roles (for example: an administrator might map "SYNCFUSION\user1" into the "Power Users" role)
and then grant/deny access based on role names (allowing a degree of abstraction to separate out your
authorization policy).

9.2 How to implement authentication via web.config?

Include the <authorization> element.

<authorization>
<deny users="?"/>
</authorization>

9.3 How to run a Web application using the permission of an


authenticated user?

Use the <identity> element in the web.config

<identity impersonate="true"/>

9.4 Which are the different ASP.NET authentication modes?


ASP.NET supports the following Authentication Providers

• Windows : Is used in conjunction with IIS authentication. Authentication is performed by IIS in one

of three ways: basic, digest, or Integrated Windows Authentication. When IIS authentication is

complete, ASP.NET uses the authenticated identity to authorize access

• Forms : The user provides credentials and submits the form.

• Passport : Centralized authentication service provided by Microsoft that offers a single logon and core

profile services for member sites.

• None : No Authentication provided. This is default Authentication mode

In the web.config file, you can specify this setting:

<authentication
mode= " [ Windows | Forms | Passport | None ] ">
</authentication>

9.5 How to determine the Windows User from a Web form Application?

Use the System.Security.Principal namespace.

VB.NET

dim wp as WindowsPrincipal = new WindowsPrincipal(WindowsIdentity.GetCurrent())


Response.Write(wp.Identity.Name)

C#

WindowsPrincipal wp = new WindowsPrincipal(WindowsIdentity.GetCurrent());


Response.Write(wp.Identity.Name);

9.6 After installing SP4 none of my ASP.NET pages developed using


Framework 1.0 are showing the errors related to security?
To resolve this issue, identify the user account that is used to run the program, and then assign the

"Impersonate a client after authentication" user right to that user account. To do this, follow these steps:

1. Click Start, point to Programs, point to Administrative Tools, and then click Local Security Policy.

2. Expand Local Policies, and then click User Rights Assignment.

3. In the right pane, double-click Impersonate a client after authentication.

4. In the Local Security Policy Setting dialog box, click Add.

5. In the Select Users or Group dialog box, click the user account that you want to add, click Add, and

then click OK.

6. Click OK.

10.1 How to assign a text to Checkbox control and know which checkbox
is selected?

<asp:CheckBox id="chkTips" style="Z-INDEX: 101; LEFT: 32px; POSITION: absolute; TOP: 64px"
runat="server"
Text="Tips"></asp:CheckBox>
<asp:CheckBox id="chkTricks" style="Z-INDEX: 102; LEFT: 32px; POSITION: absolute; TOP: 112px"
runat="server" Text="Tricks"></asp:CheckBox>
<asp:CheckBox id="chkFaqs" style="Z-INDEX: 103; LEFT: 32px; POSITION: absolute; TOP: 160px"
runat="server"
Text="Faqs"></asp:CheckBox>
<asp:Button id="btnSelect" style="Z-INDEX: 104; LEFT: 40px; POSITION: absolute; TOP: 224px"
runat="server" Text="Select"></asp:Button>

VB.NET

Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load


'Put user code to initialize the page here
If Not Page.IsPostBack Then
End If
End Sub

Private Sub btnSelect_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles


btnSelect.Click
Dim ctl As Control
Dim strchkSelected As String
For Each ctl In Page.Controls(1).Controls
If TypeOf ctl Is CheckBox Then
if CType(ctl, CheckBox).Checked Then
strchkSelected += CType(ctl, CheckBox).Text + " "
End If
End If
Next
Response.Write(strchkSelected)
End Sub

C#

private void Page_Load(object sender, System.EventArgs e)


{
// Put user code to initialize the page here
if (!Page.IsPostBack )
{
}
}

private void btnSelect_Click(object sender, System.EventArgs e)


{
string strchkSelected="" ;
foreach (Control ctl in Page.Controls[1].Controls )
{
CheckBox chk = ctl as CheckBox ;
if (chk!=null)
{
if (chk.Checked )
{
strchkSelected += chk.Text + " " ;
}
}
}
Response.Write (strchkSelected);
}

10.2 How to validate a CheckBox?

<asp:CheckBox runat="server" id="chkbox"></asp:CheckBox>


<asp:CustomValidator runat="server" ErrorMessage="Error!" OnServerValidate="ServerValidation"
ClientValidationFunction="ClientValidation"
ID="Customvalidator1" />
<asp:Button runat="server" text="submit" ID="Button1" />

<script language="javascript">
function ClientValidation(source, args)
{
args.IsValid = document.all["chkbox"].checked;
}
</script>

VB.NET

<script runat="server" language="vb">


sub ServerValidation( source as object, args as ServerValidateEventArgs )
args.IsValid = chkbox.Checked
end sub
</script>
C#

<script runat="server" language="cs">


void ServerValidation(object source, ServerValidateEventArgs args)
{
args.IsValid = chkbox.Checked;
}
</script>
11.1 How to emit client-side javascript blocks from VB.NET/C#?

The RegisterStartupScript method emits the script just before the closing tag of the Page object's <form

runat= server> element.

VB.NET

RegisterStartupScript("Sample", "<SCRIPT Language='javascript'>alert('Hello World');</SCRIPT>")

C#

RegisterStartupScript("Sample", "<SCRIPT Language='javascript'>alert('Hello World');</SCRIPT>");

Alternatively, use the RegisterClientScriptBlock method which emits the client-side script just after the

opening tag of the Page object's <form runat= server> element.

11.2 How to open a new Window using javascript function from a Link
button?

VB.NET

link.Attributes( "onClick" ) = "window.open( 'url', 'name', 'properties' )";

C#

link.Attributes[ "onClick" ] = "window.open( 'url', 'name', 'properties' )";

You can also check out Andy Smith's RemoteWindow Control


11.3 Is there a JavaScript Quick Reference Guide?

Here is a JavaScript Quick Reference Guide in Poster Format that you can print out and refer easily. Covers

the older and newer version of DOM and IE and Mozilla.

Danny Goodman's JavaScript and Browser Objects Quick Reference

11.4 How to set the background color of a web page using code behind?

Yes

1. In the body tag, add runat="server" and give the tag an id (e.g. id="bodyID").

2. In the class definition in the code-behind, add VB.NET

Protected bodyID As System.Web.UI.HtmlControls.HtmlGenericControl

C#

protected System.Web.UI.HtmlControls.HtmlGenericControl bodyID ;

In code, use the attributes collection to set the bgcolor attribute: VB.NET

bodyID.Attributes.Add("bgcolor", "green")

C#

bodyID.Attributes.Add("bgcolor", "green");

11.5 How to resolve error message "String constants must end with a
double quote."?

To resolve this check out PRB: The Tag Is Treated As a Closing Tag When Inside a Quoted String
11.6 Why can't I open a new browser window from within server code?

Server code executes on Server, whereas the new window is created on the client. You need to use client-side

script to open new window.

11.7 How to get the confirmation of Yes/No from a javascript pop-up and
display the value on the page?

Code Behind

Button1.Attributes.Add("onclick", "getMessage()")

Client Side

<SCRIPT language=javascript>
function getMessage()
{
var ans;
ans=window.confirm('Is it your confirmation.....?');

if (ans==true)
{
document.Form1.hdnbox.value='Yes';
}
else
{
document.Form1.hdnbox.value='No';}
}
</SCRIPT>

To display the Yes/No value selected by user, in your code behind file:

Response.Write(Request.Form("hdnbox"))

11.8 How to open a browser window with maximum size on click of a


button?

VB.NET

Button1.Attributes.Add("onclick", "window.open('page2.aspx','','fullscreen=yes')")
C#

Button1.Attributes.Add("onclick", "window.open('page2.aspx','','fullscreen=yes')");

11.9 How can I know if the client browser supports active scripting?

You can detect and interept the capabilities of your client using the namespace

System.Web.HttpBrowserCapabilities :

VB.NET

Dim browser As System.Web.HttpBrowserCapabilities = Request.Browser


Response.Write("Support ActiveXControl: " + browser.ActiveXControls.ToString())

C#

System.Web.HttpBrowserCapabilities browser = Request.Browser;


Response.Write ("Support ActiveXControl: " + browser.ActiveXControls.ToString ());

For more details Refer: Detecting Browser Types in Web Forms

11.10 How to determine if the Browser supports javascript?

VB.NET

if Page.Request.Browser.JavaScript then
...
else
...
end if

C#

if (Page.Request.Browser.JavaScript )
{
...
}
else
{
...
}

11.11 How can I change the scroll bar color?

Use Style Sheet to change the color of scroll-bar

body
{
FONT-SIZE: 8pt;
COLOR: #000000;
background-color: #EEEEEE;
scrollbar-face-color: #EEEE99;
scrollbar-highlight-color: #DDDDDD;
scrollbar-shadow-color: #DEE3E7;
scrollbar-3dlight-color: #FF6600;
scrollbar-arrow-color: #006699;
scrollbar-track-color: #EFEFEF;
scrollbar-darkshadow-color: #98AAB1;
}

11.12 How to create dynamic javascripts in server side code based on


server side variables?

Here's and example:

VB.NET

Dim value As String = "pic1.jpg"


Button1.Attributes("onMouseOver") = "alert( '" + value + "');"

C#

string value = "pic1.jpg";


Button1.Attributes["onMouseOver"] = "alert( \"" + value + "\");" ;

11.13 How can I use a Timer Control to refresh a page automatically at a


specified interval?

<asp:DropDownList id="DropDownList1" runat="server" onChange="SetClientRefresh(this);">


<asp:ListItem Value="1000">1 second</asp:ListItem>
<asp:ListItem Value="2000">2 seconds</asp:ListItem>
<asp:ListItem Value="3000">3 seconds</asp:ListItem>
</asp:DropDownList>

<script language='javascript'>
var cTimeOut = null;
function SetClientRefresh(sel)
{
var newRefresh = sel.options[sel.selectedIndex].value;
if (cTimeOut != null)
{
window.clearTimeout(cTimeOut);
}
cTimeOut = window.setTimeout("ReLoadPage()", newRefresh);
}

function ReLoadPage()
{
window.location.reload();
}
</script>

11.14 How to open a new window without IE menus and toolbars on click
of a button?

VB.NET

Button2 .Attributes.Add ("onclick", "window.open('webform1.aspx','_blank','toolbar=no')")

C#

Button2 .Attributes.Add ("onclick", "window.open('webform1.aspx','_blank','toolbar=no')");

11.15 Does JavaScript support hashtables/ hash tables or dictionary type


data structures?

All Objects in JavaScript implicitly support hash table like syntax by virtue of behaving as Associative Arrays.

Properties of an object can be accessed in 2 ways as shown below:

object.property = value;
object["property"] = value;
So, when used in a hash table like syntax as shown above, you will be simply creating dynamic properties

and assigning values to those properties.

11.16 How to disable the right click option on a web page?

<body oncontextmenu="return false;">


...
</body>

Note :User can still do a View/Source in their browser menu.

11.17 How to hide a control using javascript?

document.getElementById("<id>").style.visibility="hidden";

11.18 Can I modify WebUIValidation.js?

Extract from MSDN :

You are encouraged to read the script to see more of what is going on. However, it is not recommended that
you modify these scripts, because their function is very closely tied to a particular version of the run time. If
the run time is updated, the scripts may need a corresponding update, and you will have to either lose your
changes or face problems with the scripts not working. If you must change the scripts for a particular project,
take a copy of the files and point your project to them by overriding the location of the files with a private
web.config file.It is perfectly fine to change this location to be a relative or absolute reference.

For more details refer ASP.NET Validation in Depth

11.19 How to change a Label element's text in javascript?

document.getElementById("Label1").innerText = "Changed Text";

11.20 How to resize two <div> tags on a webform?


<script>
function ResizeDivs()
{
var DivTop = document.getElementById('Top')
var DivBottom = document.getElementById('Bottom')
var BodyHeight = 0;

var DivTopHeight = 0;
var DivBottomHeight = 0;
var DivBottomPosition = 0;

BodyHeight = document.body.clientHeight;
DivBottomHeight = DivBottom.clientHeight;
DivBottom.style.top = BodyHeight - DivBottomHeight;
DivTop.style.height = DivBottom.style.top;

window.onload = ResizeDivs;
window.onresize = ResizeDivs;</script>

<div id="Top" style="position:absolute; top:0px; left:0px; background-color:#c0c0c0; overflow:auto;


width:100%">
Top Div Text:
<br>Syncfusion
<br>Sample code
<br>To
<br>autosize
<br><div>
<br>tag

</div>
<div id="Bottom" style="position:absolute; background-color:#808080; width:100%">
Bottom Div Text:
<br> Footer for the page
<br> Line1
<br> Line2
</div>

Note : if the DIV has no borders, clientHeight works. If you are going to be using a border or margins, then

use offsetHeight

11.21 How to check/ uncheck a checkbox based on the text entered in


textbox?

<asp:CheckBox id="CheckBox1" runat="server"></asp:CheckBox>


<asp:TextBox id="TextBox1" runat="server"></asp:TextBox>
<script type="text/javascript">
function chkTextEntered()
{
document.getElementById("CheckBox1").checked = true;
if(document.getElementById("TextBox1").value =="" )
{
document.getElementById("CheckBox1").checked = false;
}
}
</script>

In Page_Load

VB.NET

TextBox1.Attributes.Add("onKeyDown", "chkTextEntered();")

C#

TextBox1.Attributes.Add("onKeyDown", "chkTextEntered();");

11.22 How to rotate a Label Text?

<asp:Label id="Label1" style="writing-mode:tb-rl" runat="server">Label</asp:Label>

11.23 How to display a message in the status bar of a browser window?

<body onload ="window.status='First Page'">


..
</body>

11.24 How to change the BackGroundColor of a page based on the value


selected in a DropdownList?

<asp:DropDownList id="DropDownList1" runat="server" AutoPostBack="True">


<asp:ListItem Value="Red">Red</asp:ListItem>
<asp:ListItem Value="Blue">Blue</asp:ListItem>
<asp:ListItem Value="Green">Green</asp:ListItem>
</asp:DropDownList>

VB.NET

Page.RegisterClientScriptBlock("BodyStyle", "<style type='text/css'>body{background-color: " +


DropDownList1.SelectedItem.Value + ";}</style>")

C#

Page.RegisterClientScriptBlock("BodyStyle", "<style type='text/css'>body{background-color: " +


DropDownList1.SelectedItem.Value + ";}</style>");

11.25 How to disable a Dropdownlist once someone has selected an item


in the Dropdownlist?

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


<asp:ListItem Value="Red">Red</asp:ListItem>
<asp:ListItem Value="Blue">Blue</asp:ListItem>
<asp:ListItem Value="Green">Green</asp:ListItem>
</asp:DropDownList>

VB.NET

DropDownList1.Attributes.Add("onChange","this.disabled=true;" )

C#

DropDownList1.Attributes.Add("onChange","this.disabled=true;" );

11.26 How can I make a Textbox a mandatory field if a checkbox is


checked on a button click event in the client side?

<asp:TextBox id="TextBox1" style="Z-INDEX: 101; LEFT: 32px; POSITION: absolute; TOP: 104px"
runat="server">
<asp:CheckBox id="CheckBox1" style="Z-INDEX: 102; LEFT: 24px; POSITION: absolute; TOP: 80px"
runat="server">
<asp:Button id="Button1" style="Z-INDEX: 103; LEFT: 32px; POSITION: absolute; TOP: 144px"
runat="server" Text="Button">

<script>
function func1()
{
if(document.getElementById ("CheckBox1").checked==true)
{
if(document.getElementById("TextBox1").value=="")
{
alert("Enter something in textbox");
}
}

}
</script>

VB.NET

Button1.Attributes.Add ("onclick" , "return func1()");

C#

Button1.Attributes.Add ("onclick" , "return func1()");

11.27 Why does the SmartNavigation does not work on the live server
but works perfectly on the Development Machine?

May be the domain does not have access to the aspnet_client folder which is located in the wwwroot folder.

i.e the website is not able to find the scripts for smart navigation. So set up a virtual folder to the

wwwroot/aspnet_client and it will fix the problem.

11.28 How to pop up a message box when no item in the dropdownlist is


selected before postback?

• Make sure to add a ListItem with Text="Please Choose" and Value ="".

• Add a RequiredFieldValidator with ControlToValidate= <Dropdownlist1> and Display="None"


• Add a ValidationSummary with ShowMessageBox =true

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


<asp:ListItem Value="">Please Choose</asp:ListItem>
<asp:ListItem Value="Faq">Faq</asp:ListItem>
<asp:ListItem Value="Tips">Tips</asp:ListItem>
<asp:ListItem Value="Tricks">Tricks</asp:ListItem>
</asp:DropDownList>
<asp:RequiredFieldValidator id="RequiredFieldValidator1" style="Z-INDEX: 102; LEFT: 176px; POSITION:
absolute; TOP: 48px"
runat="server" ErrorMessage="Please Select an Item in the dropdownlist"
ControlToValidate="DropDownList1"
Display="None"></asp:RequiredFieldValidator>
<asp:Button id="Button1" style="Z-INDEX: 104; LEFT: 128px; POSITION: absolute; TOP: 16px"
runat="server"
Text="Button"></asp:Button>
<asp:ValidationSummary id="ValidationSummary1" style="Z-INDEX: 105; LEFT: 176px; POSITION:
absolute; TOP: 72px"
runat="server" ShowMessageBox="True" ShowSummary="False"></asp:ValidationSummary>

11.29 Are there any resources regarding the Mozilla specific Browser
Objects and CSS information?

Official Gecko DOM Reference:

Gecko Dom Reference

Here is a very useful list of custom CSS styles specific to Mozilla:

12.1 How to write the data from database into an XML file?

VB.NET

'Fill the DataSet


ds.WriteXml(Server.MapPath ("products.xml" ) )

C#

//Fill the DataSet


ds.WriteXml(Server.MapPath ("products.xml" ) );

Note : Make sure you have write and modify rights.

12.2 How to read data from an XML file and display it in a DataGrid?
VB.NET

dim ds as new DataSet()


ds.ReadXml (Server.MapPath ("products.xml"))
DataGrid1.DataSource =ds
DataGrid1.DataBind()

C#

DataSet ds= new DataSet ();


ds.ReadXml (Server.MapPath ("products.xml"));
DataGrid1.DataSource =ds;
DataGrid1.DataBind();

12.3 How to read data from the XML file using FileStream and display it
in a DataGrid?

Use namespace System.IO

VB.NET

dim ds as new DataSet()


dim fs as FileStream = new FileStream (Server.MapPath ("products.xml"),FileMode.Open , FileAccess.Read )
ds.ReadXml (fs)
DataGrid1.DataSource = ds
DataGrid1.DataBind ()

C#

DataSet ds= new DataSet ();


FileStream fs = new FileStream (Server.MapPath ("products.xml"),FileMode.Open , FileAccess.Read );
ds.ReadXml (fs);
DataGrid1.DataSource = ds;
DataGrid1.DataBind ();

12.4 How to save an xml-string into an Xml document?

VB.NET

Dim xmlText As String = "<?xml version=""1.0""?> Node1 Node2 "


Dim xmlDoc As New XmlDocument
xmlDoc.LoadXml(xmlText)
Dim writer As XmlTextWriter = New XmlTextWriter(Server.MapPath("data.xml"), Nothing)
writer.Formatting = Formatting.Indented
xmlDoc.Save(writer)

C#
string xmlText = "<?xml version=\"1.0\"?> Node1 Node2 ";
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(xmlText);
XmlTextWriter writer = new XmlTextWriter(Server.MapPath("data.xml"),null);
writer.Formatting = Formatting.Indented;
xmlDoc.Save(writer);

12.5 How to use the <asp:xml> tag?

<asp:Xml id="Xml1" DocumentSource="products.xml" runat="server"></asp:Xml>

12.6 How to display the Attribute values in an XML Document in a


DataGrid?

products.xml

<?xml version="1.0" standalone="yes"?>


<NewDataSet>
<Product>
<ProductID pcode="P2">2</ProductID>
<ProductName>Chang</ProductName>
<SupplierID>1</SupplierID>
<CategoryID>1</CategoryID>
<QuantityPerUnit>24 - 12 oz bottles</QuantityPerUnit>
</Product>
<Product>
<ProductID pcode="P4">3</ProductID>
<ProductName>Aniseed Syrup</ProductName>
<SupplierID>1</SupplierID>
<CategoryID>2</CategoryID>
<QuantityPerUnit>12 - 550 ml bottles</QuantityPerUnit>
</Product>
</NewDataSet>

Use Namespace System.Xml

VB.NET

<asp:DataGrid id="DataGrid1" AutoGenerateColumns="False" runat="server">


<Columns>
<asp:TemplateColumn HeaderText="ProductCode">
<ItemTemplate>
<%#CType(Container.DataItem, System.Xml.XmlNode).Attributes("pcode").value%>
</ItemTemplate>
</asp:TemplateColumn>
</Columns>
</asp:DataGrid>

dim xmldoc as XmlDocument = new XmlDocument()


xmldoc.Load(Server.MapPath("products.xml"))
dim xmlnodes as XmlNodeList = xmldoc.SelectNodes("NewDataSet/Product/ProductID")
DataGrid1.DataSource = xmlnodes
DataGrid1.DataBind ()

C#

<asp:DataGrid id="DataGrid1" AutoGenerateColumns="False" runat="server">


<Columns>
<asp:TemplateColumn HeaderText ="ProductCode">
<ItemTemplate>
<%# ((System.Xml.XmlNode)Container.DataItem).Attributes["pcode"].Value %>
</ItemTemplate>
</asp:TemplateColumn>
</Columns>
</asp:DataGrid>

XmlDocument xmldoc = new XmlDocument();


xmldoc.Load(Server.MapPath("products.xml"));
XmlNodeList xmlnodes = xmldoc.SelectNodes("NewDataSet/Product/ProductID");
DataGrid1.DataSource = xmlnodes;
DataGrid1.DataBind ();
13.1 How to retrieve the multiple selected items in a CheckBoxList?

<asp:CheckBoxList id="CheckBoxList1" runat="server">


<asp:ListItem Value="Faq">Faq</asp:ListItem>
<asp:ListItem Value="Tips">Tips</asp:ListItem>
<asp:ListItem Value="Tricks">Tricks</asp:ListItem>
</asp:CheckBoxList>
<asp:Button id="btnShow" style="Z-INDEX: 101; LEFT: 40px; POSITION: absolute; TOP: 136px"
runat="server"
Text="Show"></asp:Button>

VB.NET

Private Sub btnShow_Click(sender As Object, e As System.EventArgs)


Dim strchklist As String = ""
Dim li As ListItem
For Each li In CheckBoxList1.Items
If li.Selected Then
strchklist += li.Text + " "
End If
Next
If strchklist = "" Then
Response.Write("No item Selected")
Else
Response.Write(("You selected : " + strchklist))
End If
End Sub 'btnShow_Click
C#

private void btnShow_Click(object sender, System.EventArgs e)


{
string strchklist="";
foreach (ListItem li in CheckBoxList1.Items )
{
if (li.Selected )
{
strchklist += li.Text + " " ;
}
}
if (strchklist =="")
{
Response.Write ("No item Selected");
}
else
{
Response.Write ("You selected : " + strchklist);
}
}

13.2 How to check if nothing is selected in a CheckBoxList without using


a loop to parse through all the items?

You can check if CheckBoxList.SelectedIndex equals to -1 which means nothing is selected.

15.1 What is the best way to rename a file on the webserver in code?

Use namespace System.IO

VB.NET

File.Move("C:\Dir1\SomeFile.txt", "C:\Dir1\RenamedFileName.txt")

C#

File.Move(@"C:\Dir1\SomeFile.txt", @"C:\Dir1\RenamedFileName.txt")

Refer

• Rename Function

• FileInfo.MoveTo Method

Note: In a Web application, the code is running in the context of the machine\ASPNET account, which has
limited privileges. If the error you are getting pertains to permissions, you might need to grant to the
machine\ASPNET account the rights to create and delete files in the directory where you're working. Note
that this could be a security issue.

15.2 How to create a folder in ASP.NET?

Use System.IO namespace

VB.NET

Dim path As String = ""


try
' Determine whether the directory exists.
If Directory.Exists(path) Then
Response.Write("That path exists already.")
Return
End If
' Try to create the directory.
Dim di As DirectoryInfo = Directory.CreateDirectory(path)
Response.Write(("Directory create successfully at " + Directory.GetCreationTime(path)))
catch ex as Exception
Response.Write (ex.Message )
end try

C#

string path = @"c:\MyDir";


try
{
// Determine whether the directory exists.
if (Directory.Exists(path))
{
Response.Write ("That path exists already.");
return;
}
// Try to create the directory.
DirectoryInfo di = Directory.CreateDirectory(path);
Response.Write("Directory create successfully at " + Directory.GetCreationTime(path));
}
catch(Exception ex)
{
Response.Write (ex.Message );
}

15.3 How to show the ASP.NET code to the users?

Use namespace
• System.IO

• System.Text

VB.NET

Protected Function GetCode(filename As String) As String


Dim sr As New StreamReader(filename)
Dim sb As New StringBuilder()
sb.Append("<code><pre>")
sb.Append(sr.ReadToEnd())
sb.Append("</pre></code>")
sr.Close()
Return sb.ToString()
sb = Nothing
sr = Nothing
End Function 'GetCode

Private Sub Button1_Click(sender As Object, e As System.EventArgs)


Response.Write(GetCode((Server.MapPath("WebForm1.aspx") + ".vb")))
End Sub 'Button1_Click

C#

protected string GetCode(string filename)


{
StreamReader sr =new StreamReader(filename );
StringBuilder sb =new StringBuilder();
sb.Append("<code><pre>");
sb.Append(sr.ReadToEnd());
sb.Append("</pre></code>");
sr.Close();
return sb.ToString();
sb = null;
sr = null;
}
private void Button1_Click(object sender, System.EventArgs e)
{
Response.Write (GetCode(Server.MapPath ("WebForm1.aspx") + ".cs"));
}

15.4 How to read a html file in ASP.NET?

Use namespace System.IO

VB.NET
Dim file As String = Server.MapPath("temp.html")
Dim sr As StreamReader
Dim fi As New FileInfo(file)
Dim input As String = "<pre>"
If File.Exists(file) Then
sr = File.OpenText(file)
input += Server.HtmlEncode(sr.ReadToEnd())
sr.Close()
End If
input += "</pre>"
Me.Label1.Text = input

C#

string file = Server.MapPath ("temp.html");


StreamReader sr;
FileInfo fi = new FileInfo(file);
string input = "<pre>";
if(File.Exists(file))
{
sr = File.OpenText(file);
input += Server.HtmlEncode(sr.ReadToEnd());
sr.Close();
}
input += "</pre>";
this.Label1.Text = input;

15.5 How can I to get the path to the system area that holds temporary
files?

Use System.IO namespace

VB.NET

Dim filePath As String = Path.GetTempPath()


Dim fileName As String = Path.GetTempFileName()
Response.Write((filePath + "
"))
Response.Write(fileName)

C#

string filePath =Path.GetTempPath ();


string fileName = Path.GetTempFileName();
Response.Write (filePath + "
" );
Response.Write (fileName );
15.6 How to save a file in the client machine?

The browser will not allow you to save a file directly to a client machine. You could however do a

Response.Redirect("http://server/filename"); which would send the file back to the browser, at which point

the user would be prompted to save / open the file.

15.7 How to get the physical path of a file?

Use Request.Path

15.8 How to get the current filename?

VB.NET

Response.Write (Path.GetFileName(Request.PhysicalPath))

C#

Response.Write (Path.GetFileName(Request.PhysicalPath));

15.9 How to Upload files in ASP.NET?

Take a look at following articles

• VB.NET code

• C# Code

15.10 How to delete a file from the server?

VB.NET

System.IO.File.Delete(Server.MapPath("wnew.txt"))
C#

System.IO.File.Delete(Server.MapPath("wnew.txt"))

Make sure that you have permissions to delete a file.

15.11 How to find the date and time the specified file or directory was
last written to?

Use namespace System.IO

VB.NET

dim path as string = Server.MapPath("page1.aspx")


Response.Write ( File.GetLastWriteTime(path))

C#

string path =Server.MapPath("page1.aspx");


Response.Write ( File.GetLastWriteTime(path));

15.12 How to get the File information using ASP.NET?

Use the namepsace System.IO

VB.NET

Dim fPath As String = Server.MapPath("orders.xml")


Dim fInfo As New FileInfo(fPath)
Dim strFileInfo As String
If fInfo.Exists Then
strFileInfo = "Name: " + fInfo.Name + "<br />"
strFileInfo += "Location: " + fInfo.FullName + "<br />"
strFileInfo += "Created on: " + fInfo.CreationTime + "<br />"
strFileInfo += "Extension: " + fInfo.Extension
Else
strFileInfo = "The file <b>" + fPath + "</b> was not found."
End If
Response.Write(strFileInfo)

C#
string fPath = Server.MapPath("orders.xml");
FileInfo fInfo = new FileInfo(fPath);
string strFileInfo ;
if(fInfo.Exists)
{
strFileInfo = "Name: " + fInfo.Name + "<br />";
strFileInfo += "Location: " + fInfo.FullName + "<br />";
strFileInfo += "Created on: " + fInfo.CreationTime + "<br />";
strFileInfo += "Extension: " + fInfo.Extension;
}
else
{
strFileInfo = "The file <b>" + fPath + "</b> was not found.";
}
Response.Write (strFileInfo);

15.13 How to create a .csv file that grabs the data from the database?

<asp:Button id="Button1" runat="server" Text="Button"></asp:Button>

VB.NET

Dim cn As SqlConnection
Dim cmd As SqlCommand
Dim filename As String
Dim dr As SqlDataReader
Dim i As Integer
Dim sb As System.Text.StringBuilder

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles


Button1.Click
cn=NewSqlConnection("server=localhost;uid=sa;pwd=;database=northwind")
filename = "products.csv"
cmd = New SqlCommand("select * from products ", cn)
cmd.Connection.Open()
dr = cmd.ExecuteReader(CommandBehavior.CloseConnection)
sb = New System.Text.StringBuilder

'For field Names


For i = 0 To dr.FieldCount - 1
If i < (dr.FieldCount - 1) Then
sb.Append(Chr(34) & dr.GetName(i) & _
Chr(34) & ",")
Else
sb.Append(Chr(34) & dr.GetName(i) & _
Chr(34) & vbCrLf)
End If
Next
'For field Values
While dr.Read()
For i = 0 To dr.FieldCount - 1
If i < (dr.FieldCount - 1) Then
sb.Append(Chr(34) & _
dr.GetValue(i).ToString & Chr(34) & ",")
Else
sb.Append(Chr(34) & _
dr.GetValue(i).ToString & Chr(34) & vbCrLf)
End If
Next
End While
dr.Close()
cn.Close()
Response.ContentType = "Application/x-msexcel"
Response.AddHeader _
("content-disposition", "attachment; filename=""" & _
filename & """")
'Write the file directly to the HTTP output stream.
Response.Write(sb.ToString)
Response.End()
End Sub

C#

SqlConnection cn ;
SqlCommand cmd ;
string filename ;
SqlDataReader dr ;
System.Text.StringBuilder sb ;

private void Button1_Click(object sender, System.EventArgs e)


{
cn=newSqlConnection("server=localhost;uid=sa;pwd=;database=northwind");
filename = "products.csv";
cmd = new SqlCommand("select * from products ", cn);
cmd.Connection.Open();
dr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
sb = new System.Text.StringBuilder();

//For field Names


for(int i = 0 ;i< = dr.FieldCount - 1;i++)
{
if( i < (dr.FieldCount - 1) )
{
sb.Append("\t" + dr.GetName(i) + "\t" + ",");
}
else
{
sb.Append("\t" + dr.GetName(i) + "\t" + "\n");
}
}

//For field Values


while( dr.Read())
{
for(int i = 0 ;i<= dr.FieldCount - 1;i++)
{
if( i < (dr.FieldCount - 1) )
{
sb.Append("\t" + dr.GetValue(i) + "\t" + ",");
}
else
{
sb.Append("\t" + dr.GetValue(i) + "\t" + "\n");
}
}
}
dr.Close();
cn.Close();
Response.ContentType = "Application/x-msexcel";
Response.AddHeader ("content-disposition", "attachment; filename=" + filename ) ;

//Write the file directly to the HTTP output stream.


Response.Write(sb.ToString());
Response.End();
}

15.14 How to read text file in ASP.NET?

Use namespace System.IO

VB.NET

Dim sr As StreamReader
sr = File.OpenText(Server.MapPath("1.txt"))
Dim strContents As String = sr.ReadToEnd()
'To display normal raw contents
Response.Write(strContents)

'To handle Carriage returns


Response.Write(strContents.Replace(vbCrLf, "<br>"))

sr.Close()

C#

StreamReader sr = File.OpenText(Server.MapPath("1.txt"));
string strContents = sr.ReadToEnd();
//To display normal raw contents
Response.Write(strContents);

//To handle Carriage returns


Response.Write(strContents.Replace("\n" , "<br>"));

sr.Close();

15.15 How to read specific characters from a text file?


Use namespace System.IO

VB.NET

Dim fs As New System.IO.FileStream(Server.MapPath("1.txt"), IO.FileMode.Open)


Dim buffer(5) As Byte ' 5=> number of characters to be read
fs.Read(buffer, 0, 5)
fs.Close()
Dim filechars() As Char = System.Text.Encoding.ASCII.GetChars(buffer)
Dim filestring As String = New String(filechars)
Response.Write(filestring)

C#

FileStream fs =new FileStream(Server.MapPath("1.txt"), FileMode.Open);


Byte[] buffer= new byte [5] ; //5 => Number of characters to be read
fs.Read(buffer, 0, 5);
fs.Close();
Char[] filechars = System.Text.Encoding.ASCII.GetChars(buffer);
string filestring = new String(filechars);
Response.Write(filestring);

15.16 How to check files exist in a particular directory?

Try to use "System.IO.File.Exists("path")". path is the physical file path and it will return you a boolean value.

15.17 What is a MemoryStream and how to use MemoryStream in


ASP.NET?

The MemoryStream class creates streams that use memory as storage instead of a disk or a network

connection. MemoryStream encapsulates data stored as an unsigned byte array that is initialized upon

creation of a MemoryStream object, or the array can be created as empty. The encapsulated data is directly

accessible in memory. Memory streams can reduce the need for temporary buffers and files in an application.

For more details refer

• MemoryStream Class

• How can I display an image from a Sql Server database?


15.18 How to detect if the string indicating a file-system resource is a
file or directory?

VB.NET

Dim path As String = Server.MapPath("webform1.aspx")


' Put user code to initialize the page here
If(File.GetAttributes(path) And FileAttributes.Directory) = FileAttributes.Directory Then
Response.Write("Its a directory")
Else
Response.Write("Its a file")
End If

C#

string path =Server.MapPath ("webform1.aspx");


if ((File.GetAttributes(path) & FileAttributes.Directory) ==FileAttributes.Directory)
{
Response.Write ("Its a directory");
}
else
{
Response.Write ("Its a file");
}
16.1 How to make the listbox scroll down to show it's last entry when
the page loads?

<p>
<asp:ListBox id="ListBox1" runat="server"></asp:ListBox>
</p>
<p>
<asp:Button id="buttonAdd" runat="server" Text="Add"></asp:Button>
</p>

In button Click Event

VB.NET

ListBox1.Items.Add(DateTime.Now.ToString("MMM dd, yyyy") + " " + DateTime.Now.ToString("t"))


Dim scrollScript As String
scrollScript &= "<script language='javascript'>"
scrollScript &= "document.forms[0].ListBox1.selectedIndex " & _
" = document.forms[0].ListBox1.options.length-1;"
scrollScript &= "<" & "/" & "script>"
Page.RegisterStartupScript("", scrollScript)

C#

ListBox1.Items.Add(DateTime.Now.ToString("MMM dd, yyyy") + " " + DateTime.Now.ToString("t"));


string scrollScript="" ;
scrollScript += "<script language='javascript'>";
scrollScript += "document.forms[0].ListBox1.selectedIndex= document.forms[0].ListBox1.options.length-
1;";
scrollScript += "<" + "/" + "script>";
Page.RegisterStartupScript("", scrollScript);

16.2 How to check if an item already exists in a listbox?

VB.NET

Dim lstitem As ListItem = ListBox1.Items.FindByValue("<valuecheckedfor>")


If Not lstitem Is Nothing Then
Response.Write("Item Exists")
Else
Response.Write("Item Does not exist")
End If

C#

ListItem lstitem = ListBox1.Items.FindByValue("<valuecheckedfor>");


if ( lstitem !=null)
{
Response.Write ("Does exist");
}
else
{
Response.Write ("Does not exist");
}

You can also use FindByText instead of FindByValue.

16.3 How to populate a listbox with the Column Names in a Table?

VB.NET

'Populate the dataset


Dim dc As DataColumn
For Each dc In ds.Tables(0).Columns
ListBox1.Items.Add(dc.ColumnName)
Next

C#

//Populate the Dataset


foreach (DataColumn dc in ds.Tables[0].Columns)
{
ListBox1.Items.Add(dc.ColumnName);
}
16.4 How to clear all the items in a listbox?

VB.NET

ListBox1.Items.Clear

C#

ListBox1.Items.Clear();

16.5 How to add items dynamically to a ListBox using an ArrayList?

<asp:ListBox id="ListBox1" runat="server" AutoPostBack="True"></asp:ListBox>

VB.NET

Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load


'Put user code to initialize the page here
If Not IsPostBack Then
Dim arrList As New ArrayList
arrList.Add("One")
arrList.Add("Two")
arrList.Add("Three")
arrList.Add("Four")
ListBox1.DataSource = arrList
ListBox1.DataBind()
End If
End Sub

Private Sub ListBox1_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs)


Handles ListBox1.SelectedIndexChanged
Response.Write(ListBox1.SelectedItem.Text)
End Sub

C#

private void Page_Load(object sender, System.EventArgs e)


{
// Put user code to initialize the page here
if (!Page.IsPostBack )
{
ArrayList arrList = new ArrayList();
arrList.Add("One");
arrList.Add("Two");
arrList.Add("Three");
arrList.Add("Four");
ListBox1.DataSource = arrList;
ListBox1.DataBind();
}
}
private void ListBox1_SelectedIndexChanged(object sender, System.EventArgs e)
{
Response.Write (ListBox1.SelectedItem.Text );
}

16.6 How to move items between ListBoxes?

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


<asp:ListItem Value="Faqs">Faqs</asp:ListItem>
<asp:ListItem Value="Tips">Tips</asp:ListItem>
<asp:ListItem Value="Tricks">Tricks</asp:ListItem>
<asp:ListItem Value="Advanced">Advanced</asp:ListItem>
</asp:ListBox>
<asp:Button id="btnToRight" style="Z-INDEX: 101; LEFT: 112px; POSITION: absolute; TOP: 24px"
runat="server" Text=">"></asp:Button>
<asp:ListBox id="ListBox2" style="Z-INDEX: 102; LEFT: 152px; POSITION: absolute; TOP: 16px"
runat="server"></asp:ListBox>
<asp:RequiredFieldValidator id="RequiredFieldValidator1" style="Z-INDEX: 103; LEFT: 24px; POSITION:
absolute; TOP: 120px"
runat="server" ErrorMessage="Please Select Item"
ControlToValidate="ListBox1"></asp:RequiredFieldValidator>

VB.NET

Private Sub btnToRight_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles


btnToRight.Click
If ListBox1.Items.Count = 0 Then
Response.Write("No item to move")
End If
Dim itemremoved As String = ListBox1.SelectedItem.Text
ListBox1.Items.Remove(itemremoved)
ListBox2.Items.Add(itemremoved)
End Sub

C#

private void btnToRight_Click(object sender, System.EventArgs e)


{
if (ListBox1.Items.Count == 0 )
{
Response.Write("No item to move");
}
string itemremoved = ListBox1.SelectedItem.Text;
ListBox1.Items.Remove(itemremoved);
ListBox2.Items.Add(itemremoved);
}

16.7 How to select a specific Item in a ListBox in code?

VB.NET

ListBox1.Items.FindByValue(<Value>).Selected = true
'ListBox1.Items.FindByText(<Text>).Selected = true

C#

ListBox1.Items.FindByValue(<Value>).Selected = true;
//ListBox1.Items.FindByText(<Text>).Selected = true;

16.8 How can you use a ListBox control to display items with Price above
a specific value in one color and the ones below that value in a different
color?

The ListBox Web server control prevents us from assigning the style property to each item in the ListBox. This

bug is confirmed by Microsoft Knowledge Base Article - 309338

So, instead use a HTML ListBox with runat=server

<SELECT id="listbox1" size="14" runat="server" >


</SELECT>

VB.NET

Dim myconnection As SqlConnection


Dim myda As SqlDataAdapter
Dim ds As DataSet
Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
myconnection=NewSqlConnection("Server=localhost;uid=sa;password=;database=northwind;")
myda = New SqlDataAdapter("Select * from Products ", myconnection)
ds = New DataSet()
myda.Fill(ds, "AllTables")
dim i as Integer
For i = 0 To ds.Tables(0).Rows.Count - 1
listBox1.Items.Add(New ListItem(ds.Tables(0).Rows(i)("UnitPrice"),
ds.Tables(0).Rows(i)("ProductID")))
If ds.Tables(0).Rows(i)("UnitPrice") <= 25 Then
listBox1.Items(i).Attributes.Add("style", "color:red")
Else
listBox1.Items(i).Attributes.Add("style", "color:green")
End If
Next
End Sub

C#

SqlConnection mycn;
SqlDataAdapter myda;
DataSet ds;
String strConn;
private void Page_Load(object sender, System.EventArgs e)
{
if (!IsPostBack)
{
strConn="DataSource=localhost;uid=sa;pwd=;Initial Catalog=northwind";
mycn = new SqlConnection(strConn);
myda = new SqlDataAdapter ("Select * FROM Products ", mycn);
ds = new DataSet();
myda.Fill (ds,"Table");

for(int i = 0 ;i < ds.Tables[0].Rows.Count - 1;i++)


{
listBox1.Items.Add (new ListItem(ds.Tables[0].Rows[i]["UnitPrice"].ToString(),
ds.Tables[0].Rows[i]["ProductID"].ToString()));
if(Convert.ToDouble(ds.Tables[0].Rows[i]["UnitPrice"].ToString()) <= 25 )
{
listBox1.Items[i].Attributes.Add("style", "color:red");
}
else
{
listBox1.Items[i].Attributes.Add("style", "color:green");
}
}
}
}

16.9 How to select all the Items from a listbox when the user selects a
radio button?

<asp:listbox id="ListBox1" runat="server" selectionmode="Multiple">


<asp:listitem value="Red">Red</asp:listitem>
<asp:listitem value="Blue">Blue</asp:listitem>
<asp:listitem value="Green">Green</asp:listitem>
<asp:listitem value="White">White</asp:listitem>
</asp:listbox>
<asp:radiobutton id="RadioButton1" runat="server" groupname="selrb" text="Select All"
autopostback="True"></asp:radiobutton>

VB.NET

Private Sub RadioButton1_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs)


Handles RadioButton1.CheckedChanged
Dim lstItem As ListItem
For Each lstItem In ListBox1.Items
lstItem.Selected = True
Next
End Sub

C#

foreach (ListItem lstItem in ListBox1.Items)


{
lstItem.Selected = true;
}
16.10 How to use a single DataReader associated with two different
tables to databind two different listbox controls?

VB.NET

Dim cn As SqlConnection
Dim cmd As SqlCommand
Dim dr As SqlDataReader
cn=NewSqlConnection("Server=localhost;uid=sa;database=northwind;pwd=")
cmd = New SqlCommand("select * from products;select * from categories", cn)
cn.Open()
dr = cmd.ExecuteReader()
ListBox1.DataSource = dr
ListBox1.DataTextField = "productname"
ListBox1.DataBind()
dr.NextResult()
ListBox2.DataSource = dr
ListBox2.DataTextField = "categoryname"
ListBox2.DataBind()

C#

SqlConnection cn;
SqlCommand cmd;
SqlDataReader dr;
cn=newSqlConnection("Server=localhost;uid=sa;database=northwind;pwd=");
cmd= new SqlCommand ("select * from products;select * from categories", cn);
cn.Open();
dr = cmd.ExecuteReader();
ListBox1.DataSource = dr;
ListBox1.DataTextField = "productname";
ListBox1.DataBind();
dr.NextResult();
ListBox2.DataSource = dr;
ListBox2.DataTextField = "categoryname";
ListBox2.DataBind();
17.1 How can I remove the cache of a page (cached with VaryByParam)
for certain request params in code?

You can attach a cache dependency to the response that is unique per query param, then invalidate the

dependency for that particular param:

// add cache item dependency on response


string cacheKey = "xxx.aspx?" + queryParam;
Cache[cacheKey] = new object();
Response.AddCacheItemDependency(cacheKey);

// invalidate the dependency


string cacheKey = "xxx.aspx?" + queryParam;
Cache.Remove(cacheKey);

17.2 How can I set a page/control to be cached only for certain


parameters?
Let's say you set your output cache directive as follows:

<%@ OutputCache Duration="86400" VaryByParam="RegionID" VaryByCustom="ProductID" %>

VaryByCustom - is a string that your application has to interpret in the GetVaryByCustomString override in

the gloabal.asax file.

Now, to avoid caching pages for certain ProductIDs you can set the cacheability to private or nocache from

your page load for those pages as follows:

VB.NET

Response.Cache.SetCacheability(HttpCacheability.Private)

C#

Response.Cache.SetCacheability(HttpCacheability.Private) ;

17.3 What is Output Caching?

Output caching lets you cache the output of static aspx pages or portions of pages to improve performance.

Since the pages are cached asp.net doesn't have to regenerate the html for every request.

For more information see:

• Output Caching Techniques In ASP.NET

17.4 I want to Cache based on HTTP header .How can I do that?

<%@OutputCache ... VaryByHeader="UserAgent" %>

or

<%@ OutputCache ... VaryByHeader="Accept-Language" %>

17.5 How to make a page expire immediately in such a way that a


warning message "This page has expired."appears?

Try the following:


<%@ OutputCache location="none" %>

17.6 How to prevent client Cache? I want every client request get sent to
the server even if it's behind a proxy server and for any browser setting.

You can use tag

<%@ OutputCache Duration="0" Location="None" VaryByParam="none" %>

or

VB.NET

Response.Cache.SetCacheability(HttpCacheability.NoCache)

C#

Response.Cache.SetCacheability(HttpCacheability.NoCache);

17.7 Is there any way to cache by browser a page or User Control?

Try VaryByCustom="browser" in the user control/page.

17.8 Is caching PDF Files a good or bad idea?

If the PDF files are on the disk, you should just let the IIS handle them. The IIS static file handler performs

caching and is much faster than the ASP.NET cache.

17.9 How to remove Output Cache by param?

You can attach a cache dependency to the response that is unique per query param, then invalidate the

dependency for the particular param:

VB.NET

'add cache item dependency on response


Dim cacheKey As String = "webform1.aspx?" + queryParam
Cache(cacheKey) = New Object() '
Response.AddCacheItemDependency(cacheKey)

' invalidate the dependency


Dim cacheKey As String = "webform1.aspx?" + queryParam
Cache.Remove(cacheKey)

C#
// add cache item dependency on response
string cacheKey = "webform1.aspx?" + queryParam;
Cache[cacheKey] = new object();
Response.AddCacheItemDependency(cacheKey);

// invalidate the dependency


string cacheKey = "webform1.aspx?" + queryParam;
Cache.Remove(cacheKey);

17.10 How can I programatically invalidate the outputcache from a


usercontrol?

You could add a dependency to the output cached control, and change the dependency to evict the control.

Here's code to do that:

VB.NET

If TypeOf Parent Is System.Web.UI.BasePartialCachingControl Then


Cache("dependent") = "dependent"
Dim dep As New CacheDependency(Nothing, New String() {"dependent"}) '
CType(Parent, System.Web.UI.BasePartialCachingControl).Dependency = dep
End If

C#

if (Parent is System.Web.UI.BasePartialCachingControl)
{
Cache["dependent"] = "dependent";
CacheDependency dep = new CacheDependency(null, new string[] "dependent");
((System.Web.UI.BasePartialCachingControl)Parent).Dependency = dep;
}

17.11 Is it possible to cache a page by Browser Version and/or some


params?

Yes. In your page:

<%@ OutputCache Duration="60" VaryByParams="abc;xyz" VaryByCustom="browsermajorversion" %>

In your global.asax file:

VB.NET

Public Overrides Function GetVaryByCustomString(context As HttpContext, custom As String) As String


If custom.ToLower() = "browsermajorversion" Then
Dim browser As HttpBrowserCapabilities = context.Request.Browser
Return browser.Browser + " " + browser.MajorVersion
Else
Return MyBase.GetVaryByCustomString(context, custom)
End If
End Function 'GetVaryByCustomString
C#

public override string GetVaryByCustomString(HttpContext context, string custom)


{
if (custom.ToLower() == "browsermajorversion") {
HttpBrowserCapabilities browser = context.Request.Browser;
return browser.Browser + " " + browser.MajorVersion;
}
else
{
return base.GetVaryByCustomString(context, custom);
}
}

17.12 Why do I get the error message "The type or namespace name
'CacheDependency' could not be found (are you missing a using directive
or an assembly reference?) "?

Use namespace System.Web.Caching or

refer to it as System.Web.Caching.CacheDependency

17.13 Is there a way that I can clear/expire a page cache from another
page/class?

No, not easily unless you use the output cache APIs on Response.Cache and take advantage of the

Response.AddCacheDependency() to make the page dependent on a common key.

Then, from the other page or class you could invalidate the common key which would enforce a dependency

eviction (since the key page1 depended on changed). Refer How to remove OutputCache by param?

17.14 How to access the Cache from a compiled class?

VB.NET

somevar=System.Web.HttpContext.Current.Cache(" ")

C#

somevar=System.Web.HttpContext.Current.Cache(" ");

17.15 How can I cache the page by the complete querystring?

Try the following:

<%@ OutputCache Duration="10" VaryByParam="*" %>


This should result in any changes to querystring parameters causing a new version of the page to be cached.

Keep in mind that this can significantly increase the amount of memory used for caching, depending on how

many querystring parameters you're using.

Note: "*" is not recommended - it is best to use a list of params that your page truly varies by.

17.16 How do I access the cache in the Global.asax?

Use HttpRuntime.Cache

17.17 How to display items stored in a local application Cache?

VB.NET

Dim objItem As DictionaryEntry


For Each objItem In Cache
Response.Write(("Key :" + objItem.Key.ToString() + "
"))
Response.Write((" Value :" + objItem.Value.ToString() + "
"))
Next

C#

foreach(DictionaryEntry objItem in Cache)


{
Response.Write ("Key :" + objItem.Key.ToString () + "
");
Response.Write(" Value :" + objItem.Value.ToString ()+ "
");
}

17.18 Is there a Cache.RemoveAll()? How can I clear / remove the total


cache?

VB.NET

Dim objItem As DictionaryEntry


For Each objItem In Cache
'Response.Write (objItem.Key.ToString ());
Cache.Remove(objItem.Key.ToString())
Next

C#

foreach(DictionaryEntry objItem in Cache)


{
//Response.Write (objItem.Key.ToString ());
Cache.Remove(objItem.Key.ToString () ) ;
}
17.19 Why do I get the error message "Exception Details:
System.Web.HttpException: Cache is not available "?

Try using "HttpContext.Current.Cache" instead of just "Cache" in your code. The compiler probably wasn't

able to resolve the Cache type.

17.20 How to remove the Cache starting with "cachedata_"?

VB.NET

Dim enumerator As IDictionaryEnumerator = Cache.GetEnumerator()


While enumerator.MoveNext()
Dim key As String = CType(CType(enumerator.Current, DictionaryEntry).Key, String)
If key.StartsWith("cachedata_") Then
' Print it:
Response.Write(("Deleting key " + key + "
"))
' Remove it:
Cache.Remove(key)
End If
End While

C#

IDictionaryEnumerator enumerator = Cache.GetEnumerator();


while(enumerator.MoveNext())
{
String key = (String) ((DictionaryEntry) enumerator.Current).Key;
if(key.StartsWith("cachedata_"))
{
// Print it:
Response.Write("Deleting key " + key + "
");
// Remove it:
Cache.Remove(key);
}
}
18.1 How to send HTML mail in ASP.NET?

VB.NET

Dim mail As New MailMessage()


mail.To = "manag@megasolutions.net"
mail.From = "admin@megasolutions.net"
mail.Subject = "Test."
mail.BodyFormat = MailFormat.Html
mail.Body = "Test Message"
SmtpMail.SmtpServer = "localhost" 'your real server goes here
SmtpMail.Send(mail)

C#
MailMessage mail = new MailMessage();
mail.To = "manag@megasolutions.net";
mail.From = "admin@megasolutions.net";
mail.Subject = "Test.";
mail.BodyFormat = MailFormat.Html;
mail.Body = "Test Message";
SmtpMail.SmtpServer = "localhost"; //your real server goes here
SmtpMail.Send( mail );

18.2 How to send simple text mail in ASP.NET?

VB.NET

Dim mail As New MailMessage()


mail.To = "admin@megasolutions.net"
mail.From = "manag@megasolutions.net"
mail.Subject = "Test."
mail.Body = "Test Message"
SmtpMail.SmtpServer = "localhost" 'your real server goes here
SmtpMail.Send(mail)

C#

MailMessage mail = new MailMessage();


mail.To = "admin@megasolutions.net";
mail.From = "manag@megasolutions.net";
mail.Subject = "Test.";
mail.Body = "Test Message";
SmtpMail.SmtpServer = "localhost"; //your real server goes here
SmtpMail.Send( mail );

18.3 What is the namespace used for sending mails?

Use System.Web.Mail

The System.Web.Mail namespace contains classes that enable you to construct and send messages using the

CDOSYS (Collaboration Data Objects for Windows 2000) message component. The mail message is delivered

either through the SMTP mail service built into Microsoft Windows 2000 or through an arbitrary SMTP server.

The classes in this namespace can be used from ASP.NET or from any managed application.

For more details refer System.Web.Mail Namespace

18.4 How do I configure a local SMTP server?


Install the SMTP virtual server that is part of IIS.

• You will need your Windows installation CD.

• Use Add or Remove Programs in the Windows Control Panel to launch Add/Remove Windows

Components.

• Select Internet Information Services (IIS) and then click Details.

• Check SMTP Service and then click OK.

• The installation process will prompt you for your Windows CD and will install the SMTP virtual server.

After installing the SMTP server (also reboot), configure it by following these steps:

1. In the Control Panel, choose Administrative Tools, and then choose Internet Information Services.

2. Open the node for your computer, right-click the Default SMTP Virtual Server node and choose

Properties.

3. In the Access tab, click Connection.

4. Select Only the list below, click Add and add the IP 127.0.0.1. This restricts connections to just the

local computer, i.e., localhost. Close the Connection dialog box.

5. Click Relay and repeat Step 5 to allow only localhost to relay through this server.

In your firewall or router (or both), close incoming port 25. This is an important security measure

that will prevent spammers from finding your SMTP server and using it to relay spam.

18.5 Why do I get the error message "The transport failed to connect to
the server "?
This is a network related error. Your application cannot connect to the mail server specified.

Make sure that the following are true about SmtpMail.SmtpServer:

• Is a valid SMTP Server

• Make sure that the server System.Web.Mail is running or can connect to the mail server. Some times

firewalls or proxy servers can get in the way.

• Try specifying the value by IP address. Poor DNS resolution can sometimes hinder name lookups.

• Make sure that the mail server is running at port 25.

• If you did not specify a SmtpMail.SmtpServer property, or if SmtpMail.SmtpServer points to

"localhost" (or the equivalent), be sure the SMTP Service is running on port 25.

• For testing purposes change the MailMessage.From and MailMessage.To properties to an address that

exists on SmtpMail.SmtpServer. Some times this exception is thrown, when it really is a relay issue.

18.6 Why do I get the error message "The SendUsing configuration value
is invalid"?

This problem occurs because read access to the Internet Information Services (IIS) metabase and the

Microsoft Active Directory directory service has been removed for the Everyone group. This access has been

removed because of a security modification in Exchange 2000 Server SP3. CDOEX, CDOSYS, and

System.Web.Mail must have access to the IIS metabase to access information about the location of the

pickup directory path. This behavior occurs when you use the Sendusingpickup method and if this information

is not specified in the application code. Because access is restricted, the non-administrative user under whose

security context the application is running cannot read this information from the IIS metabase and Active

Directory. Fore more information refer Read Access to the Everyone Group Is Removed After You Install

Exchange 2000 SP3

18.7 How can I read POP3 email with ASP.NET?

Refer Read POP3 Email with ASP.NET

18.8 How do I email a website exception?

VB.NET

Protected Sub Application_Error(sender As [Object], e As EventArgs)


Dim ex As Exception = Server.GetLastError()
Dim mail As New MailMessage()
mail.To = "manag@megasolutions.net"
mail.From = "admin@megasolutions.net"
mail.Subject = ex.Message.ToString()
mail.Body = ex.ToString()
mail.BodyFormat = MailFormat.Html
SmtpMail.SmtpServer = "localhost"
SmtpMail.Send(mail)
End Sub 'Application_Error

C#

protected void Application_Error(Object sender, EventArgs e)


{
Exception ex = Server.GetLastError ();
MailMessage mail = new MailMessage();
mail.To = "manag@megasolutions.net";
mail.From = "admin@megasolutions.net";
mail.Subject = ex.Message.ToString ();
mail.Body =ex.ToString ();
mail.BodyFormat = MailFormat.Html;
SmtpMail.SmtpServer = "localhost";
SmtpMail.Send( mail );
}

18.9 How do I send a web page?

Use namespace System.IO and System.NET VB.NET

'In Page_Load
Dim mailcontenturl As String = "http://www.megasolutions.net"
Dim mail As New MailMessage()
mail.To = "manag@megasolutions.net"
mail.From = "admin@megasolutions.net"
mail.Subject = "Test."

'To send webpage


mail.Body = GetHTML(mailcontenturl)
mail.BodyFormat = MailFormat.Html
mail.UrlContentBase = mailcontenturl

SmtpMail.SmtpServer = "localhost"
SmtpMail.Send(mail)

'Function GetHTML
Private Function GetHTML(url As String) As String
Dim wReq As WebRequest = System.Net.HttpWebRequest.Create(url)
Dim sr As New StreamReader(wReq.GetResponse().GetResponseStream())
Dim result As String = sr.ReadToEnd()
sr.Close()
Return result
End Function 'GetHTML
C#

//In Page_Load
string mailcontenturl ="http://www.megasolutions.net";
MailMessage mail = new MailMessage();
mail.To = "manag@megasolutions.net";
mail.From = "admin@megasolutions.net";
mail.Subject = "Test.";

//To send webpage


mail.Body = GetHTML ( mailcontenturl );
mail.BodyFormat = MailFormat.Html;
mail.UrlContentBase = mailcontenturl;

SmtpMail.SmtpServer = "localhost";
SmtpMail.Send( mail );

//Function GetHTML
private string GetHTML( string url )
{
WebRequest wReq= System.Net.HttpWebRequest.Create(url);
StreamReader sr = new StreamReader( wReq.GetResponse().GetResponseStream() );
string result = sr.ReadToEnd();
sr.Close();
return result;
}

18.10 How do I send non US-ASCII mails?

VB.NET

mail.BodyEncoding = System.Text.Encoding.GetEncoding( "ISO-2022-JP" )

C#

mail.BodyEncoding = System.Text.Encoding.GetEncoding( "ISO-2022-JP" );

18.11 How do I send an email with attachments?

VB.NET

Dim mailattach As New MailAttachment(Server.MapPath("<yourfilename>"))


mail.Attachments.Add(mailattach)

C#

MailAttachment mailattach = new MailAttachment( Server.MapPath( "<yourfilename>" ) );


mail.Attachments.Add( mailattach );
18.12 How do I add the Reply-To header to the MailMessage?

VB.NET

mail.Headers.Add( "Reply-To", "admin1@megasolutions.net" )

C#

mail.Headers.Add( "Reply-To", "admin1@megasolutions.net" );

18.13 Why do I get the error message "Sender address rejected: need
fully-qualified address "?

This is happening because your SmtpMail.SmtpServer is rejecting addresses.

To resolve this make sure

• all email addresses specified at MailMessage.To, MailMessage.Cc, MailMessage.Bcc and

MailMessage.From are valid email addresses

• you have permissions to relay through the server.

• MailMessage.From has permissions to relay through the server

18.14 How do I resolve the error "The server rejected one or more
recipient addresses. The server response was: 503 This mail server
requires authentication. Please check your mail client settings"?

CDOSYS supports username and password authentication, and version 1.1 of the .NET Framework added the

Fields property to the MailMessage class, which lets you set arbitrary fields of the underlying CDOSYS object.

Refer Extending System.Web.Mail

18.15 How can I specify multiple recipients for a message?

Seperate each recipient with a semicolon (;) in the mailMessage.To property:

VB.NET

mailMessage.To = "abc@megasolutions.net;xyz@megasolutions.net"

C#

mailMessage.To = "abc@megasolutions.net;xyz@megasolutions.net";
18.16 How can I use a "friendly name" in the To and From properties?

Format the email address this way:

VB.NET

mail.From = "Name <name@megasolutions.net>"


mail.To = "Name <name@megasolutions.net>"

C#

mail.From = "Name <name@megasolutions.net>";


mail.To = "Name <name@megasolutions.net>";

18.17 Why do I get the error message "550 5.7.1 Unable to relay for xxx
or 550 not local host xxx, not a gateway "?

The SMTP server is not configured to allow you to relay. If you are working with a local SMTP server, you can

configure it to allow relaying for IP 127.0.0.1.

19.1 Why do I get the error message "CS0122:


'System.Drawing.Imaging.ImageFormat.jpeg' is inaccessible due to its
protection level "?

Try giving the proper file path for the image. Also make sure you have proper permissions on that file.

19.2 Why do I get the error message "A generic error occurred in
GDI+."?

Give the proper path of the file. Check your permissions on the server where you are trying to write/read the

files

19.3 How to draw strings vertically on a Bitmap?

...
dim sFormat As New StringFormat()
sFormat.FormatFlags = StringFormatFlags.DirectionVertical
...
g.DrawString("Syncfusion", new Font("Arial",16,FontStyle.Italic or FontStyle.Bold ),
SystemBrushes.WindowText, new PointF(2,2) , sFormat )

...
StringFormat sFormat = new StringFormat() ;
sFormat.FormatFlags = StringFormatFlags.DirectionVertical ;
...
g.DrawString("Syncfusion", new Font("Arial",16,FontStyle.Italic|FontStyle.Bold ),SystemBrushes.WindowText,
new PointF(2,2) ,sFormat) ;
...

19.4 I am using GDI+ to write on a bitmap. I know how to make font


Italic/Bold. What should be done to apply both Italic and Bold?

VB.NET

dim fntFont as Font = new Font("Arial",16,FontStyle.Italic OR FontStyle.Bold )

C#

Font fntFont =new Font("Arial",16,FontStyle.Italic|FontStyle.Bold ) ;

For more details refer FontStyle Enumeration

19.5 How can I display image from a Sql Server database?

VB.NET

'Function
Public Function showImage(empid As Int32) As Byte()
DimmyconnectionAsNewSqlConnection("Server=localhost;uid=sa;password=;database=northwind;")
Dim mycommand As New SqlCommand("Select Employeeid, FirstName,Photo from Employees where
employeeid =" + empid.ToString(), myconnection)
myconnection.Open()
Dim dr As SqlDataReader = mycommand.ExecuteReader()
dr.Read()
Dim imgbyte As Byte() = CType(dr("Photo"), Byte())
Return imgbyte
End Function 'showImage

'In Page_Load
Dim data As Byte() = showImage(2)
Dim offset As Int32 = 78
Dim mstream As New System.IO.MemoryStream()
mstream.Write(data,offset,data.Length -offset)
Dim bmp As New System.Drawing.Bitmap(mstream)
bmp.Save(Server.MapPath("sample.jpeg"), System.Drawing.Imaging.ImageFormat.Jpeg)
mstream.Close()
Image1.ImageUrl = Server.MapPath("sample.jpeg")
C#

//Function
public byte [] showImage(Int32 empid)
{
SqlConnectionmyconnection=newSqlConnection("Server=localhost;uid=sa;password=;database=northwind;");
SqlCommand mycommand = new SqlCommand ("Select Employeeid, FirstName,Photo from Employees
where employeeid =" + empid, myconnection);
myconnection.Open ();
SqlDataReader dr= mycommand.ExecuteReader();
dr.Read();
byte[] imgbyte =(byte[]) dr["Photo"];
return imgbyte;

}
//In Page_Load
byte[] data = showImage (2);
Int32 offset =78;
System.IO.MemoryStream mstream = new System.IO.MemoryStream ();
mstream.Write(data, offset, data.Length - offset);
System.Drawing.Bitmap bmp= new System.Drawing.Bitmap(mstream);
bmp.Save(Server.MapPath ("sample.jpeg"), System.Drawing.Imaging.ImageFormat.Jpeg );
mstream.Close();
Image1.ImageUrl = Server.MapPath("sample.jpeg");

19.6 How to display image on a browser without using the image tag?

VB.NET

Dim objBitmap As New Bitmap(500, 500)


Dim objGraphics As Graphics = Graphics.FromImage(objBitmap)
objGraphics.Clear(Color.White)
objGraphics.FillRectangle(New SolidBrush(Color.Purple), 0, 0, 400, 10)
objBitmap.Save(Response.OutputStream, ImageFormat.Jpeg)

C#

Bitmap objBitmap = new Bitmap(500, 500);


Graphics objGraphics = Graphics.FromImage(objBitmap);
objGraphics.Clear(Color.White);
objGraphics.FillRectangle(new SolidBrush(Color.Purple ), 0, 0, 400, 10);
objBitmap.Save(Response.OutputStream, ImageFormat.Jpeg);

19.7 How to rotate a image in ASP.NET?

VB.NET
Dim img As System.Drawing.Image
Dim strFilename As String = Server.MapPath("curves1.jpg")
img = System.Drawing.Image.FromFile(strFilename)
Dim b = New System.Drawing.Bitmap(img.Width, img.Height, PixelFormat.Format24bppRgb)
Dim g As Graphics = Graphics.FromImage(b)
img.RotateFlip(System.Drawing.RotateFlipType.Rotate270FlipXY)
g.DrawImage(img, New Point(0, 0))
Response.ContentType = "image/jpeg"
b.Save(Response.OutputStream, ImageFormat.Jpeg)

C#

System.Drawing.Image img ;
string strFilename = Server.MapPath("curves1.jpg") ;
img = System.Drawing.Image.FromFile(strFilename) ;
Bitmap b = new System.Drawing.Bitmap(img.Width, img.Height, PixelFormat.Format24bppRgb) ;
Graphics g = Graphics.FromImage(b) ;
img.RotateFlip(System.Drawing.RotateFlipType.Rotate270FlipXY) ;
g.DrawImage(img,new Point(0,0)) ;
Response.ContentType="image/jpeg" ;
b.Save(Response.OutputStream, ImageFormat.Jpeg) ;

19.8 How to show the graphics that have text written on it crisp and
clear?

Try

VB.NET

objGraphics.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias

C#

objGraphics.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias;

19.9 I get error "Value of String cannot be converted


System.Drawing.Color' when I use label1.BackColor= "Red"?

Try
VB.NET

Label1.BackColor = System.Drawing.Color.FromName("Green")

C#

Label1.BackColor = System.Drawing.Color.FromName("Green");

19.10 How to load a image from a website URL?

Use WebClient to request it and save it to disk, open the local copy.

19.11 How can I check the image raw format i.e how can I find if
Image.RawFormat property returns a "jpeg" or "gif",?

VB.NET

if (Img.RawFormat.Equals(System.Drawing.Imaging.ImageFormat.Jpeg)) then
Response.ContentType = "image/jpeg"
Else
..
End if

C#

if (Img.RawFormat.Equals(System.Drawing.Imaging.ImageFormat.Jpeg))
{
Response.ContentType = "image/jpeg"
}
else
{
..
}

19.12 How to align the text on a bitmap?

VB.NET

...
Dim sFormat As New StringFormat()
sFormat.Alignment = StringAlignment.Far
...
g.DrawString("Syncfusion", New Font("Arial", 16, FontStyle.Italic), SystemBrushes.WindowText, New
PointF(2, 2), sFormat)
......

C#

...
StringFormat sFormat = new StringFormat() ;
sFormat.Alignment = StringAlignment.Far;
...
g.DrawString("Syncfusion", new Font("Arial", 16, FontStyle.Italic), SystemBrushes.WindowText, new PointF(2,
2), sFormat) ;
......
20.1 How to bind an ArrayList to a DropDownList?

VB.NET

Dim arrList As ArrayList = New ArrayList


arrList.Add("Faq")
arrList.Add("Tips")
arrList.Add("Tricks")
DropDownList1.DataSource = arrList
DropDownList1.DataBind()

C#

ArrayList arrList = new ArrayList();


arrList.Add("Faq");
arrList.Add("Tips");
arrList.Add("Tricks");
DropDownList1.DataSource = arrList;
DropDownList1.DataBind();

20.2 How to check if the ArrayList is empty?

VB.NET

if arrList= 0 then
..
else
..
end if

C#

if (arrList ==0)
{
...
}
else
{
...
}

20.3 I get the error message "DataGrid with id 'DataGrid1' could not
automatically generate any columns from the selected data source"
when I bind a HashTable to the DataGrid?

Set the AutoGenerateColumns property of the DataGrid to False.Sample code below VB.NET

<asp:DataGrid AutoGenerateColumns=False id="DataGrid1" runat="server">


<Columns >
<asp:TemplateColumn HeaderText="HashTable">
<ItemTemplate>
<%# Container.DataItem.Key %> <br>
<%# Container.DataItem.Value %>
</ItemTemplate>
</asp:TemplateColumn>
</Columns>
</asp:DataGrid>

'In Page_Load
Dim ht As New Hashtable()
ht.Add("emp1", "A")
ht.Add("emp2", "B")
ht.Add("emp3", "C")

DataGrid1.DataSource = ht
DataGrid1.DataBind()

C#

<asp:DataGrid AutoGenerateColumns=False id="DataGrid1" runat="server">


<Columns >
<asp:TemplateColumn HeaderText="HashTable">
<ItemTemplate>
<%# ((DictionaryEntry)Container.DataItem).Key %><br>
<%# ((DictionaryEntry)Container.DataItem).Value %>
</ItemTemplate>
</asp:TemplateColumn>
</Columns>
</asp:DataGrid>

//In Page_Load
Hashtable ht = new Hashtable();
ht.Add ("emp1", "A");
ht.Add ("emp2", "B");
ht.Add ("emp3", "C");

DataGrid1.DataSource = ht;
DataGrid1.DataBind();
20.4 How to sort ArrayList?

<asp:Button id="btnAsc" runat="server" Text="Asc"></asp:Button>


<asp:ListBox id="ListBox1" runat="server"></asp:ListBox>
<asp:Button id="btnDesc" runat="server" Text="Desc"></asp:Button>

VB.NET

Private Sub Page_Load(sender As Object, e As System.EventArgs)


' Put user code to initialize the page here
Dim arrlist As New ArrayList()
arrlist.Add("Tips")
arrlist.Add("Tricks")
arrlist.Add("Code")
arrlist.Add("Samples")
ListBox1.DataSource = arrlist
ListBox1.DataBind()
ViewState("AList") = arrlist
End Sub 'Page_Load

Private Sub btnAsc_Click(sender As Object, e As System.EventArgs)


CType(ViewState("AList"), ArrayList).Sort()
ListBox1.DataSource = CType(ViewState("AList"), ArrayList)
ListBox1.DataBind()
End Sub 'btnAsc_Click

Private Sub btnDesc_Click(sender As Object, e As System.EventArgs)


CType(ViewState("AList"), ArrayList).Sort()
CType(ViewState("AList"), ArrayList).Reverse()
ListBox1.DataSource = CType(ViewState("AList"), ArrayList)
ListBox1.DataBind()
End Sub 'btnDesc_Click

C#

private void Page_Load(object sender, System.EventArgs e)


{
// Put user code to initialize the page here
ArrayList arrlist = new ArrayList ();
arrlist.Add ("Tips");
arrlist.Add ("Tricks");
arrlist.Add ("Code");
arrlist.Add ("Samples");
ListBox1.DataSource =arrlist ;
ListBox1.DataBind ();
ViewState["AList"] = arrlist ;
}

private void btnAsc_Click(object sender, System.EventArgs e)


{
((ArrayList)ViewState["AList"]).Sort() ;
ListBox1.DataSource =(ArrayList)ViewState["AList"] ;
ListBox1.DataBind ();
}

private void btnDesc_Click(object sender, System.EventArgs e)


{
((ArrayList)ViewState["AList"]).Sort() ;
((ArrayList)ViewState["AList"]).Reverse ();
ListBox1.DataSource =(ArrayList)ViewState["AList"] ;
ListBox1.DataBind ();
}

20.5 How to sort the DataGrid using an ArrayList as the DataSource?

<asp:DataGrid AllowSorting =True OnSortCommand="SortData" id="DataGrid1" runat="server"


EnableViewState="false"></asp:DataGrid>

VB.NET

Private Sub Page_Load(sender As Object, e As System.EventArgs)


' Put user code to initialize the page here
Dim arrlist As New ArrayList()
arrlist.Add("Tips")
arrlist.Add("Tricks")
arrlist.Add("Code")
arrlist.Add("Samples")
DataGrid1.DataSource = arrlist
DataGrid1.DataBind()
ViewState("AList") = arrlist
End Sub 'Page_Load

Protected Sub SortData([source] As [Object], e As


System.Web.UI.WebControls.DataGridSortCommandEventArgs)
If ViewState("SortOrder") Is Nothing Then
SortAsc()
Else
If ViewState("SortOrder").ToString() = " ASC" Then
SortDesc()
Else
SortAsc()
End If
End If
End Sub 'SortData

Sub SortAsc()
ViewState("SortOrder") = " ASC"
CType(ViewState("AList"), ArrayList).Sort()
DataGrid1.DataSource = ViewState("AList")
DataGrid1.DataBind()
ViewState("Sort") = "DESC"
End Sub 'SortAsc

Sub SortDesc()
ViewState("SortOrder") = " DESC"
CType(ViewState("AList"), ArrayList).Sort()
CType(ViewState("AList"), ArrayList).Reverse()
DataGrid1.DataSource = ViewState("AList")
DataGrid1.DataBind()
ViewState("Sort") = "ASC"
End Sub 'SortDesc

C#

private void Page_Load(object sender, System.EventArgs e)


{
// Put user code to initialize the page here
ArrayList arrlist = new ArrayList ();
arrlist.Add ("Tips");
arrlist.Add ("Tricks");
arrlist.Add ("Code");
arrlist.Add ("Samples");
DataGrid1.DataSource = arrlist ;
DataGrid1.DataBind ();
ViewState["AList"] = arrlist ;
}

protected void SortData(Object source, System.Web.UI.WebControls.DataGridSortCommandEventArgs e )


{
if (ViewState["SortOrder"] ==null)
{
SortAsc();
}
else if (ViewState["SortOrder"].ToString () == " ASC" )
{
SortDesc();
}
else
{
SortAsc();
}
}

void SortAsc()
{
ViewState["SortOrder"] = " ASC";
((ArrayList)ViewState["AList"]).Sort ();
DataGrid1.DataSource = ViewState["AList"];
DataGrid1.DataBind ();
ViewState["Sort"]="DESC";
}

void SortDesc()
{
ViewState["SortOrder"] = " DESC";
((ArrayList)ViewState["AList"]).Sort ();
((ArrayList)ViewState["AList"]).Reverse ();
DataGrid1.DataSource = ViewState["AList"];
DataGrid1.DataBind ();
ViewState["Sort"]="ASC";
}
21.1 How can I have the first item in the radiobuttonlist selected?

VB.NET

RadioButtonList1.Items(0).Selected = true
C#

RadioButtonList1.Items[0].Selected = true;

21.2 What is the difference between a series of RadioButton controls and


a series of Checkbox controls?

RadioButton control is designed to allow users to choose atleast one option from a list of available options.

Checkbox is designed to allow users to choose from zero to all options.

21.3 How can I enforce that only one radiobutton gets selected among a
list of Radiobutton controls?

Set same Groupname for the radiobutton controls

22.1 How to close the browser window on button control click?

Method 1. This will cause a postback on button click in response to which we will send some script to close

the window.

VB.NET
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles
Button1.Click
Response.Write("<script>window.close();</script>")
End Sub

C#
private void Button1_Click(object sender, System.EventArgs e)
{
Response.Write("<script>window.close();</script>");
}

Method 2. This is preferrable since there is no postback involved.

Use the Attribute collections i.e use Attributes of button control to add client side JavaScript code
VB.NET
Button1.Attributes.Add("OnClick", "window.close();")
C#
Button1.Attributes.Add("OnClick", "window.close();");

22.2 How to create server controls at runtime?

Here is an example of creating a HyperLink control in code.

VB.NET

Dim hpl As New HyperLink()


hpl.Text="Text"
hpl.NavigateUrl="http://www.syncfusion.com"'
hpl.ID="theID"
Page.Controls(1).Controls.Add(hpl)

C#
HyperLink hpl = new HyperLink();
hpl.Text="Text";
hpl.NavigateUrl="http://www.syncfusion.com";
hpl.ID="theID";
Page.Controls[1].Controls.Add(hpl);

22.3 How to change the text color of a linkbutton control?

<asp:LinkButton forecolor ="green" id="LinkButton1" runat="server">LinkButton</asp:LinkButton>

22.4 How to dynamically add validator controls?

VB.NET

Dim i As Integer = 1

'Textbox
Dim txtBox As TextBox = New TextBox
txtBox.ControlStyle.CssClass = "textbox"
txtBox.ID = "txtbox" + i.ToString()
'RequiredFieldValidator
Dim rqdVal As RequiredFieldValidator = New RequiredFieldValidator
rqdVal.ID = "rqdVal" + i.ToString()
rqdVal.ControlToValidate = "txtbox" + i.ToString()
rqdVal.ErrorMessage = "Please enter a value"
rqdVal.Display = ValidatorDisplay.Dynamic

'RangeValidator
Dim rngVal As RangeValidator = New RangeValidator
rngVal.ID = "rngVal" + i.ToString()
rngVal.MinimumValue = "1"
rngVal.MaximumValue = "100"
rngVal.ControlToValidate = "txtbox" + i.ToString()
rngVal.Type = ValidationDataType.Double
rngVal.ErrorMessage = " Value should be between 1 and 100"

'Add Controls on the page


Page.Controls(1).Controls.Add(txtBox)
Page.Controls(1).Controls.Add(rqdVal)
Page.Controls(1).Controls.Add(rngVal)

C#

int i=1;

//Textbox
TextBox txtBox = new TextBox();
txtBox.ControlStyle.CssClass = "textbox";
txtBox.ID = "txtbox" + i.ToString();

//RequiredFieldValidator
RequiredFieldValidator rqdVal = new RequiredFieldValidator();
rqdVal.ID = "rqdVal" + i.ToString();
rqdVal.ControlToValidate = "txtbox" + i.ToString();
rqdVal.ErrorMessage = "Please enter a value";
rqdVal.Display =ValidatorDisplay.Dynamic;

//RangeValidator
RangeValidator rngVal = new RangeValidator();
rngVal.ID = "rngVal" + i.ToString();
rngVal.MinimumValue = "1";
rngVal.MaximumValue = "100";
rngVal.ControlToValidate = "txtbox" + i.ToString();
rngVal.Type = ValidationDataType.Double;
rngVal.ErrorMessage = " Value should be between 1 and 100";

//Add Controls on the page


Page.Controls[1].Controls.Add (txtBox);
Page.Controls[1].Controls.Add (rqdVal);
Page.Controls[1].Controls.Add (rngVal);

22.5 How to change the image button size during runtime?

VB.NET
Dim x As New Unit("80px")
Dim y As New Unit("20px")
Dim imagestate as string= "stand"
If imagestate = "stand" then
imagebutton1.height = x
else
imagebutton1.height = y
end if

C#

Unit x = new Unit ("80px");


Unit y = new Unit("20px");
string imagestate="stand";
if( imagestate != "stand")
{
ImageButton1.Height = x;
}
else
{
ImageButton1.Height = y;
}

For more details Setting Web Server Control Properties Programmatically

22.6 How can I to divide the .aspx page to different parts with different
functionality in a neat and organized manner. Is there any control that
can do that?

You can use Panel controls, which render as HTML div elements. You can then show or hide the panels by

enabling/disabling them. In addition, you can specify different formatting options for different Panels/divs

using manual formatting or CSS styles.

22.7 How to maintain Scroll Position in any Page Element?

Check out Jim Ross's article Maintain Scroll Position in any Page Element

The article describes, when using a scrollable Datagrid--one inside an overflow-auto DIV control--how to

maintain the user's scroll position inside the DIV across postbacks. It does this using IE behaviors, HTC files.

22.8 DataBinder.Eval imposes performance penalty on code as it uses


late bound reflection. How can I replace this calls with explicit calls?
Change the Databinding Expression

<%#DataBinder.Eval (Container.DataItem , "StartDate" , "{0:c}")%>

to In VB.NET

<%#String.Format("{0:d}" , (CType(Container.DataItem, DataRowView))("StartDate"))%>

C#

<%#String.Format("{0:d}" , ((DataRowView)Container.DataItem)["StartDate"])%>

22.9 What is the difference between User Controls and Custom Controls?

User Controls are text files with the extension '.ascx' which enables you to make GUI re-usable controls. Its a

text file, which contains a mixture of HTML and scripting. User Controls can be edited in an editor.

On the other hand Custom Controls reside in compiled ( Dll ) assemblies. They are non-GUI but can emit

HTML GUI at runtime. Example of Custom Controls would be the sever controls which come bundled with the

.NET SDK like DataGrid, Repeater, DataList etc. Custom Controls are always compiled into Dll's and hence

require good programming knowledge. The purpose of Custom Controls is also to create re-usable units of

code.

22.10 How to apply Style to a Web Server control programmatically?

User Interface

<asp:TextBox id="TextBox1" style="Z-INDEX: 101; LEFT: 40px; POSITION: absolute; TOP: 64px"
runat="server">Syncfusion</asp:TextBox>
<asp:Button id="Button1" style="Z-INDEX: 102; LEFT: 48px; POSITION: absolute; TOP: 120px"
runat="server" Text="Button"></asp:Button>
<asp:CheckBox id="CheckBox1" style="Z-INDEX: 103; LEFT: 40px; POSITION: absolute; TOP: 200px"
runat="server" Text="Syncfusion"></asp:CheckBox>

VB.NET

Create a function
Protected Function createStyleForControl(ByVal _forecolor As Color, ByVal _backcolor As Color, ByVal
_fontbold As Boolean) As Style
Dim s As Style = New Style
s.ForeColor = _forecolor
s.BackColor = _backcolor
s.Font.Bold = _fontbold
Return s
End Function

In Page_Load

Dim textboxStyle As Style = createStyleForControl(Color.Pink, Color.Yellow, False)


Dim buttonStyle As Style = createStyleForControl(Color.Blue, Color.Teal, True)
Dim checkboxStyle As Style = createStyleForControl(Color.AliceBlue, Color.PowderBlue, False)

TextBox1.ApplyStyle(textboxStyle)
Button1.ApplyStyle(buttonStyle)
CheckBox1.ApplyStyle(checkboxStyle)

C#

Create a function

protected Style createStyleForControl(Color _forecolor ,Color _backcolor ,bool _fontbold )


{
Style s = new Style();
s.ForeColor = _forecolor;
s.BackColor =_backcolor;
s.Font.Bold = _fontbold;
return s;
}

In Page_Load

Style textboxStyle=createStyleForControl (Color.Pink , Color.Yellow ,false );


Style buttonStyle=createStyleForControl (Color.Blue , Color.Teal ,true );
Style checkboxStyle =createStyleForControl (Color.AliceBlue , Color.PowderBlue ,false );

TextBox1.ApplyStyle(textboxStyle );
Button1.ApplyStyle (buttonStyle );
CheckBox1.ApplyStyle (checkboxStyle );

22.11 How can I disable a button to prevent the user from multiple
clicking?

In the very last line of the button1_Click subroutine, add this line:
VB.NET

Button1.Enabled = False

C#

Button1.Enabled =false;

22.12 Why do I get the error message "Access is denied : <myctrl>"


when I try to load a Custom Control?

This is a common problem in ASP.NET. It happens because some program is scanning the Temporary ASP.NET

files folders where your assemblies are copied. They have the files open in a mode that prevents ASP.NET

itself from using the assembly file.

For solution refer PRB: Access Denied Error When You Make Code Modifications with Index Services Running

22.13 How to pass information between panels. Information entered in


one panel should be displayed in other panel?

<asp:Panel id="Panel1" runat="server" Width="271px" Height="41px">


<TABLE id="Table1" cellSpacing="1" cellPadding="1" width="300" border="1">
<TR>
<TD>
<P><asp:TextBox id="TextBox1" runat="server"></asp:TextBox></P>
</TD>
</TR>
<TR>
<TD>
<asp:Button id="Button1" runat="server" Text="Button"></asp:Button></TD>
</TR>
</TABLE>
</asp:Panel>
<asp:Panel id="Panel2" style="Z-INDEX: 102; LEFT: 16px; POSITION: absolute; TOP: 120px" runat="server"
Width="176px" Height="91px" Visible="False">
<asp:Label id="Label1" runat="server"></asp:Label>
</asp:Panel>

On Button Click

VB.NET

Panel2.Visible =true
Label1.Text = TextBox1.Text
C#

Panel2.Visible =true;
Label1.Text = TextBox1.Text ;

Note: Based on the criteria you can hide and show panels

22.14 Why do I get error message "The control '_ctl1' of type 'TextBox'
must be inside a form label with runat=server" while trying to place a
control inside a form dynamically?

You are probably adding the textbox into the Page directly instead of adding it to the Page's form. Try doing

this:

VB.NET

Me.Page.Controls(1).Controls.Add(txtboxctrl)

C#

this.Page.Controls[1].Controls.Add(txtboxctrl);

22.15 How to implement mouseover effects in a <asp:image> web server


control?

<asp:Image id="Image1" runat="server" ImageUrl="b2346.jpg"></asp:Image>

VB.NET

Image1.Attributes.Add("onmouseover", "this.src='b2456.jpg'")

C#

Image1.Attributes.Add("onmouseover", "this.src='b2456.jpg'");
22.16 Is there a way to set the position of the controls dynamically?

Yes.

<asp:Button id="Button1" style="Z-INDEX: 101; LEFT: 116px; POSITION: absolute; TOP: 152px"
runat="server"
Text="Move"></asp:Button>
<asp:RadioButtonList id="RadioButtonList1" style="Z-INDEX: 103; LEFT: 87px; POSITION: absolute; TOP:
27px"
runat="server" AutoPostBack="True">
<asp:ListItem Value="10px">10 pixels</asp:ListItem>
<asp:ListItem Value="100px">100 pixels</asp:ListItem>
<asp:ListItem Value="200px">200 pixels</asp:ListItem>
</asp:RadioButtonList>

VB.NET

Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load


' Put user code to initialize the page here
If Not Page.IsPostBack Then
Button1.Style.Add("LEFT", "1px")
End If
End Sub 'Page_Load

Private Sub RadioButtonList1_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As


System.EventArgs) Handles RadioButtonList1.SelectedIndexChanged
Button1.Style.Add("LEFT", RadioButtonList1.SelectedItem.Value.ToString())
End Sub 'RadioButtonList1_SelectedIndexChanged

C#

private void Page_Load(object sender, System.EventArgs e)


{
// Put user code to initialize the page here
if (!Page.IsPostBack )
{
Button1.Style.Add("LEFT", "1px");
}
}

private void RadioButtonList1_SelectedIndexChanged(object sender, System.EventArgs e)


{
Button1.Style.Add("LEFT",RadioButtonList1.SelectedItem.Value.ToString());
}
22.17 How can I set the maximum and minimum value for
RangeValidator based on two dates?

<asp:textbox id="TextBox1" runat="server"></asp:textbox>


<asp:rangevalidator id="RangeValidator1" type="Date" controltovalidate="TextBox1" runat="server"
errormessage="Not in range" />
<asp:button id="Button1" runat="server" text="Button"></asp:button>

VB.NET

...
Dim dtMinDate As DateTime
Dim dtMaxDate As DateTime
dtMinDate = Convert.ToDateTime("04/25/04")
dtMaxDate = Convert.ToDateTime("10/17/04")
RangeValidator1.MinimumValue = dtMinDate
RangeValidator1.MaximumValue = dtMaxDate
TextBox1.Text = dtMaxDate.ToShortDateString
RangeValidator1.ErrorMessage = "Not in Range of " & dtMinDate.ToShortDateString() & " to " &
dtMaxDate.ToShortDateString()

C#

DateTime dtMinDate ;
DateTime dtMaxDate ;
dtMinDate = Convert.ToDateTime("04/25/04");
dtMaxDate = Convert.ToDateTime("10/17/04");
RangeValidator1.MinimumValue = dtMinDate.ToShortDateString () ;
RangeValidator1.MaximumValue = dtMaxDate.ToShortDateString () ;
TextBox1.Text = dtMaxDate.ToShortDateString();
RangeValidator1.ErrorMessage = "Not in Range of " + dtMinDate.ToShortDateString() + " to " +
dtMaxDate.ToShortDateString();

22.18 How to specifiy the hspace and vspace in a <asp:Image>?

VB.NET

Image1.Attributes.Add("hspace", "50")
Image1.Attributes.Add("vspace", "50")

C#

Image1.Attributes.Add("hspace", "50") ;
Image1.Attributes.Add("vspace", "50") ;
22.19 How to disable status bar messages for Hyperlink Controls?

VB.NET

HyperLink1.Attributes.Add("onMouseOver", "window.status=' '; return true;")

C#

HyperLink1.Attributes.Add("onMouseOver", "window.status=' '; return true;") ;

22.20 How to get the list of all System.Web.UI.WebControls in my page?

<asp:Repeater runat="server" DataSource='<%# GetControls() %>' ID="Repeater1">


<HeaderTemplate>
<ul>
</HeaderTemplate>
<ItemTemplate>
<li>
<%# DataBinder.Eval(Container.DataItem, "Name") %>
</li>
</ItemTemplate>
<FooterTemplate>
</ul>
</FooterTemplate>
</asp:Repeater>

VB.NET

Protected Function GetControls() As ArrayList


Dim arrList As New ArrayList()
Dim t As Type
For Each t In GetType(Page).Assembly.GetTypes()
If t.Namespace = "System.Web.UI.WebControls" And GetType(Control).IsAssignableFrom(t) Then
arrList.Add(t)
End If
Next
Return arrList
End Function 'GetControls

'In Page_Load
DataBind()
C#

protected ArrayList GetControls()


{
ArrayList arrList = new ArrayList();
foreach (Type t in typeof(Page ).Assembly.GetTypes())
{
if (t.Namespace == "System.Web.UI.WebControls" && typeof(Control).IsAssignableFrom(t))
arrList.Add(t);
}
return arrList;
}

//In Page_Load
DataBind();

22.21 How to set the vertical align of a TableCell programmatically?

VB.NET

Dim tbl As New TableCell()


'VerticalAlign is enumeration in System.Web.UI.WebControls namespace
tbl.VerticalAlign = VerticalAlign.Top

C#

TableCell tbl=new TableCell();


//VerticalAlign is enumeration in System.Web.UI.WebControls namespace
tbl.VerticalAlign = VerticalAlign.Top;

22.22 How to control viewstate on individual controls?

You can set the EnableViewState property of the control. You should disable viewstate for any control that

doesn't use it to gurantee optimum performance.

23.1 How to create a table control dynamically to populate data?

<asp:Table id="Table1" runat="server"></asp:Table>


VB.NET

Dim mycn As SqlConnection


Dim myda As SqlDataAdapter
Dim ds As DataSet
mycn=NewSqlConnection("server=localhost;uid=sa;password=;database=northwind")
myda = New SqlDataAdapter("Select Employeeid, FirstName , LastName from employees", mycn)
ds = New DataSet
myda.Fill(ds, "Employees")

Dim dc As DataColumn
Dim dr As DataRow
For Each dr In ds.Tables(0).Rows
Dim trow As New TableRow
For Each dc In ds.Tables(0).Columns
Dim tcell As New TableCell
tcell.Controls.Add(New LiteralControl(dr(dc.ColumnName).ToString))
trow.Cells.Add(tcell)
Next
Table1.Rows.Add(trow)
Next

C#

SqlConnection mycn ;
SqlDataAdapter myda ;
DataSet ds ;
mycn=newSqlConnection("server=localhost;uid=sa;password=;database=northwind");
myda = new SqlDataAdapter("Select Employeeid, FirstName , LastName from employees", mycn);
ds = new DataSet();
myda.Fill(ds, "Employees");

TableRow trow ;
TableCell tcell;
foreach (DataRow dr in ds.Tables[0].Rows)
{
trow = new TableRow ();
foreach( DataColumn dc in ds.Tables[0].Columns)
{
tcell= new TableCell ();
tcell.Controls.Add(new LiteralControl(dr[dc.ColumnName].ToString()));
trow.Cells.Add(tcell);
}
Table1.Rows.Add(trow);
}

23.2 How to limit table cell size with long strings?

Set style property for the table cell as

style="WORD-BREAK:break-all"
23.3 How to use a Table control to display data vertically?

<asp:Table id="Table1" runat="server"></asp:Table>

VB.NET

'Populate the DataSet ds


Dim dr As DataRow
For Each dc In ds.Tables(0).Columns
Dim trow As New TableRow()
Dim tcellcolname As New TableCell()
'To Display the Column Names
For Each dr In ds.Tables(0).Rows
tcellcolname.Text = dc.ColumnName
trow.BackColor = System.Drawing.Color.Beige
tcellcolname.BackColor = System.Drawing.Color.AliceBlue
'Populate the TableCell with the Column Name
tcellcolname.Controls.Add(New LiteralControl(dc.ColumnName.ToString))
Next
trow.Cells.Add(tcellcolname)
'To Display the Column Data
For Each dr In ds.Tables(0).Rows
Dim tcellcoldata As New TableCell()
'Populate the TableCell with the Column Data
tcellcoldata.Controls.Add(New LiteralControl(dr(dc.ColumnName).ToString))
trow.Cells.Add(tcellcoldata)
Next
Table1.Rows.Add(trow)
Next

C#

//Populate the DataSet ds


foreach(DataColumn dc in ds.Tables[0].Columns )
{
TableRow trow = new TableRow();
TableCell tcellcolname = new TableCell() ;
foreach(DataRow dr in ds.Tables[0].Rows )
{
tcellcolname.Text = dc.ColumnName ;
trow.BackColor = System.Drawing.Color.Beige ;
tcellcolname.BackColor = System.Drawing.Color.AliceBlue ;
//Populate the TableCell with the Column Name
tcellcolname.Controls.Add(new LiteralControl(dc.ColumnName.ToString())) ;
}
trow.Cells.Add(tcellcolname) ;
//To Display the Column Data
foreach(DataRow dr in ds.Tables[0].Rows )
{
TableCell tcellcoldata =new TableCell() ;
//Populate the TableCell with the Column Data
tcellcoldata.Controls.Add(new LiteralControl(dr[dc.ColumnName].ToString())) ;
trow.Cells.Add(tcellcoldata);
}
Table1.Rows.Add(trow) ;
}

23.4 Are there any IE specific performance imporvement possible with


Table Layout?

In IE5 and later, significantly faster Table Rendering is now possible. Here is some information in MSDN :

Enhancing Table Presentation.

Among other things, you can specific col specific widths using the colgroup tag or col tag and also set the

visibility of rows and columns using special styles.

24.1 Why does my page show up poorly in Mozilla based browsers like
Netscape and Firefox?

The .Net framework recognizes the capabilities of the latest version of the above browsers poorly. This is

because, by default, the BrowserCaps section of the machine.config file (usually found under a folder like

"C:\WINDOWS\Microsoft.NET\Framework\v1.1.4322\CONFIG") declares the capabilities of the Mozilla based

browser poorly. So, you will have to replace the default entry in your install with this one: Mozilla

BrowserCaps .

In case the above link didn't work, this is the content from the above link, captured as of (4/10/2005):

<browserCaps>

<!--
Name: BrowserCaps update for modern browsers,
http://slingfive.com/pages/code/browserCaps/
Author: Rob Eberhardt, http://slingfive.com/
History:
2004-11-19 improved detection of Safari, Konqueror & Mozilla variants, added Opera detection
2003-12-21 updated TagWriter info
2003-12-03 first published
-->

<!-- GECKO Based Browsers (Netscape 6+, Mozilla/Firefox, ...) //-->


<case match="^Mozilla/5\.0 \([^)]*\) (Gecko/[-\d]+)(?'VendorProductToken'
(?'type'[^/\d]*)([\d]*)/(?'version'(?'major'\d+)(?'minor'\.\d+)(?'letters'\w*)))?">
browser=Gecko
<filter>
<case match="(Gecko/[-\d]+)(?'VendorProductToken'
(?'type'[^/\d]*)([\d]*)/(?'version'(?'major'\d+)(?'minor'\.\d+)(?'letters'\w*)))">
type=${type}
</case>
<case>
type=Mozilla
</case>
</filter>
frames=true
tables=true
cookies=true
javascript=true
javaapplets=true
ecmascriptversion=1.5
w3cdomversion=1.0
css1=true
css2=true
xml=true
tagwriter=System.Web.UI.HtmlTextWriter
<case match="rv:(?'version'(?'major'\d+)(?'minor'\.\d+)(?'letters'\w*))">
version=${version}
majorversion=0${major}
minorversion=0${minor}
<case match="^b" with="${letters}">
beta=true
</case>
</case>
</case>

<!-- AppleWebKit Based Browsers (Safari...) //-->


<case match="AppleWebKit/(?'version'(?'major'\d?)(?'minor'\d{2})(?'letters'\w*)?)">
browser=AppleWebKit
version=${version}
majorversion=0${major}
minorversion=0.${minor}
frames=true
tables=true
cookies=true
javascript=true
javaapplets=true
ecmascriptversion=1.5
w3cdomversion=1.0
css1=true
css2=true
xml=true
tagwriter=System.Web.UI.HtmlTextWriter
<case match="AppleWebKit/(?'version'(?'major'\d)(?'minor'\d+)(?'letters'\w*))(.* )?
(?'type'[^/\d]*)/.*( |$)">
type=${type}
</case>
</case>

<!-- Konqueror //-->


<case match=".+[K|
k]onqueror/(?'version'(?'major'\d+)(?'minor'(\.[\d])*)(?'letters'[^;]*));\s+(?'platform'[^;\)]*)(;|\))">
browser=Konqueror
version=${version}
majorversion=0${major}
minorversion=0${minor}
platform=${platform}
type=Konqueror
frames=true
tables=true
cookies=true
javascript=true
javaapplets=true
ecmascriptversion=1.5
w3cdomversion=1.0
css1=true
css2=true
xml=true
tagwriter=System.Web.UI.HtmlTextWriter
</case>
<!-- Opera //-->
<case match="Opera[ /](?'version'(?'major'\d+)(?'minor'\.(?'minorint'\d+))(?'letters'\w*))">
<filter match="[7-9]" with="${major}">
tagwriter=System.Web.UI.HtmlTextWriter
</filter>
<filter>
<case match="7" with="${major}">
<filter>
<case match="[5-9]" with="${minorint}">
ecmascriptversion=1.5
</case>
<case>
ecmascriptversion=1.4
</case>
</filter>
</case>
<case match="[8-9]" with="${major}">
ecmascriptversion=1.5
</case>
</filter>
</case>

</browserCaps>
25.1 Why do I get the Columns twice in the datagrid. I am using
BoundColumns and TemplateColumns in DataGrid?

Set the AutogenerateColumns= False. By Default it is set to true for a datagrid

25.2 How to Format and display currency with n decimal points in a


BoundColumn.

Set the Dataformatstring of the boundcolumn to {0:Nn} where n=> number of decimal points For more

details refer Format Function

25.3 How do I specify more than one parameter for my


HyperlinkColumn?

<asp:DataGrid id="DataGrid1" runat="server" AutoGenerateColumns="False">


<Columns>
<asp:TemplateColumn HeaderText="Sample Column">
<ItemTemplate>
<asp:Hyperlink runat="server" Text='<%#DataBinder.Eval(Container.DataItem,
"ProductName").ToString()%>' NavigateUrl='<%# "page1.aspx?id=" +
DataBinder.Eval(Container.DataItem,"ProductId").ToString() + "&Name=" +
DataBinder.Eval(Container.DataItem,"ProductName").ToString()%>' ID="Hyperlink1" NAME="Hyperlink1"/>
</ItemTemplate>
</asp:TemplateColumn>
</Columns>
</asp:DataGrid>

25.4 Why am I getting an 'AllowCustomPaging must be true and


VirtualItemCount must be set for a DataGrid with ID MyDataGrid when
AllowPaging is set to true and the selected datasource does not
implement ICollection' Error?
You are probably trying to implement paging in a DataGrid while binding the DataGrid with a DataReader. To

fix this, instead of using a DataReader use a DataSet

25.5 How do I use a "helper function" to change the column value as


Boolean in database to be displayed as Yes/No in Datagrid?

<asp:DataGrid id="DataGrid1" runat="server" AutoGenerateColumns="False">


<Columns>
<asp:TemplateColumn HeaderText="Status">
<ItemTemplate>
<%#ShowStatus(bool.Parse(DataBinder.Eval(Container.DataItem,"Discontinued").ToString()))%>
</ItemTemplate>
</asp:TemplateColumn>
</Columns>
</asp:DataGrid>

VB.NET

protected Function ShowStatus(ByVal someval as boolean)


If someval = true Then
ShowStatus = "Yes"
Else
ShowStatus = "No"
End If
End Function

C#

protected string ShowStatus(bool someval)


{
if (someval == true)
{
return "Yes";
}
else
{
return "No";
}
}

25.6 How to display only date part in the Datagrid if the Date is of
DateTime datatype in the database?

Set the DateFormatString as {0:d}

25.7 How to open a new window with multiple parameters when clicked
on a hyperlink in a column in a datagrid?
The column should be defined as a TemplateColumn as follows and the NavigateUrl for that hyperlink can be

set as follows to open a new window with parameters varying based on the row in which the hyperlink is

present.

<asp:TemplateColumn >
<ItemTemplate>
<asp:Hyperlink ID="Hyperlink2" Runat="Server"
NavigateUrl= <%#"javascript:my_window=window.open('webform2.aspx?id=" +
DataBinder.Eval(Container.DataItem,"productid").ToString() + "&Supplierid=
"+DataBinder.Eval(Container.DataItem,"SupplierID").ToString()+"','my_window','width=300,height=300');my_window.foc
%>
text=<%#DataBinder.Eval(Container.DataItem,"ProductName").ToString() %>>
</asp:Hyperlink>
</ItemTemplate>
</asp:TemplateColumn>

The above approach would avoid the problem of showing the screen of [Object] on the parent page

25.8 How to display hierarchical data in a DataGrid?

Check out Denis Bauer's custom control HierarGrid

25.9 How do I conditionally set the text color of a cell in my Datagrid


based on the cell's/fields's value?

In the ItemDataBound event you can access the Cells() collection of the current Datagrid item (or row) and

set it's ForeColor.

<asp:DataGrid OnItemDataBound="ItemDB" id="DataGrid1" runat="server"></asp:DataGrid>

VB.NET

protected Sub ItemDB(ByVal sender As Object, ByVal e As


System.Web.UI.WebControls.DataGridItemEventArgs)
If (e.Item.ItemType = ListItemType.Item Or _
e.Item.ItemType = ListItemType.AlternatingItem) Then
If e.Item.DataItem(6) > 15 Then
e.Item.Cells(6).ForeColor = System.Drawing.Color.Green
Else
e.Item.Cells(6).ForeColor = System.Drawing.Color.Red
End If
End If
End Sub

C#

protected void ItemDB(object sender, System.Web.UI.WebControls.DataGridItemEventArgs e)


{
if((e.Item.ItemType ==ListItemType.Item) || (e.Item.ItemType == ListItemType.AlternatingItem) )
{
if (Convert.ToInt16 (e.Item.Cells[6].Text) >15 )
{
e.Item.Cells[6].ForeColor = System.Drawing.Color.Green;
}
else
{
e.Item.Cells[6].ForeColor = System.Drawing.Color.Red;
}
}
}

In Cells[x]/Cells(x) x=> index number to the list of fields in the row.

25.10 When I open my new window using Javascript, all elements


appear great, but the original window just displays [Object] why?

Check out How to open a new window with multiple parameters using datagrid?

26.1 Why doesn't my properties tagged with the


PersistenceMode.InnerProperty attribute get saved in the aspx file?

All string type properties get saved as attributes of the parent tag inspite of the InnerProperty attribute

setting. In fact, setting the InnerProperty attribute might prevent the property from getting saved at all.

For example, in the property declaration below:

[C#]
[
Category("Appearance"),
NotifyParentProperty(true),
PersistenceMode(PersistenceMode.Attribute), // This should always be Attribute, not anything else like
InnerProperty.
]
public string Text{get{return text;}set{text = value;}}

26.2 Why doesn't changes made to some of my properties don't get


saved in the aspx file during design time?

Nested properties in your controls should be marked with the NotifyParentProperty(true) attribute in

order for the designer to get notified that it's value has changed.

For example, the following property (SubProperty) declaration should include the above mentioned attribute,

for the designer to persist changes to that property during design-time:

myControl.SomeComplexProperty.SubProperty = "some value";

26.3 Why doesn't my Collection Properties get saved in the aspx file
properly during design-time?
Some common mistakes that will cause the designer to choke while persisting collection properties are:

The corresponding collection type cannot have multiple (overloaded) indexers. You should always define a

single indexer of the type "public SomeType this[object obj]{...}". Otherwise the changes will be persisted

but the control will not load in the designer. You will see a "Ambiguous match found" error. If the colleciton

property has the PersistenceMode attribute set to InnerProperty then the property should not include a set

method.

27.1 How do I insert custom @ Register tags into the aspx file from my
custom control?

In the custom control's custom designer's Initialize override, do something like this:

[C#]
public override void Initialize(IComponent component)
{

base.Initialize (component);

IDesignerHost host = component.Site.Container as IDesignerHost;


IDesigner designer = host.GetDesigner(host.RootComponent);

// Calling GetHTMLFromWebControlTool with the following custom toolboxitem will insert the
// Register directives for the type associated with that .
MethodInfo mi = designer.GetType.GetMethod("GetHTMLFromWebControlTool", BindingFlags.NonPublic |
BindingFlags.Instance);
if(mi != null)
{
// DependantType is a custom type defined in DependantAssembly.dll
mi.Invoke(designer, new object[]{new
WebControlToolboxItem(typeof(SomeNamespace.DependantType))});
}
}

C Then when the user drags and drops the item from the toolbox, besides the default @ register entry it

makes, it will also make an entry like this: <%@ Register TagPrefix="cc1" Namespace="SomeNamespace"

Assembly="DependantAssembly, Version=2.0.0.1, Culture=neutral, PublicKeyToken=3d6dfsd1fdsd44c89" %>

The assembly will not be strong named in the above tag if it's not in the GAC.

28.1 How to cast the value entered in a textbox to integer?

VB.NET
Int32.Parse(TextBox1.Text)

C#

Int32.Parse(TextBox1.Text);

28.2 How to allow only numeric values in a textbox using ASP.NET


Validator control?

<asp:TextBox id="txtNumber" Runat="server" />


<asp:RegularExpressionValidator ID="vldNumber" ControlToValidate="txtNumber" Display="Dynamic"
ErrorMessage="Not a number" ValidationExpression="(^([0-9]*|\d*\d{1}?\d*)$)" Runat="server">
</asp:RegularExpressionValidator>

28.3 Why does TextBox retain its values when posting inspite of having
ViewState property disabled for TextBox,?

Refer to Teemu Keiski's blog ASP.NET: TextBox and EnableViewState="False"

28.4 I am running the query SQL="Select name from profile where


proID=1"; and I am getting the result in Dataset dsdata. How can I read
the text from the dataset and assign it to textbox1.text ?

VB.NET

Textbox1.Text= dsData.Tables(0).Rows(0)("FieldName").ToString()

C#

TextBox1.Text=dsData.Tables[0].Rows[0]["FieldName"].ToString();

28.5 How to align the Text property of the Textbox Control?

VB.NET

TextBox1.Style("text-align")="right"

C#

TextBox1.Style["text-align"]="right";

28.6 Why do I get error message "Option Strict On disallows implicit


conversions from 'System.Web.UI.Control' to
'System.Web.UI.WebControls.TextBox'."?
For type Casting apply the following steps

VB.NET

dim aprtxt as string


aprtxt= CType(e.Item.FindControl("txtapr"), TextBox)

C#

string aprtxt;
aprtxt = (TextBox) e.Item.FindControl["txtapr"];

28.7 How to convert TextBox value into a DateTime variable?

VB.NET

Dim dt As DateTime = DateTime.Parse(TextBox1.Text)

C#

DateTime dt = DateTime.Parse(TextBox1.Text);

By default Date.Parse check the date as MDY format Refer DateTime.Parse for a specified Date Format.

28.8 How to clear all the textboxes in my form?

VB.NET

Dim ctl As Control


For Each ctl In Page.Controls(1).Controls
If TypeOf ctl Is TextBox Then
CType(ctl, TextBox).Text = ""
End If
Next

C#

foreach (Control ctl in Page.Controls[1].Controls )


{
TextBox tb = ctl as TextBox;
if (tb!=null)
{
tb.Text = "" ;
}
}
Note: Page.Controls[1]=> control is within the form tag

28.9 How to programmatically set the width of the textbox control?

VB.NET

TextBox1.Width = Unit.Pixel(100)

C#

TextBox1.Width = Unit.Pixel(100);

28.10 How to get the textbox value at the client side ?

<script lang="javascript">
function CheckFunction()
{
if (document.getElementById('<%=textbox2.ClientID%>').value == "")
{
alert("Please enter a value");
return;
}
}
</script>

<asp:textbox id="textbox2" runat="Server"></asp:textbox>


<input type=button id="btn1" onclick="javascript:CheckFunction();" value="Click">

28.11 How to display data in Textboxes using DataSet?

Product ID : <asp:TextBox id="TextBox1" style="Z-INDEX: 101; LEFT: 80px; POSITION: absolute; TOP:
64px" runat="server"></asp:TextBox>
Product Name:<asp:TextBox id="TextBox2" style="Z-INDEX: 102; LEFT: 80px; POSITION: absolute; TOP:
112px" runat="server"></asp:TextBox>

VB.NET

'Populate the DataSet


'...

'Display in TextBoxes using Column Name


TextBox1.Text = ds.Tables (0).Rows(0)("ProductId").ToString ();
TextBox2.Text =ds.Tables (0).Rows(0)("ProductName").ToString ();

'Display in TextBoxes using Column Index


TextBox1.Text = ds.Tables (0).Rows(0)(0).ToString ();
TextBox2.Text =ds.Tables (0).Rows(0)(1).ToString ();

C#

//Populate the DataSet


//...

//Display in TextBoxes using Column Name


TextBox1.Text = ds.Tables [0].Rows[0]["ProductId"].ToString ();
TextBox2.Text =ds.Tables [0].Rows[0]["ProductName"].ToString ();

//Display in TextBoxes using Column Index


TextBox1.Text = ds.Tables [0].Rows[0][0].ToString ();
TextBox2.Text =ds.Tables [0].Rows[0][1].ToString ();

28.12 How to display data in Textboxes using DataReader?

Id : <asp:TextBox id="TextBox1" style="Z-INDEX: 102; LEFT: 128px; POSITION: absolute; TOP: 32px"
runat="server"></asp:TextBox>
Name : <asp:TextBox id="TextBox2" style="Z-INDEX: 103; LEFT: 128px; POSITION: absolute; TOP: 72px"
runat="server"></asp:TextBox>

VB.NET

Dim cn As SqlConnection
Dim cmd As SqlCommand
Dim rdr As SqlDataReader

Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load


' Put user code to initialize the page here
Try
cn=NewSqlConnection("server=localhost;uid=sa;pwd=;database=northwind")
cmd = New SqlCommand("select * from Products where productid =1", cn)
cn.Open()
rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection)
rdr.Read()
TextBox1.Text = rdr("ProductId").ToString()
TextBox2.Text = rdr("ProductName").ToString()
Catch ex As Exception
Response.Write(ex.Message.ToString())
Finally
rdr.Close()
cn.Close()
End Try
End Sub

C#

SqlConnection cn ;
SqlCommand cmd ;
SqlDataReader rdr ;
private void Page_Load(object sender, System.EventArgs e)
{
// Put user code to initialize the page here
try
{
cn=newSqlConnection("server=localhost;uid=sa;pwd=;database=northwind");
cmd = new SqlCommand( "select * from Products where productid=1 ", cn);
cn.Open();
rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection );
rdr.Read ();
TextBox1.Text =rdr["ProductId"].ToString ();
TextBox2.Text =rdr["ProductName"].ToString ();
}
catch (Exception ex)
{
Response.Write (ex.Message.ToString ());
}
finally
{
rdr.Close();
cn.Close();
}
}

28.13 Is there a TextArea in ASP.NET?

You can use the TextBox webserver control and set the TextMode = MultiLine

28.14 How to right align the text in the TextBox?

<asp:TextBox id="TextBox1" dir=rtl runat="server"></asp:TextBox>

28.15 How to force the max no. of lines in a multiline TextBox using
RegularExpressionValidator?

<asp:TextBox id="TextBox1" style="Z-INDEX: 101; LEFT: 0px; POSITION: absolute; TOP: 112px"
runat="server" TextMode="MultiLine"></asp:TextBox>
<asp:RegularExpressionValidator id="RegularExpressionValidator1" style="Z-INDEX: 102; LEFT: 216px;
POSITION: absolute; TOP: 112px"
runat="server" ErrorMessage="MaxLength is 20" ControlToValidate="TextBox1"
ValidationExpression="^\w{1,20}$">
</asp:RegularExpressionValidator>

28.16 How to change server control backcolor from a variable?

<asp:TextBox id="TextBox1" BackColor =<%#colCon.ConvertFromString(bgcolor)%> runat="server">


</asp:TextBox>

VB.NET
Protected colCon As New System.Drawing.ColorConverter
Protected bgcolor As String = "#556600"

'In Page_Load
Page.DataBind()

C#

protected System.Drawing.ColorConverter colCon =new System.Drawing.ColorConverter();


protected string bgcolor = "#556600";

//In Page_Load
Page.Databind();

28.17 How to create an array of Web Controls?

<asp:PlaceHolder id="PlaceHolder1" runat="server"></asp:PlaceHolder>

VB.NET

Dim textboxes(5) As TextBox


Dim i As Integer
For i = 0 To 4
textboxes(i) = New TextBox()
textboxes(i).ID = "TextBox" + i
textboxes(i).AutoPostBack = True
PlaceHolder1.Controls.Add(textboxes(i))
Next

C#

TextBox[] textboxes = new TextBox[5];


for (int i=0; i<5; i++)
{
textboxes[i] = new TextBox();
textboxes[i].ID = "TextBox" + i;
textboxes[i].AutoPostBack = true;
PlaceHolder1.Controls.Add(textboxes[i]);
}

28.18 How to show TextBox web server control with TextMode Property
Password as **** rather than blank?
For security reason, TextBox with TextMode="Password" setting cannot be assigned or populated via the Text

property on Page_Load or PostBack event.

It's not recommend for to prefill a "Password" type TextBox with the("***") characters, though below is the

solution to achieve this.

VB.NET

ViewState("Pwd")=TextBox1.Text ;
TextBox1.Attributes.Add("value", ViewState("Pwd").ToString ()) ;

C#

ViewState["Pwd"]=TextBox1.Text ;
TextBox1.Attributes.Add("value", ViewState["Pwd"].ToString ()) ;
29.1 I have 3 DropDownLists on the page : one for a Month, second one
for a Day, and the last one for a Year. How can I let the user choose the
data and enter it to 'datetime' column in the database.

VB.NET

Dim dt as DateTime = DateTime.Parse(ddlMonth.SelectedItem.Text & "/" & ddlDay.SelectedItem.Text & "/" &
ddlYear.SelectedItem.Text )

C#

DateTime dt = DateTime.Parse(ddlMonth.SelectedItem.Text & "/" & ddlDay.SelectedItem.Text & "/" &


ddlYear.SelectedItem.Text );

29.2 How to apply css style to each item of the dropdownlist or listbox
control?

The dropDownList has a bug which prevent us from assigning the style property to each item in the

DropDownList. This bug confirmed by Microsoft in Microsoft Knowledge Base Article - 309338 For the

workaround use a HTML dropdownlist with runat=server tag

<SELECT id="DropDownList1" runat="server" >


</SELECT>

Use namespace System.Reflection VB.NET

If Not Page.IsPostBack Then


Dim col As FieldInfo
For Each col In GetType(KnownColor).GetFields
If col.FieldType Is GetType(Drawing.KnownColor) Then
DropDownList1.Items.Add(New ListItem(col.Name, col.Name))
End If
Next
End If

Dim i As Integer
For i = 0 To DropDownList1.Items.Count - 1
DropDownList1.Items(i).Attributes.Add("style", "background-color:" + DropDownList1.Items(i).Text)
Next

C#

if (!IsPostBack)
{
foreach(FieldInfo col in typeof(KnownColor).GetFields() )
{
if (col.FieldType == typeof(KnownColor) )
{
DropDownList1.Items.Add(new ListItem(col.Name ,col.Name));
}
}
}
for (int i= 0 ;i < DropDownList1.Items.Count;i++)
{
DropDownList1.Items[i].Attributes.Add("style", "background-color:" + DropDownList1.Items[i].Text);
}

29.3 How to concate and display 2 fields in a dropdownlist?

Method1

"Select FirstName + ' ' + LastName as fullname from Employees"

then use 'fullname' as the datatextfield for the dropdownlist

Method2

Dim newColumn As New DataColumn()


With newColumn
.ColumnName = "fullname"
.DataType = System.Type.GetType("System.String")
.Expression = "LastName+' '+FirstName"
End With
ds.Tables(0).Columns.Add(newColumn)
ddlName.DataTextField = "FullName"
ddlName.DataValueField = "employeeid"
ddlName.DataSource = ds.Tables(0).DefaultView
ddlName.DataBind()
C#

DataColumn newColumn =new DataColumn();


newColumn.ColumnName = "fullname";
newColumn.DataType = System.Type.GetType("System.String");
newColumn.Expression = "LastName+' '+FirstName";
ds.Tables[0].Columns.Add(newColumn);
DropDownList1.DataTextField = "FullName";
DropDownList1.DataValueField = "employeeid";
DropDownList1.DataSource = ds.Tables[0].DefaultView;
DropDownList1.DataBind();

29.4 I have a page with a Dropdownlist and some simple code for the
SelectedIndexChanged but it does not do a postback?

If you want the dropdownlist to cause a postback when selection changes set AutoPostBack property to "True"

for the dropdownlist control.

29.5 How to add an extra item to the DropDownList filled with data from
a database?

VB.NET

'DropDownList1.Items.Insert(0, "Please Select")


DropDownList1.Items.Insert(0, new ListItem("<text>", "<value>"))

C#

//DropDownList1.Items.Insert(0, "Please Select");


DropDownList1.Items.Insert(0, new ListItem("<text>", "<value>"));

This should be done after .DataBind of dropdownlist

29.6 Can I use a dropdownlist to allow user to select multiple items from
a list of available items?

No. Dropdownlist Web Control allows user to select only one item from a list of items.

29.7 Why do I get


System.Data.DataRowView/System.Data.Common.DbDataRecord as the
item in a dropdownlist?

This is probably because you have not set the DataTextField/ DatavalueField property of the dropdownlist.

VB.NET

'..
DropDownList1.DataSource = ds.Tables(0)
DropDownList1.DataTextField = "CategoryName"
DropDownList1.DataValueField = "CategoryId"
DropDownList1.DataBind()

C#

//..
DropDownList1.DataSource =ds.Tables[0];
DropDownList1.DataTextField = "CategoryName";
DropDownList1.DataValueField = "CategoryId";
DropDownList1.DataBind();

29.8 How can I display a Tool tip for a dropdownlist?

The ToolTip property is inherited from the WebControl class and is not applicable to the DropDownList control.

This implementation of the ToolTip property does not allow you to set a value and returns String. In a word, if

we can make this (a dropdown with ToolTip) work with plain HTML and client side script, we should be able to

emit the necessary code from ASP.NET.

More Details at DropDownList.ToolTip Property

29.9 How to select a specific Item in a DropDownList?

Method 1: VB.NET

DropDownList1.SelectedIndex = DropDownList1.Items.IndexOf(DropDownList1.Items.FindByValue(<value>))
'DropDownList1.SelectedIndex = DropDownList1.Items.IndexOf(DropDownList1.Items.FindByText(<Text>))

C#

DropDownList1.SelectedIndex =
DropDownList1.Items.IndexOf(DropDownList1.Items.FindByValue(<value>));
//DropDownList1.SelectedIndex = DropDownList1.Items.IndexOf(DropDownList1.Items.FindByText(<Text>));

Method 2: VB.NET

DropDownList1.Items.FindByText("<Text>").Selected = true
'DropDownList1.Items.FindByValue("<value>").Selected = true

C#

DropDownList1.Items.FindByText("<Text>").Selected = true ;
//DropDownList1.Items.FindByValue("<value>").Selected = true ;

29.10 How to display multiple spaces in a dropdownlist?


<asp:DropDownList id="DropDownList1" runat="server"></asp:DropDownList>

VB.NET

Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load


'Put user code to initialize the page here
Dim i As Integer
For i = 0 To 10
DropDownList1.Items.Add("Item Number" + SpaceDDL(10) + i.ToString)
Next
End Sub

Private Function SpaceDDL(ByVal numberOfSpaces As Integer) As String


Dim Spaces As String
Dim i As Integer
For i = 0 To numberOfSpaces
Spaces &= " "
Next
Return Server.HtmlDecode(Spaces)
End Function

C#

private void Page_Load(object sender, System.EventArgs e)


{
// Put user code to initialize the page here
for(int i = 0 ;i<=10;i++)
{
DropDownList1.Items.Add("Item Number" + SpaceDDL(10) + i.ToString());
}
}

string SpaceDDL(int numberOfSpaces )


{
string Spaces="";
for(int i = 0 ;i<=numberOfSpaces;i++)
{
Spaces += " ";
}
return Server.HtmlDecode(Spaces);
}
30.1 What is the best place to store Database connection string?

In Web.Config, you would add a key to the AppSettings Section:

<appSettings>
<addkey="MyDBConnection"value="server=<ServerName>;uid=<Username>;pwd=
;database=<DBName>" />
</appSettings>

Example :
<addkey="ConnectionString"value="Server=localhost;uid=sa;pwd=;database=northwind" />

Then, in your ASP.Net application - just refer to it like this:

Dim myConnection As SqlConnection = New


SqlConnection(ConfigurationSettings.AppSettings("ConnectionString"))

30.2 My web.config gives error "Unrecognized attribute 'verb'."?

Probably you have mispelled the attribute. It should be verbs not verb

30.3 Can I use IIS as an alternative way of configuring Custom error


pages?

Yes, you can. But the preferable way would be ASP.NET, as the ASP.NET custom pages are configured in XML

based web.config (application configuration) file, resulting in easy (xcopy) deployment and management.

31.1 What is the Performance comparison between DataSet and


DataReader?

Refer Performance Comparison: Data Access Techniques

31.2 How to get the count of records in the Database table using the
DataSet?

VB.NET

ds.Tables(0).Rows.Count

C#

ds.Tables[0].Rows.Count ;

31.3 How to check if the Dataset has records?

VB.NET

if ds.Tables(0).Rows.Count= 0 then
'No record
else
'Record Found
end if
C#

if (ds.Tables[0].Rows.Count == 0 )
{
//No record
}
else
{
//Record Found
}

31.4 How to retrieve value of a field in a dataset?

VB.NET

ds.Tables("TableName").Rows(0)("ColumnName")

C#

ds.Tables["TableName"].Rows[0]["ColumnName"];

where TableName and ColumnName could be also integer (not in quotes then) to indicate you refer to the

table's or column's index position. Rows(0) indicates the first and only row in DataTable's Rows collection

31.5 How to filter the data in the DataView and display it in some
DataControl?

VB.NET

Dim thefilter as string = "fieldname=' ' "


dbDataView.RowFilter = thefilter
Repeater1.DataSource = dbDataView
Repeater.DataBind()

C#

string thefilter = "fieldname=' ' ";


dbDataView.RowFilter = thefilter;
Repeater1.DataSource = dbDataView;
Repeater.DataBind();

31.6 How to truncate the data in the column?

VB.NET

Protected function TruncateData( Byval strNotes as string)


If strNotes.Length > 20 then
Return strNotes.Substring(0,20) + "..."
Else
return strnotes
End function

C#

protected string TruncateData( string strNotes )


{
if (strNotes.Length > 20)
{
return strNotes.Substring(0,20) + "...";
}
else
{
return strNotes;
}
}

31.7 How to find the null fields in the datareader?

VB.NET

If dbReader("fieldname").Tostring= DBnull.Value.ToString()
'Empty field value
Else
'Display value
End if

C#

if (dbReader["fieldname").ToString() == DBNull.Value.ToString() )
{
//Empty field value
}
else
{
//display Value
}

31.8 How to Implement a DataSet SELECT DISTINCT Helper Class?

VB.NET

Sample code 1

C#

Sample Code 2

31.9 I am running the query SQL="Select name from profile where


proID=1"; and I am getting the result in Dataset dsdata. Now how do I
read the text from the dataset and assign it to textbox1.text ?

VB.NET

dsData.Tables(0).Rows(0)("FieldName").ToString()

C#

dsData.Tables[0].Rows[0]["FieldName"].ToString()

31.10 How to query the database to get all the Table names?

SELECT * FROM information_schema.tables where Table_type='BASE TABLE'

31.11 How to View one record per page in ASP.NET?

<asp:label id="Label2" style="Z-INDEX: 106; LEFT: 111px; POSITION: absolute; TOP: 83px"
runat="server">Product ID</asp:label>
<asp:label id="Label1" style="Z-INDEX: 105; LEFT: 110px; POSITION: absolute; TOP: 43px"
runat="server">Product Name</asp:label>
<asp:textbox id="txtProductName" style="Z-INDEX: 104; LEFT: 206px; POSITION: absolute; TOP: 83px"
runat="server" OnDataBinding="txtDataBind"></asp:textbox>
<asp:textbox id="txtProductid" style="Z-INDEX: 103; LEFT: 204px; POSITION: absolute; TOP: 43px"
runat="server">
<asp:button id="btnPrevious" style="Z-INDEX: 102; LEFT: 137px; POSITION: absolute; TOP: 126px"
runat="server" Text="Previous" OnClick ="PrevBtn"></asp:button>
<asp:button id="btnNext" style="Z-INDEX: 101; LEFT: 243px; POSITION: absolute; TOP: 126px"
runat="server" Text="Next" OnClick ="NextBtn"></asp:button>

VB.NET

Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load


'Put user code to initialize the page here
Try
'Fill the DataSet
If Not Page.IsPostBack Then
ViewState("CurrentPos") = 0
Me.DataBind()
End If
Catch ex As Exception
Response.Write(ex.Message & ex.StackTrace)
End Try
End Sub

protected Sub NextBtn(ByVal sender As System.Object, ByVal e As System.EventArgs)


Try
Dim CurrentPos As Integer = CType(ViewState("CurrentPos"), Integer)
CurrentPos += 1
If CurrentPos > ds.Tables(0).Rows.Count Then
CurrentPos -= 1
End If
ViewState("CurrentPos") = CurrentPos
Me.DataBind()
Catch ex As Exception
Response.Write(ex.Message)
End Try
End Sub

protected Sub PrevBtn(ByVal sender As System.Object, ByVal e As System.EventArgs)


Try
Dim CurrentPos As Integer = CType(ViewState("CurrentPos"), Integer)
If CurrentPos > 0 Then
CurrentPos -= 1
End If
ViewState("CurrentPos") = CurrentPos
Me.DataBind()
Catch ex As Exception
Response.Write(ex.Message)
End Try
End Sub

protected Sub txtDataBind(ByVal sender As Object, ByVal e As System.EventArgs)


Try
Dim CurrentPos As Integer = CType(ViewState("CurrentPos"), Integer)
ViewState("CurrentPos") = (CurrentPos)
txtProductid.Text = ds.Tables(0).Rows(CurrentPos).Item("productid")
txtProductName.Text = ds.Tables(0).Rows(CurrentPos).Item("productname")
Catch ex As Exception
Response.Write(ex.Message)
End Try
End Sub
C#

DataSet ds;
private void Page_Load(object sender, System.EventArgs e)
{
// Put user code to initialize the page here
//Fill the DataSet
if (!Page.IsPostBack )
{
ViewState["CurrentPos"] = 0 ;
this.DataBind() ;
}
}
protected void PrevBtn(object sender, System.EventArgs e)
{
try
{
int CurrentPos = (int)ViewState["CurrentPos"] ;
if (CurrentPos > 0 )
{
CurrentPos -= 1 ;
}
ViewState["CurrentPos"] = CurrentPos ;
this.DataBind() ;
}
catch (Exception ex)
{
Response.Write(ex.Message) ;
}
}

protected void NextBtn(object sender, System.EventArgs e)


{
try
{
int CurrentPos = (int)ViewState["CurrentPos"] ;
CurrentPos += 1 ;
if( CurrentPos > ds.Tables[0].Rows.Count)
{
CurrentPos -= 1 ;
}
ViewState["CurrentPos"] = CurrentPos ;
this.DataBind() ;
}
catch (Exception ex)
{
Response.Write(ex.Message) ;
}
}

protected void txtDataBind(Object sender , System.EventArgs e )


{
try
{
int CurrentPos = (int) ViewState["CurrentPos"];
ViewState["CurrentPos"] = CurrentPos ;
txtProductid.Text = ds.Tables[0].Rows[CurrentPos]["productid"].ToString();
txtProductName.Text = ds.Tables[0].Rows[CurrentPos]["productname"].ToString ();
}
catch (Exception ex)
{
Response.Write(ex.Message) ;
}
}

31.12 How to insert data in database using Textboxes?

<asp:Button id="btnAdd" style="Z-INDEX: 101; LEFT: 104px; POSITION: absolute; TOP: 168px"
runat="server" Text="Add Record"></asp:Button>
<asp:TextBox id="txtFirstName" style="Z-INDEX: 102; LEFT: 168px; POSITION: absolute; TOP: 40px"
runat="server"></asp:TextBox>
<asp:TextBox id="txtLastName" style="Z-INDEX: 103; LEFT: 168px; POSITION: absolute; TOP: 80px"
runat="server"></asp:TextBox>
<asp:TextBox id="txtDate" style="Z-INDEX: 104; LEFT: 168px; POSITION: absolute; TOP: 120px"
runat="server"></asp:TextBox>
<asp:Label id="Label1" style="Z-INDEX: 105; LEFT: 56px; POSITION: absolute; TOP: 240px"
runat="server"></asp:Label>

On Page_Load

VB.NET

if not Page.IsPostBack then


'....
end if

C#

if(!Page.IsPostBack )
{
//...
}

Use namespaces System.Data.SqlClient, System.Data.SqlTypes

On Button Click

VB.NET

Dim sqlStmt As String


Dim conString As String
Dim cn As SqlConnection
Dim cmd As SqlCommand
Dim sqldatenull As SqlDateTime
Try
sqlStmt = "insert into Emp (FirstName,LastName,Date) Values (@FirstName,@LastName,@Date) "
conString="server=localhost;database=Northwind;uid=sa;pwd=;"
cn = New SqlConnection(conString)
cmd = New SqlCommand(sqlStmt, cn)

cmd.Parameters.Add(New SqlParameter("@FirstName", SqlDbType.NVarChar, 11))


cmd.Parameters.Add(New SqlParameter("@LastName", SqlDbType.NVarChar, 40))
cmd.Parameters.Add(New SqlParameter("@Date", SqlDbType.DateTime))

sqldatenull = SqlDateTime.Null

cmd.Parameters("@FirstName").Value = txtFirstName.Text
cmd.Parameters("@LastName").Value = txtLastName.Text
If (txtDate.Text = "") Then
cmd.Parameters("@Date").Value = sqldatenull
'cmd.Parameters("@Date").Value = DBNull.Value
Else
cmd.Parameters("@Date").Value = DateTime.Parse(txtDate.Text)
End If
cn.Open()
cmd.ExecuteNonQuery()
Label1.Text = "Record Inserted Succesfully"

Catch ex As Exception
Label1.Text = ex.Message
Finally
cn.Close()
End Try

On Button Click

C#

string sqlStmt ;
string conString ;
SqlConnection cn =null;
SqlCommand cmd =null;
SqlDateTime sqldatenull ;
try
{
sqlStmt = "insert into Employees (FirstName,LastName,HireDate) Values
(@FirstName,@LastName,@Date) ";
conString="server=localhost;database=Northwind;uid=sa;pwd=;";
cn = new SqlConnection(conString);
cmd = new SqlCommand(sqlStmt, cn);
cmd.Parameters.Add(new SqlParameter("@FirstName", SqlDbType.NVarChar, 11));
cmd.Parameters.Add(new SqlParameter("@LastName", SqlDbType.NVarChar, 40));
cmd.Parameters.Add(new SqlParameter("@Date", SqlDbType.DateTime));
sqldatenull = SqlDateTime.Null;
cmd.Parameters["@FirstName"].Value = txtFirstName.Text;
cmd.Parameters["@LastName"].Value = txtLastName.Text;
if (txtDate.Text == "")
{
cmd.Parameters ["@Date"].Value =sqldatenull ;
//cmd.Parameters["@Date"].Value = DBNull.Value;
}
else
{
cmd.Parameters["@Date"].Value = DateTime.Parse(txtDate.Text);
}
cn.Open();
cmd.ExecuteNonQuery();
Label1.Text = "Record Inserted Succesfully";
}
catch (Exception ex)
{
Label1.Text = ex.Message;
}
finally
{
cn.Close();
}

31.13 When I try to enter a null value for DataTime in Database I get
error message "String was not recognized as a valid DateTime" or "Value
of type 'System.DBNull' cannot be converted to 'String'"?

Use namespace

System.Data.SqlTypes

VB.NET

Dim sqldatenull As SqlDateTime


sqldatenull = SqlDateTime.Null

If (txtDate.Text = "") Then


cmd.Parameters("@Date").Value = sqldatenull
'cmd.Parameters("@Date").Value = DBNull.Value
Else
cmd.Parameters("@Date").Value = DateTime.Parse(txtDate.Text)
End If

C#

if (txtDate.Text == "")
{
cmd.Parameters ["@Date"].Value =sqldatenull ;
//cmd.Parameters["@Date"].Value = DBNull.Value;
}
else
{
cmd.Parameters["@Date"].Value = DateTime.Parse(txtDate.Text);
}
31.14 How to use Parameterized queries in ASP.NET?

The follwoing sample is a good example of parameterized queries: How to insert data in database using

Textboxes?

31.15 How to filter distinct records from a normal Select query and
display in a web control?

"Select distinct <field> from <table>".This SELECT statement is used to filter out duplicate results from a

query's output. But sometimes the requirement is to use a Stored Procedure which returns the entire data

and dsiplay the manipulated distinct data in web server control.

To do this use SortedList

For using SortedList import namespace System.Collections

Stored Procedure

Create Procedure GetSuppliers AS

SELECT * FROM Suppliers


GO

<asp:DataList id="DataList1" runat="server">


<ItemTemplate>
<%#Container.DataItem%>
</ItemTemplate>
</asp:DataList>

VB.NET

Dim ds As New DataSet


DimmydaAsSqlDataAdapter=NewSqlDataAdapter("GetSuppliers","server=localhost;database=Northwind;uid=sa;pwd=;")
myda.SelectCommand.CommandType = CommandType.StoredProcedure
myda.Fill(ds, "Table")
Dim slist As SortedList = New SortedList
Dim dr As DataRow
For Each dr In ds.Tables(0).Rows
If Not slist.ContainsValue(dr("Country")) Then
slist.Add(dr("Supplierid"), dr("Country"))
End If
Next
DataList1.DataSource = slist.GetValueList
DataList1.DataBind()
'In case of Dropdownlist
'DropDownList1.DataSource = slist.GetValueList
'DropDownList1.DataBind()
C#

DataSet ds = new DataSet();


SqlDataAdaptermyda=newSqlDataAdapter("GetSuppliers","server=localhost;database=Northwind;uid=sa;pwd=;");
myda.SelectCommand.CommandType = CommandType.StoredProcedure;
myda.Fill(ds, "Table");
SortedList slist = new SortedList();

foreach( DataRow dr in ds.Tables[0].Rows)


{
if (! slist.ContainsValue(dr["Country"]))
{
slist.Add(dr["Supplierid"].ToString (), dr["Country"].ToString ());
}
}
DataList1.DataSource = slist.GetValueList();
DataList1.DataBind();
//In case of DropDownList
//DropDownList1.DataSource = slist.GetValueList
//DropDownList1.DataBind()

31.16 A field with bit data type value when displayed on a web page
shows true/ false how to display a bit value as 1/0?

VB.NET

'Using DataReader
While dr.Read()
Response.Write((dr("ProductName") + " "))
Response.Write((Convert.ToInt16(dr("discontinued")) + "
"))
End While

C#

//Using DataReader
while (dr.Read ())
{
Response.Write (dr["ProductName"] + " ");
Response.Write (Convert.ToInt16 ( dr["discontinued"]) + "
");
}

31.17 When I try to enter null value to DateTime field in database it is


saved as 1/1/1900 12:00:00 AM?
To enter Null value in sql server directly you can use Control+0 [Control+Zero]

or

Use SqlDateTime.Null if you want to do it from your application. folowing vb.net shall be helpful .

VB.NET

Dim sqlStmt As String

Dim conString As String

Dim cn As SqlConnection

Dim cmd As SqlCommand

Dim sqldatenull As SqlDateTime

Try

sqlStmt = "insert into Emp (FirstName,LastName,Date) Values (@FirstName,@LastName,@Date) " < BR >

conString="server=localhost;database=Northwind;uid=sa;pwd=;"

cn = New SqlConnection(conString)

cmd = New SqlCommand(sqlStmt, cn)

cmd.Parameters.Add(New SqlParameter("@FirstName", SqlDbType.NVarChar, 11))

cmd.Parameters.Add(New SqlParameter("@LastName", SqlDbType.NVarChar, 40))

cmd.Parameters.Add(New SqlParameter("@Date", SqlDbType.DateTime))

sqldatenull = SqlDateTime.Null

cmd.Parameters("@FirstName").Value = txtFirstName.Text

cmd.Parameters("@LastName").Value = txtLastName.Text

If (txtDate.Text = "") Then

cmd.Parameters("@Date").Value = sqldatenull

'cmd.Parameters("@Date").Value = DBNull.Value

Else

cmd.Parameters("@Date").Value = DateTime.Parse(txtDate.Text)

End If

cn.Open()

cmd.ExecuteNonQuery()

Label1.Text = "Record Inserted Succesfully"

Catch ex As Exception

Label1.Text = ex.Message

Finally

cn.Close()

End Try
31.18 How to use Stored Procedures in ASP.NET?

Sub LoginButton_Click(sender As Object, e As EventArgs)


Dim ds As New DataSet
Dim conn As New SqlConnection( _
"Data source=" & DatabaseServer.Text & _
";User id=" & Userid.text & _
";Password=" & Password.Text & _
";Initial catalog=" & Database.Text)
Dim cmd As New SqlCommand("sp_stored_procedures", conn)
Dim adpt As New SqlDataAdapter(cmd)
Try
Status.Text = "" adpt.Fill(ds, "SPs")
SPs.DataSource = ds.Tables("SPs")
SPs.DataTextField = "PROCEDURE_NAME"
SPs.DataBind()
Catch ex as SqlException
Status.Text = ex.Message
EndTry< BR>EndSub

31.19 How to display multiple records using DataTable.Select?

Use namespace System.Data.OleDb VB.NET

Dim myConnection As New OleDbConnection("Provider= SQLOLEDB.1;DataSource=localhost;database=


northwind;UserId=sa;Password=;")
Dim myda As New OleDbDataAdapter("Select * from Orders", myConnection)
Dim ds = New DataSet
myda.Fill(ds, "table")

Dim dr() As DataRow


Dim id As String = "ROMEY" ' "Field with id ROMEY has more than one records found
Dim sel As String = "customerid='" + id + "'"
dr = ds.Tables(0).Select(sel)
Dim i As Integer
For i = 0 To (dr.GetUpperBound(0)) - 1
Response.Write((dr(i)("Orderid").ToString() + ControlChars.Tab + dr(i)("Customerid").ToString() +
ControlChars.Tab + dr(i)("Freight").ToString() + "
"))
Next

C#

OleDbConnection myConnection = new OleDbConnection("Provider=


SQLOLEDB.1;DataSource=localhost;database= northwind;UserId=sa;Password=;");
OleDbDataAdapter myda= new OleDbDataAdapter ("Select * from Orders", myConnection);
System.Data.DataSet ds= new DataSet ();
myda.Fill (ds,"table");

DataRow[] dr ;
string id ="ROMEY";// "Field with id ROMEY has more than one records found
string sel ="customerid='"+ id + "'";
dr = ds.Tables [0].Select (sel);
int i;
for(i=0;i
{
Response.Write (dr[i]["Orderid"].ToString() + "\t" +
dr[i]["Customerid"].ToString() + "\t" + dr[i]["Freight"].ToString () +
"
");
}

31.20 How to get the count of items in a dataReader?

VB.NET

DimmycnAsNewSqlConnection("server=localhost;uid=sa;password=;database=northwind;")
Dim mycmd As New SqlCommand("Select * from Products", mycn)
mycn.Open()
Dim dr As SqlDataReader = mycmd.ExecuteReader
Dim i As Integer
While dr.Read
i += 1
End While
Response.Write("Count of Records : " & i)

C#

SqlConnectionmycn=newSqlConnection("server=localhost;uid=sa;password=;database=northwind;");
SqlCommand mycmd = new SqlCommand ("Select * from Products", mycn);
mycn.Open();
SqlDataReader dr = mycmd.ExecuteReader();
int i=0;
while(dr.Read())
{
i+=1;
}
Response.Write("Count of Records : " + i.ToString());

31.21 How to check EOF with SqlDataReader?

If you are using the Framework 1.1 , use HasRows

For Framework < 1.1

VB.NET

Dim myconnection As SqlConnection


Dim mycmd As SqlCommand
Dim strSql As String
Dim myReader As SqlDataReader
myconnection=NewSqlConnection("Server=localhost;uid=sa;password=;database=northwind;")
strSql = "Select count(*) from employees;Select * from employees"
mycmd = New SqlCommand(strSql, myconnection)
myconnection.Open()
Dim count As Integer = CInt(mycmd.ExecuteScalar())
myReader = mycmd.ExecuteReader(CommandBehavior.CloseConnection)
If count = 0 Then
Response.Write("No records found")
Else
myReader.NextResult()
While myReader.Read()
Response.Write(myReader("Employeeid").ToString() + "<BR>")
End While
End If

C#

SqlConnection myconnection ;
SqlCommand mycmd ;
string strSql ;
SqlDataReader myReader ;

myconnection=newSqlConnection("Server=localhost;uid=sa;password=;database=northwind;");
strSql = "Select count(*) from employees;Select * from employees";
mycmd = new SqlCommand(strSql, myconnection);
myconnection.Open();
int count=(int) mycmd.ExecuteScalar() ;
myReader = mycmd.ExecuteReader(CommandBehavior.CloseConnection);
if (count==0 )
{
Response.Write("No records found");
}
else
{
myReader.NextResult ();
while(myReader.Read ())
{
Response.Write(myReader["Employeeid"].ToString () + "<br>");
}
}

31.22 How to filter xml data and display data in the DataGrid?

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


<products>
<product prodId="product1-00" param1="11" />
<product prodId="product1-00" param1="12" />
<product prodId="product1-01" param1="13" />
<product prodId="product1-02" param1="14" />
<product prodId="product2-00" param1="21" param2="22" />
<product prodId="product2-00" param1="31" param2="32" />
<product prodId="product2-01" param1="41" param2="42" />
</products>

VB.NET

Dim ds As New DataSet


ds.ReadXml(Server.MapPath("data1.xml"))
Dim dv As New DataView
dv = ds.Tables(0).DefaultView
dv.RowFilter = "prodId='product2-00'"
Me.DataGrid1.DataSource = dv
Me.DataBind()

C#

DataSet ds = new DataSet();


ds.ReadXml(Server.MapPath("data1.xml"));
DataView dv = new DataView();
dv = ds.Tables[0].DefaultView;
dv.RowFilter = "prodId='product2-00'";
this.DataGrid1.DataSource = dv;
this.DataBind();

31.23 Why do I get the error message "ExecuteReader requires an open


and available Connection. The connection's current state is Closed"?

This error is caused if you have not opened the connection.

Before you read the data using DataReader open the Connection

31.24 Why do I get the error message "The ConnectionString property


has not been initialized"?

Check if you have specified the connection string

VB.NET

dim cn as new SqlConnection("<your connection string>")


'dim cn as new OleDdConnection("<your connection string>")

C#

SqlConnection cn = new SqlConnection("<your connection string>");


OleDbConnection cn = new OleDbConnection("<your connection string>");

31.25 I get the error message "Keyword not supported: 'provider'",


when using Sql Server why?

If you are using SqlConnection then the connection string should be as follows:

server=localhost;uid=sa;password=;database=northwind
i.e
server=<yourservername>;uid=<youruid>;password=<yourpassword>;database=<yourdbName>"

For SqlConnection we do not provide a Provider . Provider is used in cases where OleDbConnection is used.

31.26 Why do I get the error message "ExecuteReader: Connection


property has not been initialized"?

This error is caused if there is no Connection object associated with the Command Object. To resolve this

VB.NET

Dim cn as new SqlConnection("<your connection string>")


'Dim cn as new OleDbConnection("<your connection string>")
Dim cmd As new SqlCommand("Select * from Products", cn)
'Dim cmd As new OleDbCommand("Select * from Products", cn)

C#

SqlConnection cn = new SqlConnection ("<your connection string>");


'OleDbConnection cn = new OleDbConnection ("<your connection string>");
SqlCommand cmd = new SqlCommand ("Select * from Products", cn);
'OleDbCommand cmd = new OleDbCommand ("Select * from Products", cn);

31.27 Why do I get the error message "There is already an open


DataReader associated with this Connection which must be closed
first."?

This is caused if you are attempting to use the same DataReader more than once in your code without closing

the previous Datareader. Or you might have a DataReader open on the same connection as the

DataAdapter/Command uses. So it is not recommended to share a connection between a DataReader and a


DataAdapter/Command

• Either close the first connection or,

• if you must keep it open as you are executing another reader from within it, use another connection

object.

31.28 I get the error message "Cast from type DBNull to type String is
not valid." when I try to display DataReader values on form?

Try VB.NET

txtCountry.Text = dr("FieldName").ToString()

C#

txtCountry.Text = dr["FieldName"].ToString();

or Try

VB.NET

If dbReader("fieldname").ToString= DBnull.Value.ToString()
'Empty field value
Else
'Display value
End if

C#

if (dbReader["fieldname").ToString() == DBNull.Value.ToString() )
{
//Empty field value
}
else
{
//display Value
}
31.29 What is the significance of CommandBehavior.CloseConnection?

To avoid having to explicitly close the connection associated with the command used to create either a

SqlDataReader or and OleDbDataReader, pass the CommandBehavior.CloseConnection argument to the

ExecuteReader method of the Connection. i.e

VB.NET

dr= cmd.ExecuteReader(CommandBehavior.CloseConnection)

C#

dr= cmd.ExecuteReader(CommandBehavior.CloseConnection);

The associated connection will be closed automatically when the Close method of the Datareader is called.

This makes it all the more important to always remember to call Close on your datareaders.

31.30 How to maintain Line feeds when saving data to a database?

Save the data entered in the multiline textbox as

VB.NET

..
cmd.Parameters.Add(new SqlParameter("@Notes" ,SqlDbType.NVarChar ))
cmd.Parameters ("@Notes").Value ="<pre>" + TextBox1.Text + "</pre>"
....
cn.Open()
cmd.ExecuteNonQuery()

C#

...
cmd.Parameters.Add(new SqlParameter("@Notes" ,SqlDbType.NVarChar ));
cmd.Parameters ["@Notes"].Value ="<pre>" + TextBox1.Text + "</pre>";
....
cn.Open();
cmd.ExecuteNonQuery();

To retrieve the Data


VB.NET

Response.Write (ds.Tables(0).Rows(0)("Notes").ToString ())

C#

Response.Write (ds.Tables[0].Rows[0]["Notes"].ToString ());

31.31 How to use the Same DataReader to populate two different


ListBoxes?

You cannot use the same DataReader to populate 2 Listboxes.But can try out the below workaround

VB.NET

...
cn=NewSqlConnection("Server=localhost;uid=sa;database=northwind;pwd=")
cmd = New SqlCommand("select * from products;select * from products", cn)
cn.Open()
dr = cmd.ExecuteReader()
ListBox1.DataSource = dr
ListBox1.DataTextField = "productname"
ListBox1.DataBind()
dr.NextResult()
ListBox2.DataSource = dr
ListBox2.DataTextField = "productname"
ListBox2.DataBind()

C#

...
cn=newSqlConnection("Server=localhost;uid=sa;database=northwind;pwd=");
cmd= new SqlCommand ("select * from products;select * from products", cn);
cn.Open();
dr = cmd.ExecuteReader();
ListBox1.DataSource = dr;
ListBox1.DataTextField = "productname";
ListBox1.DataBind();
dr.NextResult();
ListBox2.DataSource = dr;
ListBox2.DataTextField = "productname";
ListBox2.DataBind();

31.32 How to resolve the error message "Cannot implicitly convert type
'string' to 'System.DateTime' " when using a DataReader?

Try

VB.NET

dim dt as DateTime = ctype( dr("hiredate").ToString(), DateTime)

C#

DateTime dt= ((DateTime) dr["hiredate"]).ToString();

31.33 Why do I get the error message "Value cannot be null. Parameter
name: dataSet "?

The cause of this error may be that you have declared a dataset but have not written the following statement

VB.NET

ds= new DataSet()

C#

ds= new DataSet();

31.34 Why do I get the error message "The SelectCommand property has
not been initialized before calling 'Fill'. "?

You have to supply the Sql Statement or Stored Procedure for the DataAdapter as

VB.NET

da.SelectCommand.CommandText = "Select * from "

or

da = new SqlDataAdapter ("Select * from ", cn)


C#

da.SelectCommand.CommandText ="Select * from ";

or

da = new SqlDataAdapter ("Select * from ", cn);

31.35 How to use OleDb DataSet?

Use namespace System.Data.OleDb

VB.NET

Dim strConn As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Server.MapPath("nwind.mdb")


& ";"
Dim strsql As String = "Select * from Customers"
Dim cn As New OleDbConnection(strConn)
Dim ds As DataSet = New DataSet()
Dim da As New OleDbDataAdapter(strsql, cn)
da.Fill(ds, "T1")
DataGrid1.DataSource = ds
DataGrid1.DataBind()

C#

string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Server.MapPath("nwind.mdb") + ";";


string strsql = "Select * from Customers";
OleDbConnection cn = new OleDbConnection(strConn);
DataSet ds = new DataSet();
OleDbDataAdapter da = new OleDbDataAdapter(strsql, cn);
da.Fill(ds, "T1");
DataGrid1.DataSource = ds;
DataGrid1.DataBind();

31.36 How to use OleDb DataReader?

VB.NET
Dim strConn As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Server.MapPath("nwind.mdb")
& ";"
Dim strsql As String = "Select * from Customers"
Dim cn As New OleDbConnection(strConn)
Dim cmd As New OleDbCommand(strsql, cn)
cn.Open()
Dim dr As OleDbDataReader = cmd.ExecuteReader(CommandBehavior.CloseConnection)
DataGrid1.DataSource = dr
DataGrid1.DataBind()

C#

string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Server.MapPath("nwind.mdb") + ";";


string strsql = "Select * from Customers";
OleDbConnection cn = new OleDbConnection(strConn);
OleDbCommand cmd = new OleDbCommand (strsql, cn);
cn.Open ();
OleDbDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection );
DataGrid1.DataSource = dr;
DataGrid1.DataBind();

31.37 How to loop through a Dataset to display all records?

VB.NET

'Fill Dataset
Dim dc As DataColumn
Dim dr As DataRow
For Each dr In ds.Tables(0).Rows
For Each dc In ds.Tables(0).Columns
Response.Write(dr(dc.ColumnName).ToString())
Next
Next

C#

//Fill the DataSet


foreach (DataRow dr in ds.Tables[0].Rows)
{
foreach( DataColumn dc in ds.Tables[0].Columns)
{
Response.Write(dr[dc.ColumnName].ToString());
}
}
32.1 How to print out all the variables in the Session?

VB.NET
Dim strKey as string
For Each strKey In Session.Keys
Response.Write(strKey + " : " + Session(strKey).ToString() + "<br>")
Next

C#

foreach (string strKey in Session.Keys)


{
Response.Write(strKey + " : " + Session[strKey].ToString() + "<br>");
}

32.2 Why isn't session state available?

• - First, check your web.config, machine.config and your page directive to make sure you have

enabled session state. Reference:

o Session State

o @ Page

• - session state is not available just everywhere, anytime. It is available only after the

HttpApplication.AcquireRequestState event is called. For example, it is NOT available in the

Application_OnAuthenticateRequest handler inside global.asax. For details, see: Handling Public

Events

• - Lastly, make sure System.Web.SessionState.SessionStateModule is included the in your config files.

A common case is that SharePoint application will remove this module from their web.config files (for

performance reason), and thus session state isn't available.

32.3 Can I share session state between ASP.NET and ASP pages?

No. This MSDN article shows how to work around it: How to Share Session State Between Classic ASP and

ASP.NET

32.4 Can I share session state between web applications (i.e. "virtual
directories" or "applications" in IIS)?

No.

32.5 What is the difference between Session.Abandon() and


Session.Clear()?
The major difference is that if you call Session.Abandon(), Session_End will be fired (for InProc mode), and in

the next request, Session_Start will be fired. Session.Clear( ) just clears the session data without killing it.

32.6 The SessionID remains the same even after the Session times out or
Session abandons?

The SessionID lasts as long as the browser session lasts even though the session state expires after the

indicated timeout period i.e the same session ID can represent multiple sessions over time where the

instance of the browser remain the same.

32.7 Why are my Session variables lost frequently when using InProc
mode?

This can be due to application recycle.

See PRB: Session variables are lost intermittently in ASP.NET applications

In v1, there is also a bug that will cause worker process to restart. It's fixed in SP2 and v1.1. See FIX:

ASP.NET Worker Process (Aspnet_wp.exe) Is Recycled Unexpectedly.

32.8 Does session state have a locking mechanism that serialize the
access to state?

Session state implements a reader/writer locking mechanism:

• A page (or frame) that has session state write access (e.g. <%@ Page EnableSessionState="True"

%>) will hold a writer lock on the session until the request finishes.

• A page (or frame) that has session state read access (e.g. <%@ Page

EnableSessionState="ReadOnly" %>) will hold a reader lock on the session until the request finishes.

• Reader lock will block a writer lock; Reader lock will NOT block reader lock; Writer lock will block all

reader and writer lock.

• That's why if two frames both have session state write access, one frame has to wait for the other to

finish first

32.9 Response.Redirect and Server.Transfer is not working in


Session_End?

Session_End is fired internally by the server, based on an internal timer. And thus there is no HttpRequest

associted when that happens. That is why Response.Redirect or Server.Transfer does not make sense and will

not work.

32.10 Is the session Timeout attribute a sliding timeout value?


The session Timeout is a sliding expiration time, meaning whatever your page access session state, the

expiration time will be moved forward. Note that as long as a page has NOT disabled session state, it will

access the session automatically when requested.

32.11 I am writing my own HttpHandler. Why is session state not


working?

Your HttpHandler has to implement the "marker" interface IRequiresSessionState or IReadOnlySessionState

in order to use session state.

32.12 Why isn't Session available in my event handlers in global.asax?

It depends on which event you're handling. Session is available only after AcquireRequestState event

32.13 When I use the Session in component class as Session("CustID"),


I get error message "Session is not declared". Why?

Use HttpContext.Current.Session i.e

VB.NET

HttpContext.Current.Session("CustID") = "1"

C#

HttpContext.Current.Session["CustID"] = "1";

32.14 When I create a Session variable if I'm using inproc, where is the
session variable stored?

• In II5, it's stored in the memory of aspnet_wp.exe.

• For IIS6, by default all apps will share the same application pool, i.e. the session state is stored in

the memory of the process w3wp.exe. They are NOT separated per application, but instead per

application pool (w3wp.exe)

32.15 Is the session timeout attribute in minutes or seconds?

The Timeout setting is in minutes, not in seconds. i.e The timeout attribute specifies the number of minutes a

session can be idle before it is abandoned. The default is 20

32.16 Will my session state be saved when my page hit an error? Will my
session state be saved when my page hit an error? In Session_End, I
tried to do some cleanup job using SQL but it failed. Why?
1. Session_End is supported only in InProc mode.

2. Session_End is run using the account which runs the worker process (aspnet_wp.exe), which can be

specified in machine.config. Therefore, in your Session_End, if you connect to SQL using integrated

security, it will use that worker process account credential to connect, and may fail depending on

your SQL security settings.

32.17 Why do I lose my Session variables on redirect when I set


"cookieless" to true?

When using cookieless, you must use relative path (e.g. ..\webform1.aspx) instead of absolute path (e.g.

\dir1\subdir1\webform1.aspx). If you use absolute path, ASP.NET cannot preserve your session ID in the

URL.

32.18 How to store SortedList in Session or Cache?

VB.NET

Dim x As New SortedList()


x.Add("Key1", "ValueA")
x.Add("Key2", "ValueB")

To store in Session:

Session("SortedList1") = x

and to retrieve

Dim y As SortedList = CType(Session("SortedList1"), SortedList)

C#

SortedList x = new SortedList();


x.Add("Key1", "ValueA");
x.Add("Key2", "ValueB");

To store in Session:

Session["SortedList1"] = x;
and to retrieve

SortedList y = (SortedList) Session["SortedList1"];

32.19 Why do I get the error message "Session state can only be used
when enableSessionState is set to true, either in a configuration file or in
the Page directive"?

This problem may occur after you install Windows Sharepoint Server(WSS) on a server that has Microsoft

Visual Studio .NET 2003 installed. The WSS ISAPI filter handles all incoming URLs. When you browse one of

the ASP.NET Web application virtual directories, the ISAPI filter does not locate the URL path of the folder.

To resolve this refer Session state cannot be used in ASP.NET with Windows SharePoint Services

32.20 How to remove a Session variable?

Use HttpSessionState.Remove()

32.21 Is there any way to know how much memory is being used by
session variables in my application?

No

32.22 I have a frameset page which has an HTM extension, and I found
out that each frame it contains displays a different session id on the first
request. Why?

The reason is that your frameset page is an HTM file instead of an ASPX file.

In normal a scenario, if the frameset is an aspx file, when you request the page, it will first send the request

to the web server, receive an asp.net session cookie (which holds the session id), and then the browser will

send individual requests for the frames, and each request will carry the same session id.

However, since your frameset page is an htm file, the first request comes back without any session cookie

because the page was serviced by ASP and not ASP.NET. Then again your browser sends out individual

requests for each frame. But this time each individual request will NOT carry any session id, and so each

individual frame will create its own new session. That's why you will see different session ids in each frame.

The last request that comes back will win by overwriting the cookie written by the previous two requests. If

you do a refresh, you will see them having the same session id.

This behavior is by-design, and the simple solution is to change your frameset page to .aspx.

32.23 Can different apps store their session state in different databases
on the same SQL server?

Yes. Refer FIX: Using one SQL database for all applications for SQL Server session state may cause a

bottleneck

32.24 Do I have a valid HttpSessionState object and HttpContext object


in Session_End?
You will have the HttpSessionState object available. Just use 'Session' to access it.

For HttpContext, it is not available because this event is not associated with any request.

32.25 Why aren't my sessions expiring, I am using SQLServer mode?

In SQLServer mode, session expiration is carried out by the SQL Agent using a registered job. Make sure your

SQL Agent is running.

32.26 I set EnableSessionState to "ReadOnly", but in InProc mode I can


still modify the session. Why is that?

Even those enableSessionState is marked as ReadOnly, but in InProc state, the user can still modify the

session. The only difference is that the session will not be locked during the request. This limitation is by-

design

32.27 How can I avoid specifying a plain password for my sql


connection?

Include a sql trusted connection, or put the connection string as encrypted data in the registry. Refer

• FIX: Stronger Credentials for processModel, identity, and sessionState

• How To Use the ASP.NET Utility to Encrypt Credentials and Session State Connection Strings

32.28 How can I use Session variables in a class?

Use HttpContext.Current.Session

VB.NET

HttpContext.Current.Session("Value1") = "1"

C#

HttpContext.Current.Session["Value1"] = "1";

In similar manner you can use Application Variables too.

32.29 What kind of objects can I store in a Session State?


Depends on which mode you are using:

• InProc Mode- objects stored in session state are actually live objects, and so you can store whatever

object you have created.

• State Server or SQL Server mode, objects in the session state will be serialized and deserialized

when a request is processed. So make sure your objects are serializable and their classes must be

marked as so. If not, the session state will not be saved successfully. In v1, there is a bug which

makes the problem happen unnoticed in SQLServer mode and will make your request hang. The

hanging problem is fixed in v1.1. The fix for KB 324479: ASP.NET SQL Server Session State

Impersonation Is Lost Under Load also contains the fix for this problem. The problem will be fixed in

v1 SP3 too.

For more info: BUG: Session Data Is Not Saved in Out-of-Process Session State

32.30 Why did my request hang after I switch to SQLServer mode?

(Right answer?) Refer What kind of objects can I store in Session State?

32.31 What are the disadvantages of setting cookieless to true?

Setting Cookieless=true implies some restrictions, mainly:

1. You cannot use absolute link in your pages.

2. You have to perform additional steps to switch between http and https pages in your application.

3. If your customer sends a link to a friend, the URL will contain the session ID and both users could be

using the same session ID at the same time.

32.32 Can I store my session state in a database other than tempdb, In


SqlServer mode?

Yes. For more details Refer HOW TO: Configure ASP.NET for Persistent SQL Server Session State Management

7. DataList

8. Repeater
9. Security

10. CheckBox

11. Client Side Scripting

12. XML

13. CheckBoxList

14. AdRotator
15. Files

16. ListBox

17. Output Caching

More...

18. Mail

19. GDI+

20. Collections and Lists

21. RadioButton

22. Controls

23. Table Control

24. CSS Styles

24.1

25. DataGrid

26. Design Time Serialization


27. Custom Controls

28. TextBox

29. Dropdownlist

30. Config files

31. ADO.NET

32. Session

Das könnte Ihnen auch gefallen