Beruflich Dokumente
Kultur Dokumente
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
C:\WINNT\Microsoft.NET\Framework\v**\aspnet_regiis.exe
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
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.
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.
To verify if IIS is installed, go to your 'Add or Remove Programs' utility in the Control panel and click on
On XP Pro and below, you should see an item called "Internet Information Services (IIS)". If this is checked,
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
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
under the root folder (usually "C:\inetput\wwwroot" if you do a default installation) . You can then find the
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
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.
2. In the Open text box, type cmd, and then click OK.
WindowsDirectory\Microsoft.NET\Framework\v1.0.3705\
aspnet_regiis -s W3SVC/1/ROOT/WebApp1
2. In the Open text box, type cmd, and then click OK.
WindowsDirectory\Microsoft.NET\Framework\v1.1.4322\
aspnet_regiis -s W3SVC/1/ROOT/WebApp2
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
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.
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
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
• What is ASP.NET
• ASP.NET OverView
2.2 Why does my ASP.NET file have multiple <form> tag with
runat=server?
.Net framework provides an Administration utility that manages the installation and uninstallation of multiple
C:\WINNT\Microsoft.NET\Framework\v**\aspnet_regiis.exe
(if you install VS.NET or the framework without IIS installed, and then go back in and install IIS afterwards,
VB.NET
Response.Write(System.Environment.Version.ToString() )
C#
Response.Write(System.Environment.Version.ToString() );
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#
<%--<asp:Label id="Label1" style="Z-INDEX: 101; LEFT: 8px; POSITION: absolute; TOP: 48px"
runat="server">Label</asp:Label>--%>
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
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
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
VB.NET
System.DateTime.Now.ToShortDateString()
System.DateTime.Now.ToShortTimeString()
C#
System.DateTime.Now.ToShortDateString();
System.DateTime.Now.ToShortTimeString();
VB.NET
C#
Response.Write (Request.UserHostAddress.ToString ());
Call the Request.QueryStringmethod passing in the key. The method will return the parameter value
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>
For
• VB.NET
• C#
2.15 How to catch the 404 error in my web application and provide more
useful information?
VB.NET
C#
Exception ex = Server.GetLastError().GetBaseException();
if (ex.GetType() == typeof(System.IO.FileNotFoundException))
{
//your code
Response.Redirect ("err404.aspx");
}
else
{
//your code
}
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
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
C#
VB.NET
C#
ASP.Net does not recognize the standard ASP global.asa file. Instead it uses a file named global.asax with the
ASP.Net actually has very solid internal garbage collection. So this is not an issue as it was in previous
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
The following Code Migration Assistants are discussed in the link below.
Also refer:
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
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
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
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
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
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
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.
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
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 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
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")>
VB.NET
C#
2.40 What is the best way to output only time and not Date?
Response.Write(DateTime.Now.ToString("hh:mm:ss"))
C#
Response.Write(DateTime.Now.ToString("hh:mm:ss"));
VB.NET
Response.Write ( Request.UrlReferrer.ToString())
C#
Response.Write ( Request.UrlReferrer.ToString());
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.
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.
FormsAuthentication.SignOut()
C#
FormsAuthentication.SignOut();
VB.NET
C#
string sLang ;
sLang = Request.UserLanguages[0];
Response.Write (sLang);
• 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.
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
• Contain all information necessary for the browser(or other client program) to locate the resource
o This includes protocol moniker used( i.e http://, ftp://..etc..), Server's Domain name or IP
Relative URLs:
• Only provide information necessary to locate a resource relative to the current document(document
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
VB.NET
C#
TimeSpan ts = TimeSpan.FromMilliseconds(10000);
Response.Write (ts.ToString () );
or
However, note that each source file will be compiled individually into its own assembly, so they cannot have
VB.NET
C#
2.56 How can I ensure that application-level variables are not updated
by more than one user simultaneously?
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
C#
bool blnValid=false;
try
{
DateTime.Parse(MyString);
blnValid=true;
}
catch
{
blnValid=false;
}
Namespaces and Class names are case Sensitive. Namespaces imported using the @ Import Directive will
VB.NET
C#
bool blntimeIsOk = (DateTime.Parse("15:00") < DateTime.Parse("08:00"));
Response.Write (blntimeIsOk);
VB.NET
C#
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
VB.NET
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
You cannot write the code-behind files in different languages in the same project, but you can write the aspx
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
• 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
The value of validateRequest is set to 'true' by default, which means that the framework will automatically
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.
By default ASP.NET Web applications run as ASP.NET user. This user has limited permissions equivalent to the
User Group.
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.
• 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.
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" ;
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
C#
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;
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,
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
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?
VB.NET
2.81 How to make VS.Net use FlowLayout as the default layout rather
than the GridLayout?
.NET\Vb7\VBWizards\WebForm\Templates\1033
to
2003\VC#\VC#Wizards\CSharpWebAppWiz\Templates\1033
Change the following line in the existing WebForm1.aspx
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".
No. DataReader provides a means of reading a forward-only stream of rows from a database.
• Server.Transfer is used to End the current weform and begin executing a new webform. This method
• 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)
VB.NET
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");
}
}
VB.NET
C#
No. ASP.NET uses parsers to strip the code from ASPX files and copy it to temporary files containing derived
load the DLL when the type is referenced. This is also what happens when you add a custom control from the
This can be done by setting the ErroPage attribute of Page Directive or ErrorPage property of Page Class to
In web.config
This problem can occur if there is some error in the web.config file. To resolve this check for the well-
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 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.
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.
4. If None is selected in the Execute Permissions list, click Scripts only, and then click Apply
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.
5. In the Select Users or Groups dialog box, select the appropriate user, and then click OK.
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
1. Click Start, point to Programs, point to Administrative Tools, and then click Domain Controller
Security Policy.
5. In the Security Policy Setting window, click Define these policy settings.
7. In the Select Users or Groups window, select the IWAM account name, click Add, and then click OK.
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
Select the Configuration Properties for debugging then in right Pane, under the debugger node select true for
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.
3. Make sure the account you are logged in as and the ASP.NET Worker process is in the local
• 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.
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.
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 ...
2) In VS.Net in your project properties dialog, select "Debugging" under "Configuration Properties" and make
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.
• Using the Error event procedures at the Page, Application or Global levels
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)'"
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
• 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
• BUG: Named pipes do not work when worker process runs under ASPNET account
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.
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 moved to another location and/or deleted.
• The requested file is temporarily unavailable due to maintenance, upgrades, or other unknown
causes.
• 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
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
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:
You can view the page on which trace is enabled to true to see the details.
<configuration>
<system.web>
<trace enabled="true" requestLimit="10" pageOutput="false" traceMode="SortByTime"
localOnly="true" />
</system.web>
</configuration>
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?
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
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
VB.NET
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
The configuration section supports an inner <error> tag that associates HTTP status codes with custom error
To enable remote debugging on Microsoft® Windows® XP SP2 platforms, the Internet Connection Firewall
• 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.
• In addition, if the user running Visual Studio is not an Administrator on the remote machine, DCOM
and while doing so, the system puts a lock on the same.
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.
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:
For more information check out : Protecting Against Script Exploits in a Web Application on MSDN
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
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-
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?) "?
• 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
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:
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
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
VB.NET
Response.Redirect(url,false)
C#
Response.Redirect(url,false) ;
Its basically a syntax error in your ASPX page. It happens when your page is unreadable for the part of
To repair IIS mappings for ASP.NET, you can run the Aspnet_regiis.exe utility.
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
• (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.
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
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.
• 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
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");
In Custom Components, you can use tracing if you reference the System.Web namespace and use the
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:
<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
C#
VB.NET
C#
Label1.Text = "<sometag1>" + "<br>" + "<sometag1>";
VB.NET
C#
4.4 How do I determine if the user clicked a "Submit" button twice in the
page?
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
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
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
VB.NET
C#
4.8 How do I specify the Japanese locale for the controls in my Japanese
localized 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.
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
C#
This error occurs if you are trying to fetch the recordset value as follows
rs.Fields("productname")
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.16 How can I trigger a submit on my form when the enter key is
pressed?
Also check out Andy Smith's DefaultButton Control which triggers submit selectively on one of many buttons
VB.NET
C#
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
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
C#
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
o WebRequest is the abstact base class for the .NET Framework's request/response model for
o WebResponse is the abstract base class from which protocol specific response classes are
derived.
VB.NET
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
C#
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
C#
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
C#
string productid;
string strSQL;
string strConn;
SqlDataReader dr,dr1;
SqlConnection mycn;
SqlCommand mycmd;
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
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
C#
VB.NET
C#
Specify the pageLayout of the Document from GridLayout to FlowLayout, this will position the controls
Use the global.asax file and listen to the PostRequestHandlerExecute event of the Global object.
VB.NET
Simply use the same handler for the different button Click events.
VB.NET
C#
// In InitializeComponent
this.Button1.Click += new System.EventHandler(this.Button1_Click);
this.Button2.Click += new System.EventHandler(this.Button1_Click);
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
VB.NET
C#
4.37 How to call the Page_load procedure from any event on the page?
VB.NET
C#
4.38 How to add login user (ASPNET) to MS SQL 2000 Desktop Engine
server?
osql -S servername\instancename -E -q
--Line numbers will appear
EXEC sp_grantlogin 'machinename\ASPNET'
go
use
go
VB.NET
C#
4.40 What are the pros and cons of using Session or Cache to save
intermediate state?
To store in Session:
Pros:
• If you use StateServer or SQLServer mode, you can access your session state across the webfarm.
Cons:
• If you use StateServer or SQLServer mode, your object must be serializable, and you pay the
To use cache:
Pros:
• Can use cache dependencies or other cache features to control its lifetime
Cons:
Process of switching of User Interface between left to right i.e English, German ...and right to left such as
To mirror a form
<html dir="rtl">
You can use Http Compression to compress static aspx files. Refer Microsoft Knowledge Base Article -
322603
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
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 :
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
• enter the DOMAIN\USERNAME and select your database as the default database of the user at the
• Select last tab Database Access -> select your database, and add the db_datareader and
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.
VB.NET
Response.Write(System.Windows.Forms.SystemInformation.ComputerName)
C#
Response.Write(System.Windows.Forms.SystemInformation.ComputerName);
VB.NET
C#
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:
C# compiler csc.exe
or
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
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?
</td>
</tr>
</table>
C#
VB.NET
'In Page_Load
dim originalString as string = "a±"
Response.Write (IsAsciiString(originalString))
C#
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.
VB.NET
lnkStyle.Attributes("href") = "ie/styles.css"
C#
lnkStyle.Attributes["href"] = "ie/styles.css" ;
<configuration>
<appSettings>
<add key="PageSize" value="10">
</add>
</appSettings>
</configuration>
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
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
VB.NET
C#
string strval="" ;
foreach (DateTime day in Calendar1.SelectedDates)
{
strval += (day.Date.ToShortDateString() + "<br>");
}
Response.Write(strval);
}
Calendar1.VisibleDate = DateTime.Today
Calendar1.SelectedDates.Clear()
C#
Calendar1.VisibleDate = DateTime.Today;
Calendar1.SelectedDates.Clear();
5.4 Is there a way to click an image and let the calendar Control appear?
Other links
<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
C#
5.6 How can I change the month and Weekdays to Japanese characters
for a Calendar Control?
• 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?
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
C#
DataSet ds ;
private void Page_Load(object sender, System.EventArgs e)
{
// Put user code to initialize the page here
//Populate the DataSet
}
VB.NET
C#
Calendar1.SelectedDate =new DateTime();
5.9 How can I set the Selection of the Calendar Control to date or week
or month?
• Day
• DayWeek
• DayWeekMonth
• None
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
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;
}
VB.NET
Calendar1.ShowDayHeader = False
C#
Calendar1.ShowDayHeader = false;
VB.NET
if (e.Day.IsOtherMonth = true)
{
e.Cell.Text = "";
}
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.
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;
}
<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
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
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#
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.
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
VB.NET
C#
Drag and drop User Control and set the source property.
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
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.
Then in your aspx code, you can simply use the id to call public methods (and properties) defined by the
myUC.writeData(...)
C#
myUC.writeData(...)
<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" ;
VB.NET
C#
6.8 How to change the imageurl of the image control that exists in a
usercontrol?
In the .ascx:
In .aspx
VB.NET
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.2 How to change the colors of a row to indicate its the Birthday of the
Employee (for example) in a DataList?
VB.NET
C#
VB.NET
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();
}
VB.NET
C#
n=>Number of columns
VB.NET
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
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();
}
VB.NET
C#
VB.NET
In class
C#
In class
}
}
VB.NET
C#
" + "
";
}
VB.NET
C#
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#
VB.NET
C#
VB.NET
C#
if(!Page.IsPostBack)
{
//Populate the Data in the Repeater
}
VB.NET
C#
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
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();
}
VB.NET
C#
VB.NET
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
C#
string SortField;
SqlConnection myconnection ;
SqlDataAdapter myda ;
DataSet ds ;
String strConn ;
string SQLStmt= "Select * from Employees ";
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();
}
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?
VB.NET
C#
Authentication is the process of identifying and verifying who the client accessing the server is.
• Windows authentication and are browsing an ASP.NET page from server -- ASP.NET/IIS would
• 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
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).
<authorization>
<deny users="?"/>
</authorization>
<identity impersonate="true"/>
• 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
• Passport : Centralized authentication service provided by Microsoft that offers a single logon and core
<authentication
mode= " [ Windows | Forms | Passport | None ] ">
</authentication>
9.5 How to determine the Windows User from a Web form Application?
VB.NET
C#
"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.
5. In the Select Users or Group dialog box, click the user account that you want to add, click Add, and
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
C#
<script language="javascript">
function ClientValidation(source, args)
{
args.IsValid = document.all["chkbox"].checked;
}
</script>
VB.NET
The RegisterStartupScript method emits the script just before the closing tag of the Page object's <form
VB.NET
C#
Alternatively, use the RegisterClientScriptBlock method which emits the client-side script just after the
11.2 How to open a new Window using javascript function from a Link
button?
VB.NET
C#
Here is a JavaScript Quick Reference Guide in Poster Format that you can print out and refer easily. Covers
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").
C#
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
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"))
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
C#
VB.NET
if Page.Request.Browser.JavaScript then
...
else
...
end if
C#
if (Page.Request.Browser.JavaScript )
{
...
}
else
{
...
}
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;
}
VB.NET
C#
<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
C#
All Objects in JavaScript implicitly support hash table like syntax by virtue of behaving as Associative Arrays.
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
document.getElementById("<id>").style.visibility="hidden";
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.
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>
<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
In Page_Load
VB.NET
TextBox1.Attributes.Add("onKeyDown", "chkTextEntered();")
C#
TextBox1.Attributes.Add("onKeyDown", "chkTextEntered();");
VB.NET
C#
VB.NET
DropDownList1.Attributes.Add("onChange","this.disabled=true;" )
C#
DropDownList1.Attributes.Add("onChange","this.disabled=true;" );
<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
C#
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
• Make sure to add a ListItem with Text="Please Choose" and Value ="".
11.29 Are there any resources regarding the Mozilla specific Browser
Objects and CSS information?
12.1 How to write the data from database into an XML file?
VB.NET
C#
12.2 How to read data from an XML file and display it in a DataGrid?
VB.NET
C#
12.3 How to read data from the XML file using FileStream and display it
in a DataGrid?
VB.NET
C#
VB.NET
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);
products.xml
VB.NET
C#
VB.NET
15.1 What is the best way to rename a file on the webserver in code?
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.
VB.NET
C#
Use namespace
• System.IO
• System.Text
VB.NET
C#
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#
15.5 How can I to get the path to the system area that holds temporary
files?
VB.NET
C#
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
Use Request.Path
VB.NET
Response.Write (Path.GetFileName(Request.PhysicalPath))
C#
Response.Write (Path.GetFileName(Request.PhysicalPath));
• VB.NET code
• C# Code
VB.NET
System.IO.File.Delete(Server.MapPath("wnew.txt"))
C#
System.IO.File.Delete(Server.MapPath("wnew.txt"))
15.11 How to find the date and time the specified file or directory was
last written to?
VB.NET
C#
VB.NET
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?
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
C#
SqlConnection cn ;
SqlCommand cmd ;
string filename ;
SqlDataReader dr ;
System.Text.StringBuilder sb ;
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)
sr.Close()
C#
StreamReader sr = File.OpenText(Server.MapPath("1.txt"));
string strContents = sr.ReadToEnd();
//To display normal raw contents
Response.Write(strContents);
sr.Close();
VB.NET
C#
Try to use "System.IO.File.Exists("path")". path is the physical file path and it will return you a boolean value.
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.
• MemoryStream Class
VB.NET
C#
<p>
<asp:ListBox id="ListBox1" runat="server"></asp:ListBox>
</p>
<p>
<asp:Button id="buttonAdd" runat="server" Text="Add"></asp:Button>
</p>
VB.NET
C#
VB.NET
C#
VB.NET
C#
VB.NET
ListBox1.Items.Clear
C#
ListBox1.Items.Clear();
VB.NET
C#
VB.NET
C#
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
VB.NET
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");
16.9 How to select all the Items from a listbox when the user selects a
radio button?
VB.NET
C#
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
VaryByCustom - is a string that your application has to interpret in the GetVaryByCustomString override in
Now, to avoid caching pages for certain ProductIDs you can set the cacheability to private or nocache from
VB.NET
Response.Cache.SetCacheability(HttpCacheability.Private)
C#
Response.Cache.SetCacheability(HttpCacheability.Private) ;
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.
or
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.
or
VB.NET
Response.Cache.SetCacheability(HttpCacheability.NoCache)
C#
Response.Cache.SetCacheability(HttpCacheability.NoCache);
If the PDF files are on the disk, you should just let the IIS handle them. The IIS static file handler performs
You can attach a cache dependency to the response that is unique per query param, then invalidate the
VB.NET
C#
// add cache item dependency on response
string cacheKey = "webform1.aspx?" + queryParam;
Cache[cacheKey] = new object();
Response.AddCacheItemDependency(cacheKey);
You could add a dependency to the output cached control, and change the dependency to evict the control.
VB.NET
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;
}
VB.NET
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?) "?
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
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?
VB.NET
somevar=System.Web.HttpContext.Current.Cache(" ")
C#
somevar=System.Web.HttpContext.Current.Cache(" ");
Keep in mind that this can significantly increase the amount of memory used for caching, depending on how
Note: "*" is not recommended - it is best to use a list of params that your page truly varies by.
Use HttpRuntime.Cache
VB.NET
C#
VB.NET
C#
Try using "HttpContext.Current.Cache" instead of just "Cache" in your code. The compiler probably wasn't
VB.NET
C#
VB.NET
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 );
VB.NET
C#
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.
• Use Add or Remove Programs in the Windows Control Panel to launch Add/Remove Windows
Components.
• 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.
4. Select Only the list below, click Add and add the IP 127.0.0.1. This restricts connections to just the
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 server System.Web.Mail is running or can connect to the mail server. Some times
• Try specifying the value by IP address. Poor DNS resolution can sometimes hinder name lookups.
"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
VB.NET
C#
'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."
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.";
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;
}
VB.NET
C#
VB.NET
C#
VB.NET
C#
18.13 Why do I get the error message "Sender address rejected: need
fully-qualified address "?
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.
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?
VB.NET
C#
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
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
...
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) ;
...
VB.NET
C#
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
C#
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;
Try
VB.NET
Label1.BackColor = System.Drawing.Color.FromName("Green")
C#
Label1.BackColor = System.Drawing.Color.FromName("Green");
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
{
..
}
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
C#
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
'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#
//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?
VB.NET
C#
VB.NET
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#
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;
RadioButton control is designed to allow users to choose atleast one option from a list of available options.
21.3 How can I enforce that only one radiobutton gets selected among a
list of Radiobutton controls?
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>");
}
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();");
VB.NET
C#
HyperLink hpl = new HyperLink();
hpl.Text="Text";
hpl.NavigateUrl="http://www.syncfusion.com";
hpl.ID="theID";
Page.Controls[1].Controls.Add(hpl);
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"
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";
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#
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
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.
to In VB.NET
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.
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
TextBox1.ApplyStyle(textboxStyle)
Button1.ApplyStyle(buttonStyle)
CheckBox1.ApplyStyle(checkboxStyle)
C#
Create a function
In Page_Load
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;
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
For solution refer PRB: Access Denied Error When You Make Code Modifications with Index Services Running
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);
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
C#
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();
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
C#
VB.NET
'In Page_Load
DataBind()
C#
//In Page_Load
DataBind();
VB.NET
C#
You can set the EnableViewState property of the control. You should disable viewstate for any control that
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);
}
style="WORD-BREAK:break-all"
23.3 How to use a Table control to display data vertically?
VB.NET
C#
In IE5 and later, significantly faster Table Rendering is now possible. Here is some information in MSDN :
Among other things, you can specific col specific widths using the colgroup tag or col tag and also set the
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
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
-->
</browserCaps>
25.1 Why do I get the Columns twice in the datagrid. I am using
BoundColumns and TemplateColumns in DataGrid?
Set the Dataformatstring of the boundcolumn to {0:Nn} where n=> number of decimal points For more
VB.NET
C#
25.6 How to display only date part in the Datagrid if the Date is of
DateTime datatype in the database?
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
In the ItemDataBound event you can access the Cells() collection of the current Datagrid item (or row) and
VB.NET
C#
Check out How to open a new window with multiple parameters using datagrid?
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.
[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;}}
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,
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);
// 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"
The assembly will not be strong named in the above tag if it's not in the GAC.
VB.NET
Int32.Parse(TextBox1.Text)
C#
Int32.Parse(TextBox1.Text);
28.3 Why does TextBox retain its values when posting inspite of having
ViewState property disabled for TextBox,?
VB.NET
Textbox1.Text= dsData.Tables(0).Rows(0)("FieldName").ToString()
C#
TextBox1.Text=dsData.Tables[0].Rows[0]["FieldName"].ToString();
VB.NET
TextBox1.Style("text-align")="right"
C#
TextBox1.Style["text-align"]="right";
VB.NET
C#
string aprtxt;
aprtxt = (TextBox) e.Item.FindControl["txtapr"];
VB.NET
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.
VB.NET
C#
VB.NET
TextBox1.Width = Unit.Pixel(100)
C#
TextBox1.Width = Unit.Pixel(100);
<script lang="javascript">
function CheckFunction()
{
if (document.getElementById('<%=textbox2.ClientID%>').value == "")
{
alert("Please enter a value");
return;
}
}
</script>
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
C#
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
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();
}
}
You can use the TextBox webserver control and set the TextMode = MultiLine
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>
VB.NET
Protected colCon As New System.Drawing.ColorConverter
Protected bgcolor As String = "#556600"
'In Page_Load
Page.DataBind()
C#
//In Page_Load
Page.Databind();
VB.NET
C#
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
It's not recommend for to prefill a "Password" type TextBox with the("***") characters, though below is the
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#
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
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);
}
Method1
Method2
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"
29.5 How to add an extra item to the DropDownList filled with data from
a database?
VB.NET
C#
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.
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();
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
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 ;
VB.NET
C#
<appSettings>
<addkey="MyDBConnection"value="server=<ServerName>;uid=<Username>;pwd=
;database=<DBName>" />
</appSettings>
Example :
<addkey="ConnectionString"value="Server=localhost;uid=sa;pwd=;database=northwind" />
Probably you have mispelled the attribute. It should be verbs not verb
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.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 ;
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
}
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
C#
VB.NET
C#
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
}
VB.NET
Sample code 1
C#
Sample Code 2
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?
<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
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) ;
}
}
<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
C#
if(!Page.IsPostBack )
{
//...
}
On Button Click
VB.NET
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
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
Stored Procedure
VB.NET
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"]) + "
");
}
or
Use SqlDateTime.Null if you want to do it from your application. folowing vb.net shall be helpful .
VB.NET
Dim cn As SqlConnection
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)
sqldatenull = SqlDateTime.Null
cmd.Parameters("@FirstName").Value = txtFirstName.Text
cmd.Parameters("@LastName").Value = txtLastName.Text
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()
Catch ex As Exception
Label1.Text = ex.Message
Finally
cn.Close()
End Try
31.18 How to use Stored Procedures in ASP.NET?
C#
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 () +
"
");
}
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());
VB.NET
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?
VB.NET
C#
Before you read the data using DataReader open the Connection
VB.NET
C#
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.
This error is caused if there is no Connection object associated with the Command Object. To resolve this
VB.NET
C#
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
• 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
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.
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();
C#
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
C#
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
C#
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
or
or
VB.NET
C#
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#
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#
VB.NET
Dim strKey as string
For Each strKey In Session.Keys
Response.Write(strKey + " : " + Session(strKey).ToString() + "<br>")
Next
C#
• - First, check your web.config, machine.config and your page directive to make sure you have
o Session State
o @ Page
• - session state is not available just everywhere, anytime. It is available only after the
Events
A common case is that SharePoint application will remove this module from their web.config files (for
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.
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
32.7 Why are my Session variables lost frequently when using InProc
mode?
In v1, there is also a bug that will cause worker process to restart. It's fixed in SP2 and v1.1. See FIX:
32.8 Does session state have a locking mechanism that serialize the
access to state?
• 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
• That's why if two frames both have session state write access, one frame has to wait for the other to
finish first
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.
expiration time will be moved forward. Note that as long as a page has NOT disabled session state, it will
It depends on which event you're handling. Session is available only after AcquireRequestState event
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?
• 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
The Timeout setting is in minutes, not in seconds. i.e The timeout attribute specifies the number of minutes a
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
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.
VB.NET
To store in Session:
Session("SortedList1") = x
and to retrieve
C#
To store in Session:
Session["SortedList1"] = x;
and to retrieve
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
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
For HttpContext, it is not available because this event is not associated with any request.
In SQLServer mode, session expiration is carried out by the SQL Agent using a registered job. Make sure your
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
Include a sql trusted connection, or put the connection string as encrypted data in the registry. Refer
• How To Use the ASP.NET Utility to Encrypt Credentials and Session State Connection Strings
Use HttpContext.Current.Session
VB.NET
HttpContext.Current.Session("Value1") = "1"
C#
HttpContext.Current.Session["Value1"] = "1";
• InProc Mode- objects stored in session state are actually live objects, and so you can store whatever
• 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
(Right answer?) Refer What kind of objects can I store in Session State?
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
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
12. XML
13. CheckBoxList
14. AdRotator
15. Files
16. ListBox
More...
18. Mail
19. GDI+
21. RadioButton
22. Controls
24.1
25. DataGrid
28. TextBox
29. Dropdownlist
31. ADO.NET
32. Session