What is ASP.NET - Part
1
ASP.NET is a Web application framework developed by Microsoft to build dynamic data driven Web
applications and Web services.
1. ASP.NET is a subset of .NET framework. In simple terms a framework is a collection of classes.
2. ASP.NET is the successor to classic ASP (Active Server Pages).
What other technologies can be used to build web applications
1. PHP
2. Java
3. CGI
4. Ruby on Rails
5. Perl
What is a Web Application?
A web application is an application that is accessed by users using a web browser. Examples of web browsers include
1. Microsoft Internet Explorer
2. Google Chrome
3. Mozilla FireFox
4. Apple Safari
5. Netscape Navigator
What are the advantages of Web applications?
1. Web Applications just need to be installed only on the web server, where as desktop applications need to be installed on every computer, where you want to access them.
2. Maintenance, support and patches are easier to provide.
3. Only a browser is required on the client machine to access a web application.
4. Accessible from anywhere, provided there is internet.
5. Cross Platform
How Web applications work?
1. Web applications work on client/server architecture
2. On the client all you need is a browser, that can understand HTML
3. On the server side, the Web application runs under Microsoft Internet Information Services (IIS)

When the client enters the URL of the web application in the browser, and submits the request. The web server which hosts the web application, receives the request. The request is then processed by the application. The application generates, the HTML and hands it over to the IIS (web server). Finally, IIS sends the generated HTML to the client, who made the initial request. The client browser will the interpret the HTML and displays the user interface. All this communication, happens over the internet using HTTP protocol. HTTP stands for Hyper Text Transfer Protocol. A protocol is a set of rules that govern how two or more items communicate
1. ASP.NET is a subset of .NET framework. In simple terms a framework is a collection of classes.
2. ASP.NET is the successor to classic ASP (Active Server Pages).
What other technologies can be used to build web applications
1. PHP
2. Java
3. CGI
4. Ruby on Rails
5. Perl
What is a Web Application?
A web application is an application that is accessed by users using a web browser. Examples of web browsers include
1. Microsoft Internet Explorer
2. Google Chrome
3. Mozilla FireFox
4. Apple Safari
5. Netscape Navigator
What are the advantages of Web applications?
1. Web Applications just need to be installed only on the web server, where as desktop applications need to be installed on every computer, where you want to access them.
2. Maintenance, support and patches are easier to provide.
3. Only a browser is required on the client machine to access a web application.
4. Accessible from anywhere, provided there is internet.
5. Cross Platform
How Web applications work?
1. Web applications work on client/server architecture
2. On the client all you need is a browser, that can understand HTML
3. On the server side, the Web application runs under Microsoft Internet Information Services (IIS)

When the client enters the URL of the web application in the browser, and submits the request. The web server which hosts the web application, receives the request. The request is then processed by the application. The application generates, the HTML and hands it over to the IIS (web server). Finally, IIS sends the generated HTML to the client, who made the initial request. The client browser will the interpret the HTML and displays the user interface. All this communication, happens over the internet using HTTP protocol. HTTP stands for Hyper Text Transfer Protocol. A protocol is a set of rules that govern how two or more items communicate
Creating ASP.NET
website - Part 2
In this video session
1. We will learn about using visual studio
2. Creating your first ASP.NET web application
3. Learn about different windows in visual studio
Start Page in Visual Studio:
When you first run visual studio, you will see the start page. The start page contains latest news related to .NET development, learning and community resources. If you are using visual studio 2010, at the bottom of the start page, you will notice the following 2 options.
1. Close page after project load - Select this option if you want to close the start page, as soon as you open and load a project.
2. Show page on startup - Uncheck this option, if you don't want the start page to be shown, when you start visual studio.
If you have closed the start page, and later, if you want to see it again, select START PAGE from the VIEW menu.
Creating your first ASP.NET web application:
1. Select File => New Project
2. Select the Programming language you want to use from Installed Templates section, in the New Project dialog box. Out of the box, you can either use C# or Visual Basic to develop ASP.NET web applications.
3. Now, Select ASP.NET Web Application, from the middle section of the New Project dialog box.
4. Give your project and solution a meaningful name.
5. Select the location, where you want the solution to be created.
6. Finally click OK.

Different windows in visual studio:
At this point, you should have your first web application created. Now, let's shift our focus, to learn more about the windows that we see in visual studio.
Solution Explorer: To view the solution explorer window, from the VIEW menu, select SOLUTION EXPLORER. Or you can also use keyboard short cut, CTRL + W, S. On the solution explorer, use the AUTO-HIDE push pin button, to either show or hide solution explorer.

Visual Studio organizes applications into projects and solutions. A solution is a collection of projects. In our example, we have WebApplication2 solution. This solution has only one project - WebApplication2. If you want to add another project to the solution, simply right click the solution, and Select Add => New Project. For example, to add a class library project, select CLASS LIBRARY from the New Project dialog box and click OK.
At this point, your solution should contain 2 projects
1. A web Application Project - WebApplication2
2. A class library project - ClassLibrary1

Notice that, in the solution explorer, WebApplication2 project is bolded, indicating that this is the start up project. You can only have one start up project in a solution. If you want to change your start up project, RIGHT CLICK the project, and select "SET AS STARTUP PROJECT". The start-up project is the project that runs when you click Start in Visual Studio .NET. When you’re developing multiple projects as part of a single solution, the start-up project usually calls the other projects in the solution.
The solution file will have a .sln extension and the project file will have .csproj (if c# is the programming language) or .vbproj (if visual basic is the programming language)
Tool Box: To view the TOOL BOX, Select TOOL BOX from the VIEW menu, or use the keyboard short cut, CTRL + W, X. Just like, solution explorer, tool box can be auto hidden using the AUTO-HIDE PUSH PIN. Toolbox displays the controls and components that can be used on a web form.
Web Forms: WebForms has the extension of .aspx. A web form also has a code behind and designer files. Code behind files has the extension of .aspx.cs (if c# is the programming language) or .aspx.vb (if vb is the programming language). Designer files contains the extension of .aspx.designer.cs (if c# is the programming language) or .aspx.designer.vb (if visual basic is the programming language). Code behind files contain the code that user writes, where as the designer file contains the auto generated code. You shouldn't change the code in the designer file, because that code might later be modified by Visual Studio and your changes could be overwritten. A Web form is associated with its code file using the @Page directive found in the Web form’s HTML.
<%@ Page Title="Home Page" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebApplication2._Default" %>
A webform's HTML can be edited either in Source or Design mode. You can also choose SPLIT mode, which shows both the DESIGN and the SOURCE at the same time.

Properties Window: Used to change property of a webform or a control on a webform. To view the Properties window, select PROPERTIES WINDOW from the VIEW menu, or use keyboard short cut CTRL + W, P.
1. We will learn about using visual studio
2. Creating your first ASP.NET web application
3. Learn about different windows in visual studio
Start Page in Visual Studio:
When you first run visual studio, you will see the start page. The start page contains latest news related to .NET development, learning and community resources. If you are using visual studio 2010, at the bottom of the start page, you will notice the following 2 options.
1. Close page after project load - Select this option if you want to close the start page, as soon as you open and load a project.
2. Show page on startup - Uncheck this option, if you don't want the start page to be shown, when you start visual studio.
If you have closed the start page, and later, if you want to see it again, select START PAGE from the VIEW menu.
Creating your first ASP.NET web application:
1. Select File => New Project
2. Select the Programming language you want to use from Installed Templates section, in the New Project dialog box. Out of the box, you can either use C# or Visual Basic to develop ASP.NET web applications.
3. Now, Select ASP.NET Web Application, from the middle section of the New Project dialog box.
4. Give your project and solution a meaningful name.
5. Select the location, where you want the solution to be created.
6. Finally click OK.

Different windows in visual studio:
At this point, you should have your first web application created. Now, let's shift our focus, to learn more about the windows that we see in visual studio.
Solution Explorer: To view the solution explorer window, from the VIEW menu, select SOLUTION EXPLORER. Or you can also use keyboard short cut, CTRL + W, S. On the solution explorer, use the AUTO-HIDE push pin button, to either show or hide solution explorer.

Visual Studio organizes applications into projects and solutions. A solution is a collection of projects. In our example, we have WebApplication2 solution. This solution has only one project - WebApplication2. If you want to add another project to the solution, simply right click the solution, and Select Add => New Project. For example, to add a class library project, select CLASS LIBRARY from the New Project dialog box and click OK.
At this point, your solution should contain 2 projects
1. A web Application Project - WebApplication2
2. A class library project - ClassLibrary1

Notice that, in the solution explorer, WebApplication2 project is bolded, indicating that this is the start up project. You can only have one start up project in a solution. If you want to change your start up project, RIGHT CLICK the project, and select "SET AS STARTUP PROJECT". The start-up project is the project that runs when you click Start in Visual Studio .NET. When you’re developing multiple projects as part of a single solution, the start-up project usually calls the other projects in the solution.
The solution file will have a .sln extension and the project file will have .csproj (if c# is the programming language) or .vbproj (if visual basic is the programming language)
Tool Box: To view the TOOL BOX, Select TOOL BOX from the VIEW menu, or use the keyboard short cut, CTRL + W, X. Just like, solution explorer, tool box can be auto hidden using the AUTO-HIDE PUSH PIN. Toolbox displays the controls and components that can be used on a web form.
Web Forms: WebForms has the extension of .aspx. A web form also has a code behind and designer files. Code behind files has the extension of .aspx.cs (if c# is the programming language) or .aspx.vb (if vb is the programming language). Designer files contains the extension of .aspx.designer.cs (if c# is the programming language) or .aspx.designer.vb (if visual basic is the programming language). Code behind files contain the code that user writes, where as the designer file contains the auto generated code. You shouldn't change the code in the designer file, because that code might later be modified by Visual Studio and your changes could be overwritten. A Web form is associated with its code file using the @Page directive found in the Web form’s HTML.
<%@ Page Title="Home Page" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebApplication2._Default" %>
A webform's HTML can be edited either in Source or Design mode. You can also choose SPLIT mode, which shows both the DESIGN and the SOURCE at the same time.

Properties Window: Used to change property of a webform or a control on a webform. To view the Properties window, select PROPERTIES WINDOW from the VIEW menu, or use keyboard short cut CTRL + W, P.
In this video session, we will learn about
1. Stateless nature of HTTP protocol
2. How a webform is processed
3. What is ViewState
4. The role of ViewState in ASP.NET
5. Primary difference between ASP.NET Server controls and HTML controls
Web Applications work on HTTP protocol. HTTP protocol is a stateless protocol, meaning it does not retain state between user requests. Let's understand the stateless nature of the HTTP protocol with an example.
Create a new asp.net web application project. Drag and drop a TextBox and a Button control onto the webform. Change the Text property of the Button control to Click Me.
At this point, double click the button control, which should generate the event handler in the code behind file. Modify the code behind file, so the code in WebForm1 class looks as shown below.
1. In the scope of WebForm1 class, we are creating an integer variable ClicksCount which is initialized to ZERO.
2. On the Page_Load() event handler, we are setting the Text property of TextBox1 to ZERO. We do this initialization, only, when the request is an initial GET request.
3. In the Button1_Click() event, we are incrementing the value of the ClicksCount by 1, and then assigning the value to the Text property of TextBox1.
public partial class WebForm1 : System.Web.UI.Page
{
int ClicksCount = 0;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
TextBox1.Text = "0";
}
}
protected void Button1_Click(object sender, EventArgs e)
{
ClicksCount = ClicksCount + 1;
TextBox1.Text = ClicksCount.ToString();
}
}
With this code in place, run the application, and click the Button. We expect the count to be increased every time we click the button. When you click it the first time, it gets incremented to 1. After that, no matter how many times you click it, the value stays at 1. This is because of the stateless nature of the web applications that work on HTTP protocol.
So what actually happens when you make a GET request for this WebForm1?
When we compile this project an assembly is generated. Since the name of the project is ViewStateDemo, the name of the assembly will be ViewStateDemo.dll. So when a request is made for WebForm1, The application's assembly(ViewStateDemo.dll) creates an instance (object), of WebForm1, initializes ClicksCount to ZERO, and set's the TextBox1.Text to ZERO. As this is the initial GET request, the Button1_Click() event will not be executed. At this point the web server, generates the HTML to respond to the request, and posts that response back to the browser. It then immediately destroys the instance of the WebForm1.
The browser receives the HTML, and we should now see textbox set to ZERO.
What happens when we click the Button on WebForm1?
When we click the Button, the WebForm1 gets posted to the server. This is a PostBack request, NOT A GET REQUEST. So, when the webform is posted back, a new instance of this webform is created again, initializing the ClicksCount variable to ZERO. This time, the code that is wrapped between IF(!ISPOSTBACK) block is not executed. Button1_Click() event gets executed as this is a PostBack event. ClicksCount is incremented from 0 to 1. The value is then assigned to the Text Property of TextBox1. Generates the HTML, sends it to client and destroys the webform.
At this Point, we should see the value increased to 1.
What happens when we click the Button on WebForm1 again?
When you click the button for the second time, the webform gets posted back again. A new instance of WebForm1 is created. ClicksCount initialized to ZERO. In the Button1_Click() event, the value gets incremented to 1 and assigned to TextBox1. HTML gets generated and sends it to client and destroys the webform.
So, no matter how many times you click the Button, the value of the TextBox, will not move beyond 1.
Now, let's see, how to preserve the state between requests using ViewState variables. Re-write the code in WebForm1, as shown below.
public partial class WebForm1 : System.Web.UI.Page
{
int ClicksCount = 1;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
TextBox1.Text = "0";
}
}
protected void Button1_Click(object sender, EventArgs e)
{
if(ViewState["Clicks"] != null)
{
ClicksCount = (int)ViewState["Clicks"] + 1;
}
TextBox1.Text = ClicksCount.ToString(); ;
ViewState["Clicks"] = ClicksCount;
}
}
Click the Button now, and the value gets incremented every time we click. So how is this possible now. It's possible because, we are using the ViewState variable Clicks to preserve the data between requests. The ViewState data, travels with every request and response between the client and the web server.
Now, let's try to achieve the same behaviour, without explicitly storing data in a ViewState variable. Modify the WebForm1 code as shown below.
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
TextBox1.Text = "0";
}
}
protected void Button1_Click(object sender, EventArgs e)
{
int ClicksCount = Convert.ToInt32(TextBox1.Text) + 1;
TextBox1.Text = ClicksCount.ToString();
}
}
Upon clicking the Button, the value gets incremented correctly as expected. This is possible because, TextBox1 is an asp.net server control, that uses viewstate internally, to preserve data across postbacks.
Because Web forms have very short lifetimes, ASP.NET takes special steps to preserve the data entered in the controls on a Web form. Data entered in controls is sent with each request and restored to controls in Page_Init. The data in these controls is then available in the Page_Load(), Button_Click(), and many more events, that occur after Page_Init() event. We will discuss about, all the events in the life cycle of a webform and the order in which they occur in a later video session.
On the other hand the HTML controls, do not retain state across post backs. Only ASP.NET server controls retains state. To prove this
1. Add a new webform to the web application project
2. Drag and Drop Input(Text) control from the HTML tab, in the ToolBox
3. Drag and Drop TextBox control from the Standard tab, in the ToolBox
4. Finally drag and drop a button
5. Set the newly added webform as the start page by right clicking on it, in the solution explorer
6. Run the project, by pressing CTRL + F5
7. Type "TEST" into both the controls (ASP.NET TextBox and the HTML TextBox), and press the button
8. You should see that, the value in the ASP.NET TextBox is preserved across postback, but not the value in the standard HTML textbox
An HTML control can be converted in ASP.NET server control, by adding runat="server" attribute in the HTML source as shown below.
<input id="Text1" runat = "server" type="text" />
Now, if you type TEST and click the button, both controls now retain state across postback.
ViewState data is serialized into base64-encoded strings, and is stored in Hidden input field __ViewState. To view this hidden input field, right click on the browser and select "View Page Source" for google chrome. In internet explorer, right click and select "View Source" vents in the life cycle of a web application - Part 4
1. Stateless nature of HTTP protocol
2. How a webform is processed
3. What is ViewState
4. The role of ViewState in ASP.NET
5. Primary difference between ASP.NET Server controls and HTML controls
Web Applications work on HTTP protocol. HTTP protocol is a stateless protocol, meaning it does not retain state between user requests. Let's understand the stateless nature of the HTTP protocol with an example.
Create a new asp.net web application project. Drag and drop a TextBox and a Button control onto the webform. Change the Text property of the Button control to Click Me.
At this point, double click the button control, which should generate the event handler in the code behind file. Modify the code behind file, so the code in WebForm1 class looks as shown below.
1. In the scope of WebForm1 class, we are creating an integer variable ClicksCount which is initialized to ZERO.
2. On the Page_Load() event handler, we are setting the Text property of TextBox1 to ZERO. We do this initialization, only, when the request is an initial GET request.
3. In the Button1_Click() event, we are incrementing the value of the ClicksCount by 1, and then assigning the value to the Text property of TextBox1.
public partial class WebForm1 : System.Web.UI.Page
{
int ClicksCount = 0;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
TextBox1.Text = "0";
}
}
protected void Button1_Click(object sender, EventArgs e)
{
ClicksCount = ClicksCount + 1;
TextBox1.Text = ClicksCount.ToString();
}
}
With this code in place, run the application, and click the Button. We expect the count to be increased every time we click the button. When you click it the first time, it gets incremented to 1. After that, no matter how many times you click it, the value stays at 1. This is because of the stateless nature of the web applications that work on HTTP protocol.
So what actually happens when you make a GET request for this WebForm1?
When we compile this project an assembly is generated. Since the name of the project is ViewStateDemo, the name of the assembly will be ViewStateDemo.dll. So when a request is made for WebForm1, The application's assembly(ViewStateDemo.dll) creates an instance (object), of WebForm1, initializes ClicksCount to ZERO, and set's the TextBox1.Text to ZERO. As this is the initial GET request, the Button1_Click() event will not be executed. At this point the web server, generates the HTML to respond to the request, and posts that response back to the browser. It then immediately destroys the instance of the WebForm1.
The browser receives the HTML, and we should now see textbox set to ZERO.
What happens when we click the Button on WebForm1?
When we click the Button, the WebForm1 gets posted to the server. This is a PostBack request, NOT A GET REQUEST. So, when the webform is posted back, a new instance of this webform is created again, initializing the ClicksCount variable to ZERO. This time, the code that is wrapped between IF(!ISPOSTBACK) block is not executed. Button1_Click() event gets executed as this is a PostBack event. ClicksCount is incremented from 0 to 1. The value is then assigned to the Text Property of TextBox1. Generates the HTML, sends it to client and destroys the webform.
At this Point, we should see the value increased to 1.
What happens when we click the Button on WebForm1 again?
When you click the button for the second time, the webform gets posted back again. A new instance of WebForm1 is created. ClicksCount initialized to ZERO. In the Button1_Click() event, the value gets incremented to 1 and assigned to TextBox1. HTML gets generated and sends it to client and destroys the webform.
So, no matter how many times you click the Button, the value of the TextBox, will not move beyond 1.
Now, let's see, how to preserve the state between requests using ViewState variables. Re-write the code in WebForm1, as shown below.
public partial class WebForm1 : System.Web.UI.Page
{
int ClicksCount = 1;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
TextBox1.Text = "0";
}
}
protected void Button1_Click(object sender, EventArgs e)
{
if(ViewState["Clicks"] != null)
{
ClicksCount = (int)ViewState["Clicks"] + 1;
}
TextBox1.Text = ClicksCount.ToString(); ;
ViewState["Clicks"] = ClicksCount;
}
}
Click the Button now, and the value gets incremented every time we click. So how is this possible now. It's possible because, we are using the ViewState variable Clicks to preserve the data between requests. The ViewState data, travels with every request and response between the client and the web server.
Now, let's try to achieve the same behaviour, without explicitly storing data in a ViewState variable. Modify the WebForm1 code as shown below.
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
TextBox1.Text = "0";
}
}
protected void Button1_Click(object sender, EventArgs e)
{
int ClicksCount = Convert.ToInt32(TextBox1.Text) + 1;
TextBox1.Text = ClicksCount.ToString();
}
}
Upon clicking the Button, the value gets incremented correctly as expected. This is possible because, TextBox1 is an asp.net server control, that uses viewstate internally, to preserve data across postbacks.
Because Web forms have very short lifetimes, ASP.NET takes special steps to preserve the data entered in the controls on a Web form. Data entered in controls is sent with each request and restored to controls in Page_Init. The data in these controls is then available in the Page_Load(), Button_Click(), and many more events, that occur after Page_Init() event. We will discuss about, all the events in the life cycle of a webform and the order in which they occur in a later video session.
On the other hand the HTML controls, do not retain state across post backs. Only ASP.NET server controls retains state. To prove this
1. Add a new webform to the web application project
2. Drag and Drop Input(Text) control from the HTML tab, in the ToolBox
3. Drag and Drop TextBox control from the Standard tab, in the ToolBox
4. Finally drag and drop a button
5. Set the newly added webform as the start page by right clicking on it, in the solution explorer
6. Run the project, by pressing CTRL + F5
7. Type "TEST" into both the controls (ASP.NET TextBox and the HTML TextBox), and press the button
8. You should see that, the value in the ASP.NET TextBox is preserved across postback, but not the value in the standard HTML textbox
An HTML control can be converted in ASP.NET server control, by adding runat="server" attribute in the HTML source as shown below.
<input id="Text1" runat = "server" type="text" />
Now, if you type TEST and click the button, both controls now retain state across postback.
ViewState data is serialized into base64-encoded strings, and is stored in Hidden input field __ViewState. To view this hidden input field, right click on the browser and select "View Page Source" for google chrome. In internet explorer, right click and select "View Source" vents in the life cycle of a web application - Part 4
In a web application, events can occur at 3 levels
1. At the Application Level(Example: Application Start)
2. At the Page Level(Example: Page Load)
3. At the Control Level (Example: Button Click)
In this video, we will learn about Application Level events. Before understanding Application level events, lets talk about Session State and Application State variables. In Part 3 of this video series we have learnt about ViewState. ViewState variables are used to preserve data across page post back. By default, ViewState of one webform is not available in another webform.
For example, if you define ViewState["MyData"] = "View State Example" in WebForm1. ViewState["MyData"] is only available in WebForm1. ViewState["MyData"] will be null on any other web form in the application.
If you want to make your data available on multiple web forms, there are several techniques in ASP.NET, as listed below.
1. Query Strings
2. Cookies
3. Session State
4. Application State
We will discuss about Query Strings and Cookies in a later video.
Session state variables are available across all pages, but only for a given single session. Session variables are like single-user global data. Only the current session has access to its Session state.
Application State variables are available across all pages and across all sessions. Application State variables are like multi-user global data. All sessions can read and write Application State variables.
In an ASP.NET web application, Global.asax file conatins the application level events.
void Application_Start(object sender, EventArgs e)
{
// Code that runs on application startup
}
void Application_End(object sender, EventArgs e)
{
// Code that runs on application shutdown
}
void Application_Error(object sender, EventArgs e)
{
// Code that runs when an unhandled error occurs
}
void Session_Start(object sender, EventArgs e)
{
// Code that runs when a new session is started
}
void Session_End(object sender, EventArgs e)
{
// Code that runs when a session ends.
// Note: The Session_End event is raised only when the sessionstate mode
// is set to InProc in the Web.config file. If session mode is set to StateServer
// or SQLServer, the event is not raised.
}
In general, Application events are used to initialize data that needs to be available to all the current sessions of the application. Where as Session events are used to initialize data that needs to be available only for a given individual session, but not between multiple sessions.
Now, let's write a simple application, using session and application level events. Create a new asp.net web application, and copy paste the following code in Global.asax file.
1. Application_Start() event gets fired, when a first request is made, and if the application is not already running.
2. Session_Start() event is fired every time a new browser instance, with a different session-id, visits the application.
3. Session_End() event is fired when the user session times out. The default is 20 minutes. This can be configured in the web.config file.
void Application_Start(object sender, EventArgs e)
{
// Create Application state variables
Application["TotalApplications"] = 0;
Application["TotalUserSessions"] = 0;
// Increment TotalApplications by 1
Application["TotalApplications"] = (int)Application["TotalApplications"] + 1;
}
void Session_Start(object sender, EventArgs e)
{
// Increment TotalUserSessions by 1
Application["TotalUserSessions"] = (int)Application["TotalUserSessions"] + 1;
}
void Session_End(object sender, EventArgs e)
{
// Decrement TotalUserSessions by 1
Application["TotalUserSessions"] = (int)Application["TotalUserSessions"] - 1;
}
Copy and paste the following code in WebForm1.aspx.
protected void Page_Load(object sender, EventArgs e)
{
Response.Write("Number of Applications: " + Application["TotalApplications"]);
Response.Write("<br/>");
Response.Write("Number of Users Online: " + Application["TotalUserSessions"]);
}
Now, when you run the application, you get the following output:
Number of Applications: 1
Number of Users Online: 1
Copy the URL and open a new instance of the browser. Paste the URL and press enter. In the new instance of the browser, we still see the same output.
We expected the Number of Users Online to be 2. The new instance of the browser, is treated as part of the same session, because, by default the browser uses cookies to store session id. The session id is read from the same cookie when you opened the new browser window. Hence, Number of Users Online is not incremented.
How to get a new session-id and force the Session_Start() event to execute?
1. Close the browser: Close the existing browser window, which automatically deletes the session cookie. Now, open a new brwoser instance. Since, the existing session cookie associated with the previous browser instance is deleted. The new instance of the browser, will get a new session-id and a session cookie.Now, if you navigate to WebForm1.aspx, Session_Start() event gets fired and Number of Users Online is incremented to 2.
2. Open a new instance of a different browser: For example, if you first visited the application with Google Chrome, now try accessing the same page with internet explorer, Session_Start() event gets fired and Number of Users Online is incremented to 2.
3. Use Cookie-less Sessions: To use cookie-less sessions set the cookieless attribute to true in web.config as shown below.
<sessionState mode="InProc" cookieless="false"></sessionState>
What is a Session, in a web application?
A session is a unique instance of the browser. A single user can have multiple sessions, by visiting your application, with multiple instances of the browser running with a different session-id on his machine.
1. At the Application Level(Example: Application Start)
2. At the Page Level(Example: Page Load)
3. At the Control Level (Example: Button Click)
In this video, we will learn about Application Level events. Before understanding Application level events, lets talk about Session State and Application State variables. In Part 3 of this video series we have learnt about ViewState. ViewState variables are used to preserve data across page post back. By default, ViewState of one webform is not available in another webform.
For example, if you define ViewState["MyData"] = "View State Example" in WebForm1. ViewState["MyData"] is only available in WebForm1. ViewState["MyData"] will be null on any other web form in the application.
If you want to make your data available on multiple web forms, there are several techniques in ASP.NET, as listed below.
1. Query Strings
2. Cookies
3. Session State
4. Application State
We will discuss about Query Strings and Cookies in a later video.
Session state variables are available across all pages, but only for a given single session. Session variables are like single-user global data. Only the current session has access to its Session state.
Application State variables are available across all pages and across all sessions. Application State variables are like multi-user global data. All sessions can read and write Application State variables.
In an ASP.NET web application, Global.asax file conatins the application level events.
void Application_Start(object sender, EventArgs e)
{
// Code that runs on application startup
}
void Application_End(object sender, EventArgs e)
{
// Code that runs on application shutdown
}
void Application_Error(object sender, EventArgs e)
{
// Code that runs when an unhandled error occurs
}
void Session_Start(object sender, EventArgs e)
{
// Code that runs when a new session is started
}
void Session_End(object sender, EventArgs e)
{
// Code that runs when a session ends.
// Note: The Session_End event is raised only when the sessionstate mode
// is set to InProc in the Web.config file. If session mode is set to StateServer
// or SQLServer, the event is not raised.
}
In general, Application events are used to initialize data that needs to be available to all the current sessions of the application. Where as Session events are used to initialize data that needs to be available only for a given individual session, but not between multiple sessions.
Now, let's write a simple application, using session and application level events. Create a new asp.net web application, and copy paste the following code in Global.asax file.
1. Application_Start() event gets fired, when a first request is made, and if the application is not already running.
2. Session_Start() event is fired every time a new browser instance, with a different session-id, visits the application.
3. Session_End() event is fired when the user session times out. The default is 20 minutes. This can be configured in the web.config file.
void Application_Start(object sender, EventArgs e)
{
// Create Application state variables
Application["TotalApplications"] = 0;
Application["TotalUserSessions"] = 0;
// Increment TotalApplications by 1
Application["TotalApplications"] = (int)Application["TotalApplications"] + 1;
}
void Session_Start(object sender, EventArgs e)
{
// Increment TotalUserSessions by 1
Application["TotalUserSessions"] = (int)Application["TotalUserSessions"] + 1;
}
void Session_End(object sender, EventArgs e)
{
// Decrement TotalUserSessions by 1
Application["TotalUserSessions"] = (int)Application["TotalUserSessions"] - 1;
}
Copy and paste the following code in WebForm1.aspx.
protected void Page_Load(object sender, EventArgs e)
{
Response.Write("Number of Applications: " + Application["TotalApplications"]);
Response.Write("<br/>");
Response.Write("Number of Users Online: " + Application["TotalUserSessions"]);
}
Now, when you run the application, you get the following output:
Number of Applications: 1
Number of Users Online: 1
Copy the URL and open a new instance of the browser. Paste the URL and press enter. In the new instance of the browser, we still see the same output.
We expected the Number of Users Online to be 2. The new instance of the browser, is treated as part of the same session, because, by default the browser uses cookies to store session id. The session id is read from the same cookie when you opened the new browser window. Hence, Number of Users Online is not incremented.
How to get a new session-id and force the Session_Start() event to execute?
1. Close the browser: Close the existing browser window, which automatically deletes the session cookie. Now, open a new brwoser instance. Since, the existing session cookie associated with the previous browser instance is deleted. The new instance of the browser, will get a new session-id and a session cookie.Now, if you navigate to WebForm1.aspx, Session_Start() event gets fired and Number of Users Online is incremented to 2.
2. Open a new instance of a different browser: For example, if you first visited the application with Google Chrome, now try accessing the same page with internet explorer, Session_Start() event gets fired and Number of Users Online is incremented to 2.
3. Use Cookie-less Sessions: To use cookie-less sessions set the cookieless attribute to true in web.config as shown below.
<sessionState mode="InProc" cookieless="false"></sessionState>
What is a Session, in a web application?
A session is a unique instance of the browser. A single user can have multiple sessions, by visiting your application, with multiple instances of the browser running with a different session-id on his machine.
Suggested videos
before continuing with this session
Part 3 - View State in ASP.NET
Part 4 - Events in the life cycle of a web application
Let's understand the differences, with an example. Create a new asp.net web application.
ViewState:
Add a new WebForm, to the project and name it ViewState1.aspx. Drag and drop a button and a text box control onto the webform. Double click the button control on the webform. This automatically generates the event handler, for the button control.
Now add another webform, to the project, with name ViewState2.aspx. Just like you have done for ViewState1.aspx, drag and drop a TextBox and a Button control onto this webform as well.
Now, copy and paste the following code in ViewState1.aspx.cs and ViewState2.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
if (ViewState["Clicks"] == null)
{
ViewState["Clicks"] = 0;
}
TextBox1.Text = ViewState["Clicks"].ToString();
}
}
protected void Button1_Click(object sender, EventArgs e)
{
int ClicksCount = (int)ViewState["Clicks"] + 1;
TextBox1.Text = ClicksCount.ToString();
ViewState["Clicks"] = ClicksCount;
}
Now, run the application, and navigate to ViewState1.aspx. Click the button control. Everytime, you click the button, the clicks count get incremented and is displayed in the TextBox, as expected.
Now, navigate to ViewState2.aspx. Click the button, on this page. Notice, that the value starts from ZERO, indicating that, each page has it's own ViewState["Clicks"].
So, the conclusion is that, ViewState of a webform is available only with in that webform, by default.
So, where does this viewstate, gets stored - On the client or on the server? ViewState is stored on the page using a hidden field called _ViewState. So, ViewState travels along with the page, between the client and the server, with each request and response.
ASP.NET uses viewstate, to retain the values a user types into controls on the webform, across postbacks.
SessionState:
Add a new webform with name SessionState1.aspx. Drag and drop a button and a text box control onto SessionState1.aspx. Do the same thing by adding a page with name SessionState2.aspx.
Copy and paste the following code in SessionState1.aspx.cs and SessionState2.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
if (Session["Clicks"] == null)
{
Session["Clicks"] = 0;
}
TextBox1.Text = Session["Clicks"].ToString();
}
}
protected void Button1_Click(object sender, EventArgs e)
{
int ClicksCount = (int)Session["Clicks"] + 1;
TextBox1.Text = ClicksCount.ToString();
Session["Clicks"] = ClicksCount;
}
Add the following sessionstate element to your web.config file, under system.web. This setting, specifies the web application to use cookieless sessions.
<sessionState mode="InProc" cookieless="true"></sessionState>
Run the application and navigate to SessionState1.aspx. Click the button 3 times, and notice that, the value 3 is displayed in the TextBox. Now, navigate to SessionState2.aspx. The value 3 is displayed in the TextBox on SessionState2.aspx. Now, click twice, the value is incremented to 5. Now, navigate back to SessionState1.aspx, and you should see the value 5. This proves that a session state variable is accessible across all pages in a web application.
Now, open a new browser window and navigate to SessionState1.aspx (Make sure you have a different session-id). Notice that, the value in the textbox is ZERO. So, this proves that, Session state variables are available across all pages, but only for a given single session. Session variables are like single-user global data. Only the current session has access to its Session state.
Application State:
Add a new webform with name ApplicationState1.aspx. Drag and drop a button and a text box control onto ApplicationState1.aspx. Do the same thing by adding a page with name ApplicationState2.aspx.
Copy and paste the following code in ApplicationState1.aspx.cs and ApplicationState2.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
if (Application["Clicks"] == null)
{
Application["Clicks"] = 0;
}
TextBox1.Text = Application["Clicks"].ToString();
}
}
protected void Button1_Click(object sender, EventArgs e)
{
int ClicksCount = (int)Application["Clicks"] + 1;
TextBox1.Text = ClicksCount.ToString();
Application["Clicks"] = ClicksCount;
}
Run the application and navigate to ApplicationState1.aspx. Click the button 3 times, and notice that, the value 3 is displayed in the TextBox. Now, navigate to ApplicationState2.aspx. The value 3 is displayed in the TextBox on ApplicationState2.aspx. Now, click twice, the value is incremented to 5. Now, navigate back to ApplicationState1.aspx, and you should see the value 5. This proves that an application state variable is accessible across all pages in a web application.
Now, open a new browser window and navigate to ApplicationState1.aspx. Notice that, the value in the textbox is still 5. So, this proves that, Application State variables are available across all pages and across all sessions. Application State variables are like multi-user global data. All sessions can read and write Application State variables.
So, in short, the differences are as follows
ViewState:
1. ViewState of a webform is available only with in that webform
2. ViewState is stored on the page in a hidden field called _ViewState. Because of this, the ViewState, will be lost, if you navigate awaya from the page, or if the broswer is closed.
3. ViewState is used by all asp.net controls to retain their state across postback
Session State:
1. Session state variables are available across all pages, but only for a given single session. Session variables are like single-user global data.
2. Session state variables are stored on the web server.
3. SessionState variables are cleared, when the user session times out. The default is 20 minutes. This is configurable in web.config
Application State:
1. Application State variables are available across all pages and across all sessions. Application State variables are like multi-user global data.
2. Application State variables are stored on the web server.
3. Application State variables are cleared, when the process hosting the application is restarted.
Part 3 - View State in ASP.NET
Part 4 - Events in the life cycle of a web application
Let's understand the differences, with an example. Create a new asp.net web application.
ViewState:
Add a new WebForm, to the project and name it ViewState1.aspx. Drag and drop a button and a text box control onto the webform. Double click the button control on the webform. This automatically generates the event handler, for the button control.
Now add another webform, to the project, with name ViewState2.aspx. Just like you have done for ViewState1.aspx, drag and drop a TextBox and a Button control onto this webform as well.
Now, copy and paste the following code in ViewState1.aspx.cs and ViewState2.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
if (ViewState["Clicks"] == null)
{
ViewState["Clicks"] = 0;
}
TextBox1.Text = ViewState["Clicks"].ToString();
}
}
protected void Button1_Click(object sender, EventArgs e)
{
int ClicksCount = (int)ViewState["Clicks"] + 1;
TextBox1.Text = ClicksCount.ToString();
ViewState["Clicks"] = ClicksCount;
}
Now, run the application, and navigate to ViewState1.aspx. Click the button control. Everytime, you click the button, the clicks count get incremented and is displayed in the TextBox, as expected.
Now, navigate to ViewState2.aspx. Click the button, on this page. Notice, that the value starts from ZERO, indicating that, each page has it's own ViewState["Clicks"].
So, the conclusion is that, ViewState of a webform is available only with in that webform, by default.
So, where does this viewstate, gets stored - On the client or on the server? ViewState is stored on the page using a hidden field called _ViewState. So, ViewState travels along with the page, between the client and the server, with each request and response.
ASP.NET uses viewstate, to retain the values a user types into controls on the webform, across postbacks.
SessionState:
Add a new webform with name SessionState1.aspx. Drag and drop a button and a text box control onto SessionState1.aspx. Do the same thing by adding a page with name SessionState2.aspx.
Copy and paste the following code in SessionState1.aspx.cs and SessionState2.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
if (Session["Clicks"] == null)
{
Session["Clicks"] = 0;
}
TextBox1.Text = Session["Clicks"].ToString();
}
}
protected void Button1_Click(object sender, EventArgs e)
{
int ClicksCount = (int)Session["Clicks"] + 1;
TextBox1.Text = ClicksCount.ToString();
Session["Clicks"] = ClicksCount;
}
Add the following sessionstate element to your web.config file, under system.web. This setting, specifies the web application to use cookieless sessions.
<sessionState mode="InProc" cookieless="true"></sessionState>
Run the application and navigate to SessionState1.aspx. Click the button 3 times, and notice that, the value 3 is displayed in the TextBox. Now, navigate to SessionState2.aspx. The value 3 is displayed in the TextBox on SessionState2.aspx. Now, click twice, the value is incremented to 5. Now, navigate back to SessionState1.aspx, and you should see the value 5. This proves that a session state variable is accessible across all pages in a web application.
Now, open a new browser window and navigate to SessionState1.aspx (Make sure you have a different session-id). Notice that, the value in the textbox is ZERO. So, this proves that, Session state variables are available across all pages, but only for a given single session. Session variables are like single-user global data. Only the current session has access to its Session state.
Application State:
Add a new webform with name ApplicationState1.aspx. Drag and drop a button and a text box control onto ApplicationState1.aspx. Do the same thing by adding a page with name ApplicationState2.aspx.
Copy and paste the following code in ApplicationState1.aspx.cs and ApplicationState2.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
if (Application["Clicks"] == null)
{
Application["Clicks"] = 0;
}
TextBox1.Text = Application["Clicks"].ToString();
}
}
protected void Button1_Click(object sender, EventArgs e)
{
int ClicksCount = (int)Application["Clicks"] + 1;
TextBox1.Text = ClicksCount.ToString();
Application["Clicks"] = ClicksCount;
}
Run the application and navigate to ApplicationState1.aspx. Click the button 3 times, and notice that, the value 3 is displayed in the TextBox. Now, navigate to ApplicationState2.aspx. The value 3 is displayed in the TextBox on ApplicationState2.aspx. Now, click twice, the value is incremented to 5. Now, navigate back to ApplicationState1.aspx, and you should see the value 5. This proves that an application state variable is accessible across all pages in a web application.
Now, open a new browser window and navigate to ApplicationState1.aspx. Notice that, the value in the textbox is still 5. So, this proves that, Application State variables are available across all pages and across all sessions. Application State variables are like multi-user global data. All sessions can read and write Application State variables.
So, in short, the differences are as follows
ViewState:
1. ViewState of a webform is available only with in that webform
2. ViewState is stored on the page in a hidden field called _ViewState. Because of this, the ViewState, will be lost, if you navigate awaya from the page, or if the broswer is closed.
3. ViewState is used by all asp.net controls to retain their state across postback
Session State:
1. Session state variables are available across all pages, but only for a given single session. Session variables are like single-user global data.
2. Session state variables are stored on the web server.
3. SessionState variables are cleared, when the user session times out. The default is 20 minutes. This is configurable in web.config
Application State:
1. Application State variables are available across all pages and across all sessions. Application State variables are like multi-user global data.
2. Application State variables are stored on the web server.
3. Application State variables are cleared, when the process hosting the application is restarted.
ASP.NET Page Life
Cycle Events - Part 6
Suggested videos before continuing with this session
Part 3 - Understanding ViewState
Part 4 - Events in the life cycle of a web application
Part 5 - Difference between ViewState, SessionState and ApplicationState
In Part 4, of this video series, we have discussed that, events can occur at 3 levels in an asp.net web application.
1. At the application level. (Example - Session_Start event in global.asax)
2. At the Page or web form level (Example - Page_Load)
3. At the control level(Example - Selected Index changed event of a dropdownlist)
In this video, we will discuss about events at the page level. From the previous,parts of this video series, we have learnt that, web applications work on a stateless protocol. Every time a request is made for a webform, the following sequence of events occur.
1. Web Application creates an instance of the requested webform.
2. Processes the events of the webform.
3. Generates the HTML, and sends the HTML back to the requested client.
4. The webform gets destroyed and removed from the memory.
The following are some of the commonly used events in the life cycle of an asp.net webform. These events are shown in order of occurrence, except for, Error event, which occurs only if there is an unhandled exception.
PreInit - As the name suggests, this event happens just before page initialization event starts. IsPostBack, IsCallback and IsCrossPagePostBack properties are set at this stage. This event allows us to set the master page and theme of a web application dynamically. PreInit is extensively used when working with dynamic controls.
Init - Page Init, event occurs after the Init event, of all the individual controls on the webform. Use this event to read or initialize control properties. The server controls are loaded and initialized from the Web form’s view state.
InitComplete - As the name says, this event gets raised immediately after page initialization.
PreLoad - Happens just before the Page Load event.
Load - Page Load event, occurs before the load event of all the individual controls on that webform.
Control Events - After the Page load event, the control events like button's click, dropdownlist's selected index changed events are raised.
Load Complete - This event is raised after the control events are handled.
PreRender - This event is raised just before the rendering stage of the page.
PreRenderComplete - Raised immediately after the PreRender event.
Unload - Raised for each control and then for the page. At this stage the page is, unloaded from memory.
Error - This event occurs only if there is an unhandled exception.
To see the events execution order, create a new asp.net web project, and copy the following code.
protected void Page_PreInit(object sender, EventArgs e)
{ Response.Write("Page_PreInit" + "<br/>"); }
protected void Page_Init(object sender, EventArgs e)
{ Response.Write("Page_Init" + "<br/>"); }
protected void Page_InitComplete(object sender, EventArgs e)
{ Response.Write("Page_InitComplete" + "<br/>"); }
protected void Page_PreLoad(object sender, EventArgs e)
{ Response.Write("Page_PreLoad" + "<br/>"); }
protected void Page_LoadComplete(object sender, EventArgs e)
{ Response.Write("Page_LoadComplete" + "<br/>"); }
protected void Page_PreRender(object sender, EventArgs e)
{ Response.Write("Page_PreRender" + "<br/>"); }
protected void Page_PreRenderComplete(object sender, EventArgs e)
{ Response.Write("Page_PreRenderComplete" + "<br/>"); }
protected void Page_Unload(object sender, EventArgs e)
{
//Response.Write("Page_Unload" + "<br/>");
}
Run the project and you should see the following output.
Page_PreInit
Page_Init
Page_InitComplete
Page_PreLoad
Page_LoadComplete
Page_PreRender
Page_PreRenderComplete
Note: If you uncomment, Response.Write() method call in Page_Unload() event, you get System.Web.HttpException stating - Response is not available in this context. This makes sense because, the Unload event is raised after the page has been fully rendered, and the HTML is already sent to the client. At this stage, the webform instance is ready to be discarded. So, at this point, page properties such as Response and Request are unloaded and clean up is performed.
Part 3 - Understanding ViewState
Part 4 - Events in the life cycle of a web application
Part 5 - Difference between ViewState, SessionState and ApplicationState
In Part 4, of this video series, we have discussed that, events can occur at 3 levels in an asp.net web application.
1. At the application level. (Example - Session_Start event in global.asax)
2. At the Page or web form level (Example - Page_Load)
3. At the control level(Example - Selected Index changed event of a dropdownlist)
In this video, we will discuss about events at the page level. From the previous,parts of this video series, we have learnt that, web applications work on a stateless protocol. Every time a request is made for a webform, the following sequence of events occur.
1. Web Application creates an instance of the requested webform.
2. Processes the events of the webform.
3. Generates the HTML, and sends the HTML back to the requested client.
4. The webform gets destroyed and removed from the memory.
The following are some of the commonly used events in the life cycle of an asp.net webform. These events are shown in order of occurrence, except for, Error event, which occurs only if there is an unhandled exception.
PreInit - As the name suggests, this event happens just before page initialization event starts. IsPostBack, IsCallback and IsCrossPagePostBack properties are set at this stage. This event allows us to set the master page and theme of a web application dynamically. PreInit is extensively used when working with dynamic controls.
Init - Page Init, event occurs after the Init event, of all the individual controls on the webform. Use this event to read or initialize control properties. The server controls are loaded and initialized from the Web form’s view state.
InitComplete - As the name says, this event gets raised immediately after page initialization.
PreLoad - Happens just before the Page Load event.
Load - Page Load event, occurs before the load event of all the individual controls on that webform.
Control Events - After the Page load event, the control events like button's click, dropdownlist's selected index changed events are raised.
Load Complete - This event is raised after the control events are handled.
PreRender - This event is raised just before the rendering stage of the page.
PreRenderComplete - Raised immediately after the PreRender event.
Unload - Raised for each control and then for the page. At this stage the page is, unloaded from memory.
Error - This event occurs only if there is an unhandled exception.
To see the events execution order, create a new asp.net web project, and copy the following code.
protected void Page_PreInit(object sender, EventArgs e)
{ Response.Write("Page_PreInit" + "<br/>"); }
protected void Page_Init(object sender, EventArgs e)
{ Response.Write("Page_Init" + "<br/>"); }
protected void Page_InitComplete(object sender, EventArgs e)
{ Response.Write("Page_InitComplete" + "<br/>"); }
protected void Page_PreLoad(object sender, EventArgs e)
{ Response.Write("Page_PreLoad" + "<br/>"); }
protected void Page_LoadComplete(object sender, EventArgs e)
{ Response.Write("Page_LoadComplete" + "<br/>"); }
protected void Page_PreRender(object sender, EventArgs e)
{ Response.Write("Page_PreRender" + "<br/>"); }
protected void Page_PreRenderComplete(object sender, EventArgs e)
{ Response.Write("Page_PreRenderComplete" + "<br/>"); }
protected void Page_Unload(object sender, EventArgs e)
{
//Response.Write("Page_Unload" + "<br/>");
}
Run the project and you should see the following output.
Page_PreInit
Page_Init
Page_InitComplete
Page_PreLoad
Page_LoadComplete
Page_PreRender
Page_PreRenderComplete
Note: If you uncomment, Response.Write() method call in Page_Unload() event, you get System.Web.HttpException stating - Response is not available in this context. This makes sense because, the Unload event is raised after the page has been fully rendered, and the HTML is already sent to the client. At this stage, the webform instance is ready to be discarded. So, at this point, page properties such as Response and Request are unloaded and clean up is performed.
ASP.NET Server control
events - Part 7
Suggested Videos
Part 4 - Events in the life cycle of a web application
Part 5 - Difference between ViewState, SessionState and ApplicationState
Part 6 - ASP.NET Page Life Cycle Events
In the previous parts of this video series, we have discussed that events can occur at application, page and control levels. In Part 4, we discussed application level events, and in Part 6, we discussed about Page Level events.
In this session, we will discuss about control level events. ASP.NET server controls, such as TextBox, Button, and DropDownList has their own events. For example, Button has a click event. TextBox has TextChanged event, and DropDownList has SelectedIndexChanged event. We have a set of asp.net validation controls, that has validation events. The events that all these controls expose, can be broadly divided into 3 categories.
Postback events - These events submit the Web page, immediately to the server for processing. Click event of a button control is an example for PostBack event.
Cached events - These events are saved in the page’s view state to be processed when a postback event occurs. TextChanged event of TextBox control, and SelectedIndexChanged event of a DropDownList control are examples of cached events. Cached events can be converted into postback events, by setting the AutoPostBack property of the control to true.
Validation events - These events occur on the client, before the page is posted back to the server. All validation controls use these type of events.
In Part 6, of this video series, we have understood that control events are processed after the PageLoad event. The picture below depicts the same. Among the control events, Cached events happen before PostBack events.

To understand the order in which Page and Server control events execute, add a Web form with a TextBox, RequiredFieldValidator, and a Button control. You can find RequiredFieldValidator under Validation tab, in the ToolBox. Double click the TextBox control on the WebForm, and the event handler TextBox1_TextChanged() will be automatically generated. Along the same lines, double click the Button control, Button1_Click() event handler will be generated. Right Click the RequiredFieldValidator control on the webform and select Properties. From the Properties window, Set ControlToValidate property to TextBox1. At this stage copy and paste the following code in WebForm1.aspx.cs.
protected void Page_PreInit(object sender, EventArgs e)
{
Response.Write("Page_PreInit" + "<br/>");
}
protected void Page_Init(object sender, EventArgs e)
{
Response.Write("Page_Init" + "<br/>");
}
protected void Page_InitComplete(object sender, EventArgs e)
{
Response.Write("Page_InitComplete" + "<br/>");
}
protected void Page_PreLoad(object sender, EventArgs e)
{
Response.Write("Page_PreLoad" + "<br/>");
}
protected void Page_LoadComplete(object sender, EventArgs e)
{
Response.Write("Page_LoadComplete" + "<br/>");
}
protected void Page_PreRender(object sender, EventArgs e)
{
Response.Write("Page_PreRender" + "<br/>");
}
protected void Page_PreRenderComplete(object sender, EventArgs e)
{
Response.Write("Page_PreRenderComplete" + "<br/>");
}
protected void TextBox1_TextChanged(object sender, EventArgs e)
{
Response.Write("Text Changed Event"+ "<br/>");
}
protected void Button1_Click(object sender, EventArgs e)
{
Response.Write("Button Click"+ "<br/>");
}
Now, run the project, and when the webform renders, the page level events occur in the following order. Notice that, TextChanged and ButtonClick events are not fired.
Page_PreInit
Page_Init
Page_InitComplete
Page_PreLoad
Page_LoadComplete
Page_PreRender
Page_PreRenderComplete
Don't type anything in the TextBox, and click the button control. The RequiredFieldValidator message is displayed. No other events get processed and the page is not posted back to the server.
Now, enter some text, into the TextBox and Click the button. Notice that, Text Changed Event and Button Click, execute after Page Load and Before Page Load Complete events. Among the control events, TextChanged event is fired before the click event. The execution order is shown below.
Page_PreInit
Page_Init
Page_InitComplete
Page_PreLoad
Text Changed Event
Button Click
Page_LoadComplete
Page_PreRender
Page_PreRenderComplete
Part 4 - Events in the life cycle of a web application
Part 5 - Difference between ViewState, SessionState and ApplicationState
Part 6 - ASP.NET Page Life Cycle Events
In the previous parts of this video series, we have discussed that events can occur at application, page and control levels. In Part 4, we discussed application level events, and in Part 6, we discussed about Page Level events.
In this session, we will discuss about control level events. ASP.NET server controls, such as TextBox, Button, and DropDownList has their own events. For example, Button has a click event. TextBox has TextChanged event, and DropDownList has SelectedIndexChanged event. We have a set of asp.net validation controls, that has validation events. The events that all these controls expose, can be broadly divided into 3 categories.
Postback events - These events submit the Web page, immediately to the server for processing. Click event of a button control is an example for PostBack event.
Cached events - These events are saved in the page’s view state to be processed when a postback event occurs. TextChanged event of TextBox control, and SelectedIndexChanged event of a DropDownList control are examples of cached events. Cached events can be converted into postback events, by setting the AutoPostBack property of the control to true.
Validation events - These events occur on the client, before the page is posted back to the server. All validation controls use these type of events.
In Part 6, of this video series, we have understood that control events are processed after the PageLoad event. The picture below depicts the same. Among the control events, Cached events happen before PostBack events.

To understand the order in which Page and Server control events execute, add a Web form with a TextBox, RequiredFieldValidator, and a Button control. You can find RequiredFieldValidator under Validation tab, in the ToolBox. Double click the TextBox control on the WebForm, and the event handler TextBox1_TextChanged() will be automatically generated. Along the same lines, double click the Button control, Button1_Click() event handler will be generated. Right Click the RequiredFieldValidator control on the webform and select Properties. From the Properties window, Set ControlToValidate property to TextBox1. At this stage copy and paste the following code in WebForm1.aspx.cs.
protected void Page_PreInit(object sender, EventArgs e)
{
Response.Write("Page_PreInit" + "<br/>");
}
protected void Page_Init(object sender, EventArgs e)
{
Response.Write("Page_Init" + "<br/>");
}
protected void Page_InitComplete(object sender, EventArgs e)
{
Response.Write("Page_InitComplete" + "<br/>");
}
protected void Page_PreLoad(object sender, EventArgs e)
{
Response.Write("Page_PreLoad" + "<br/>");
}
protected void Page_LoadComplete(object sender, EventArgs e)
{
Response.Write("Page_LoadComplete" + "<br/>");
}
protected void Page_PreRender(object sender, EventArgs e)
{
Response.Write("Page_PreRender" + "<br/>");
}
protected void Page_PreRenderComplete(object sender, EventArgs e)
{
Response.Write("Page_PreRenderComplete" + "<br/>");
}
protected void TextBox1_TextChanged(object sender, EventArgs e)
{
Response.Write("Text Changed Event"+ "<br/>");
}
protected void Button1_Click(object sender, EventArgs e)
{
Response.Write("Button Click"+ "<br/>");
}
Now, run the project, and when the webform renders, the page level events occur in the following order. Notice that, TextChanged and ButtonClick events are not fired.
Page_PreInit
Page_Init
Page_InitComplete
Page_PreLoad
Page_LoadComplete
Page_PreRender
Page_PreRenderComplete
Don't type anything in the TextBox, and click the button control. The RequiredFieldValidator message is displayed. No other events get processed and the page is not posted back to the server.
Now, enter some text, into the TextBox and Click the button. Notice that, Text Changed Event and Button Click, execute after Page Load and Before Page Load Complete events. Among the control events, TextChanged event is fired before the click event. The execution order is shown below.
Page_PreInit
Page_Init
Page_InitComplete
Page_PreLoad
Text Changed Event
Button Click
Page_LoadComplete
Page_PreRender
Page_PreRenderComplete
Suggested Videos
Part 3 - ViewState in ASP.NET
Part 6 - ASP.NET Page Life Cycle Events
Part 7 - ASP.NET Server Control Events
IsPostBack is a Page level property, that can be used to determine whether the page is being loaded in response to a client postback, or if it is being loaded and accessed for the first time.
In real time there are many situations where IsPostBack property is used. For example, consider the webform used to register employee details. A sample form that we will use for this example is shown below. The form has First Name, Last Name and City fields.

If you want to follow along with me, copy and paste the following HTML in a web form.
<table style="font-family: Arial">
<tr>
<td colspan = "2"><b>Employee Details Form</b></td>
</tr>
<tr>
<td>First Name: </td>
<td> <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox> </td>
</tr>
<tr>
<td>Last Name: </td>
<td> <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox> </td>
</tr>
<tr>
<td>City:</td>
<td>
<asp:DropDownList ID="ddlCity" runat="server">
</asp:DropDownList>
</td>
</tr>
<tr>
<td></td>
<td>
<asp:Button ID="Button1" runat="server" onclick="Button1_Click"
Text="Register Employee" />
</td>
</tr>
</table>
Copy and Paste the following code in the code behind file of the web form.
protected void Page_Load(object sender, EventArgs e)
{
LoadCityDropDownList();
}
public void LoadCityDropDownList()
{
ListItem li1 = new ListItem("London");
ddlCity.Items.Add(li1);
ListItem li2 = new ListItem("Sydney");
ddlCity.Items.Add(li2);
ListItem li3 = new ListItem("Mumbai");
ddlCity.Items.Add(li3);
}
protected void Button1_Click(object sender, EventArgs e)
{
}
Now run the application. Look at the City DropDownList. The cities, (London, Sydney and Mumbai) are correctly shown as expected. Just click the button once. Notice, that the city names in the DropDownList are duplicated. So, every time you click the button, the city names are again added to the DropDownList.
Let's now understand the cause for this duplication.
We know that all ASP.NET server controls retain their state across postback. These controls make use of ViewState. So, the first time, when the webform load. the cities get correctly added to the DropDownList and sent back to the client.
Now, when the client clicks the button control, and the webform is posted back to the server for processing. During the Page initialization, ViewState restoration happens. During this stage, the city names are retrieved from the viewstate and added to the DropDownList. PageLoad event happens later in the life cycle of the webform. During page load we are again adding another set of cities. Hence, the duplication.
How to solve the DropDownList items duplication
There are several ways to solve this. One of the best ways to do this, is to use IsPostBack property. So, in the Page_Load, call LoadCityDropDownList() method, if the request, is not a postback request. That is, only if the webform is being loaded and accessed for the first time.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
LoadCityDropDownList();
}
}
Another way to solve, this problem is to simply disable the ViewState of the DropDownlist control. To disable the viewstate, right click the DropDownList control, and set EnableViewState property to false. Now run the project, and the cities duplication issue is gone.
But the problem, with this approach is that, the DropDownList list, does not remember your selecttion across postback. That is, Select "Mumabi" as the city, and submit the form. When the page rerenders, observer that selection is set back to "London". Another problem with, disabling the viewstate is that, the DropDownList events may not work correctly as expected.
Another way to solve this, is to clear all the DropDownList items, before calling LoadCityDropDownList() method. But this not efficient from a performance perspective. The modified code is shown below.
protected void Page_Load(object sender, EventArgs e)
{
ddlCity.Items.Clear();
LoadCityDropDownList();
}
Part 3 - ViewState in ASP.NET
Part 6 - ASP.NET Page Life Cycle Events
Part 7 - ASP.NET Server Control Events
IsPostBack is a Page level property, that can be used to determine whether the page is being loaded in response to a client postback, or if it is being loaded and accessed for the first time.
In real time there are many situations where IsPostBack property is used. For example, consider the webform used to register employee details. A sample form that we will use for this example is shown below. The form has First Name, Last Name and City fields.
If you want to follow along with me, copy and paste the following HTML in a web form.
<table style="font-family: Arial">
<tr>
<td colspan = "2"><b>Employee Details Form</b></td>
</tr>
<tr>
<td>First Name: </td>
<td> <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox> </td>
</tr>
<tr>
<td>Last Name: </td>
<td> <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox> </td>
</tr>
<tr>
<td>City:</td>
<td>
<asp:DropDownList ID="ddlCity" runat="server">
</asp:DropDownList>
</td>
</tr>
<tr>
<td></td>
<td>
<asp:Button ID="Button1" runat="server" onclick="Button1_Click"
Text="Register Employee" />
</td>
</tr>
</table>
Copy and Paste the following code in the code behind file of the web form.
protected void Page_Load(object sender, EventArgs e)
{
LoadCityDropDownList();
}
public void LoadCityDropDownList()
{
ListItem li1 = new ListItem("London");
ddlCity.Items.Add(li1);
ListItem li2 = new ListItem("Sydney");
ddlCity.Items.Add(li2);
ListItem li3 = new ListItem("Mumbai");
ddlCity.Items.Add(li3);
}
protected void Button1_Click(object sender, EventArgs e)
{
}
Now run the application. Look at the City DropDownList. The cities, (London, Sydney and Mumbai) are correctly shown as expected. Just click the button once. Notice, that the city names in the DropDownList are duplicated. So, every time you click the button, the city names are again added to the DropDownList.
Let's now understand the cause for this duplication.
We know that all ASP.NET server controls retain their state across postback. These controls make use of ViewState. So, the first time, when the webform load. the cities get correctly added to the DropDownList and sent back to the client.
Now, when the client clicks the button control, and the webform is posted back to the server for processing. During the Page initialization, ViewState restoration happens. During this stage, the city names are retrieved from the viewstate and added to the DropDownList. PageLoad event happens later in the life cycle of the webform. During page load we are again adding another set of cities. Hence, the duplication.
How to solve the DropDownList items duplication
There are several ways to solve this. One of the best ways to do this, is to use IsPostBack property. So, in the Page_Load, call LoadCityDropDownList() method, if the request, is not a postback request. That is, only if the webform is being loaded and accessed for the first time.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
LoadCityDropDownList();
}
}
Another way to solve, this problem is to simply disable the ViewState of the DropDownlist control. To disable the viewstate, right click the DropDownList control, and set EnableViewState property to false. Now run the project, and the cities duplication issue is gone.
But the problem, with this approach is that, the DropDownList list, does not remember your selecttion across postback. That is, Select "Mumabi" as the city, and submit the form. When the page rerenders, observer that selection is set back to "London". Another problem with, disabling the viewstate is that, the DropDownList events may not work correctly as expected.
Another way to solve this, is to clear all the DropDownList items, before calling LoadCityDropDownList() method. But this not efficient from a performance perspective. The modified code is shown below.
protected void Page_Load(object sender, EventArgs e)
{
ddlCity.Items.Clear();
LoadCityDropDownList();
}
In this videos we will learn about
1. What is a Web Server
2. Do you need IIS to develop and test asp.net web applications
3. How to check if IIS is installed?
4. Installing IIS
5. Configuring IIS server to run asp.net web applications
What is a web server?
In simple terms, a web server, is a software, that is used to deliver web pages to clients using the Hypertext Transfer Protocol (HTTP). For example, IIS is a web server that can be used to run asp.net web applications.
Do you need IIS to develop and test asp.net web applications?
No, Visual Studio ships with a built-in web server. If you want to just build and test web applications on your machine, you don't need an IIS. Keep in mind, Built-in web server will not serve requests to another computer. By default, visual studio uses the built-in web server.
Create a new asp.net web application and run it by pressing CTRL + F5. Notice the URL of the page in the browser. A random port number is used. On my machine it was using port number 16041.
http://localhost:16041/WebForm1.aspx
To confirm, if this is the built-in visual studio development server, check the notifications area on the task bar, and you should see ASP.NET Development Server running. Please refer to the image below.

Another way to check, if visual studio is using, built-in development server.
1. Right cick on the web application project in solution explorer and select Properties.
2. On the Project properties window, click on the Web tab.
3. Scroll down to servers section - Notice that "Use visual studio development server" is selected.
4. By default, visual studio auto assigns an available port. If you want to assign a specific port, you can do so, by selecting Specific Port radio button.

How to check if IIS is installed?
1. Click on the windows Start button
2. Type INETMGR in the Run window.
3. Click OK.
4. If you get IIS manager window, it is installed, otherwise not installed.
How to install IIS?
1. Click on the start button and select ControlPanel
2. Click on Programs
3. Click on, Turn windows features on or Off, under Programs and features option
4. In the windows features
5. Select Internet Information Services and related services, and click OK
To configure a virtual directory in IIS to run asp.net web applications
1. In the IIS Manager window, double click on the iis server name in the connections section.
2. Expand sites
3. Right click on Default Web Site, and Select Add Application.
4. Give an alias name. This is the name you will use in the URL, when connecting to your web application.
5. Click the button next to the textbox under physical path. Select the physical web application folder.
You can also create the virtual directory from visual studio, on the project properties window.
1. Select Use Local IIS Web Server
2. Project URL will be populated automatically. You can change the name of the virtual directory if you wish to do so.
3. Click Create Virtual Directory button.
4. After a few seconds the virtual directory was successfully created message will appear.
5. Click OK
1. What is a Web Server
2. Do you need IIS to develop and test asp.net web applications
3. How to check if IIS is installed?
4. Installing IIS
5. Configuring IIS server to run asp.net web applications
What is a web server?
In simple terms, a web server, is a software, that is used to deliver web pages to clients using the Hypertext Transfer Protocol (HTTP). For example, IIS is a web server that can be used to run asp.net web applications.
Do you need IIS to develop and test asp.net web applications?
No, Visual Studio ships with a built-in web server. If you want to just build and test web applications on your machine, you don't need an IIS. Keep in mind, Built-in web server will not serve requests to another computer. By default, visual studio uses the built-in web server.
Create a new asp.net web application and run it by pressing CTRL + F5. Notice the URL of the page in the browser. A random port number is used. On my machine it was using port number 16041.
http://localhost:16041/WebForm1.aspx
To confirm, if this is the built-in visual studio development server, check the notifications area on the task bar, and you should see ASP.NET Development Server running. Please refer to the image below.

Another way to check, if visual studio is using, built-in development server.
1. Right cick on the web application project in solution explorer and select Properties.
2. On the Project properties window, click on the Web tab.
3. Scroll down to servers section - Notice that "Use visual studio development server" is selected.
4. By default, visual studio auto assigns an available port. If you want to assign a specific port, you can do so, by selecting Specific Port radio button.

How to check if IIS is installed?
1. Click on the windows Start button
2. Type INETMGR in the Run window.
3. Click OK.
4. If you get IIS manager window, it is installed, otherwise not installed.
How to install IIS?
1. Click on the start button and select ControlPanel
2. Click on Programs
3. Click on, Turn windows features on or Off, under Programs and features option
4. In the windows features
5. Select Internet Information Services and related services, and click OK
To configure a virtual directory in IIS to run asp.net web applications
1. In the IIS Manager window, double click on the iis server name in the connections section.
2. Expand sites
3. Right click on Default Web Site, and Select Add Application.
4. Give an alias name. This is the name you will use in the URL, when connecting to your web application.
5. Click the button next to the textbox under physical path. Select the physical web application folder.
You can also create the virtual directory from visual studio, on the project properties window.
1. Select Use Local IIS Web Server
2. Project URL will be populated automatically. You can change the name of the virtual directory if you wish to do so.
3. Click Create Virtual Directory button.
4. After a few seconds the virtual directory was successfully created message will appear.
5. Click OK
ASP.NET TextBox
Control - Part 10
The TextBox control is used to get the input from the user of
the web application. An asp.net textbox
has several properties, that we need to be aware of as a developer.
Properties of a TextBox control
1. TextMode Propertry - SingleLine, MultiLine and Password.
When you set the TextMode to MultiLine, use Rows property to control the number of lines to display for a MultiLine TextBox.
2. Text - Use this property to set or get the Text from the TextBox.
3. MaxLength - The maximum number of chatacters that a user can enter.
4. ReadOnly - Set this property to true if you don't want the user to change the text in the TextBox.
5. ToolTip - The tooltip is displayed when the mouse is over the control.
6. Columns - Use this property to specify the width of the TextBox in characters
7. Height - Set the height
8. Width - Set the width
9. AutoPostBack - By default, the TextChanged event of a TextBox control is cached in the viewstate, and is executed when the webform is submitted thru a postback by clicking the button control. If you want to change this behaviour, and post the webform immediately when the Text is changed, set AutoPostBack to true. Setting this property to true, will convert the cached event into a postback event.
Events of TextBox:
TextChanged - This event is fired, when the text is changed.
Methods of a TextBox:
Focus - Set input focus onto the control.
To view the properties of the TextBox, Right click on the control, and select Properties. In the properties window, you can also find the events supported by the control.
All these properties can be set at the design time, or at runtime using code.
Properties of a TextBox control
1. TextMode Propertry - SingleLine, MultiLine and Password.
When you set the TextMode to MultiLine, use Rows property to control the number of lines to display for a MultiLine TextBox.
2. Text - Use this property to set or get the Text from the TextBox.
3. MaxLength - The maximum number of chatacters that a user can enter.
4. ReadOnly - Set this property to true if you don't want the user to change the text in the TextBox.
5. ToolTip - The tooltip is displayed when the mouse is over the control.
6. Columns - Use this property to specify the width of the TextBox in characters
7. Height - Set the height
8. Width - Set the width
9. AutoPostBack - By default, the TextChanged event of a TextBox control is cached in the viewstate, and is executed when the webform is submitted thru a postback by clicking the button control. If you want to change this behaviour, and post the webform immediately when the Text is changed, set AutoPostBack to true. Setting this property to true, will convert the cached event into a postback event.
Events of TextBox:
TextChanged - This event is fired, when the text is changed.
Methods of a TextBox:
Focus - Set input focus onto the control.
To view the properties of the TextBox, Right click on the control, and select Properties. In the properties window, you can also find the events supported by the control.
All these properties can be set at the design time, or at runtime using code.
Radio Button control is used, when you want the user to select only one option from the available choices. For example, the gender of a person. A person can be Male or Female. He cannot be both. So, if the user has first selected Male, and if tries to select Female, the initial Male selection he made should automatically get de-selected. Another example, would be when you want the user to select his or her favourite colour.
In short, if you want to provide the user with mutually exclusive options, then choose a Radio Button Control.
Important Properties of the Radio Button Control
Checked - This is a boolean property, that is used to check if the button is checked or not.
Text - This is string property used to get or set the text associated with the radio button control
TextAlign - right or left. On which side of the radio button the text should appear
AutoPostBack - Set this property to true, if you want the webform to be posted immediately when the checked status of the radio button changes.
Group Name - By default, the individual radio button selections, are not mutually exclusive. If you have a group of radio buttons, and if you want the selections among the group to be mutually exclusive, then use the same group name for all the radio button controls.
Events:
CheckedChanged - This event is fired when the checked status of the radio button control is changed.
Suggested Videos:
Part 10 - TextBox Control
Part 11 - RadioButton Control
In this video we will learn about the properties, methods and events of an asp.net CheckBox control
CheckBox Control is used, when you want the user to select more than one option from the available choices. For example, the education of a person. A person can have a graduate degree, post graduate degree and a doctrate. In this case the user selects all the 3 checkboxes. Where as a person, may just have a graduate degree, in which case he only selects, the graduate checkbox.

Another example, would be when you want the user to select the days of his availability.

In short, if you want to provide the user with more than one option to select from, then choose a check box Control.
Important Properties of the CheckBox Control
Checked - This is a boolean property, that is used to check if the check box is checked or not.
Text - This is a string property used to get or set the text associated with the check box control
TextAlign - right or left. On which side of the check box the text should appear
AutoPostBack - Set this property to true, if you want the webform to be posted immediately when the checked status of the check box changes.
Methods:
Focus() - Just like TextBox, checkbox also supports, Focus() method. If you want to set the input focus, to a specific checkbox, Call this method for that check box control.
Events:
CheckedChanged - This event is fired when the checked status of the check button control is changed.
HTML of the ASPX page, we used in the example
<div style="font-family:Arial">
<fieldset style="width:350px">
<legend><b>Education</b></legend>
<asp:CheckBox ID="GraduateCheckBox" Checked="true" Text="Graduate" runat="server"
oncheckedchanged="GraduateCheckBox_CheckedChanged" />
<asp:CheckBox ID="PostGraduateCheckBox" Text="Post Graduate" runat="server" />
<asp:CheckBox ID="DoctrateCheckBox" Text="Doctrate" runat="server" />
</fieldset>
<br /><br />
<asp:Button ID="Button1" runat="server" Text="Submit" onclick="Button1_Click" />
</div>
Code from the CodeBehind file
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
PostGraduateCheckBox.Focus();
}
}
protected void Button1_Click(object sender, EventArgs e)
{
StringBuilder sbUserChoices = new StringBuilder();
if (GraduateCheckBox.Checked)
{
sbUserChoices.Append(GraduateCheckBox.Text);
}
if (PostGraduateCheckBox.Checked)
{
sbUserChoices.Append(", " + PostGraduateCheckBox.Text);
}
if (DoctrateCheckBox.Checked)
{
sbUserChoices.Append(", " + DoctrateCheckBox.Text);
}
Response.Write("Your Selections: " + sbUserChoices.ToString());
}
protected void GraduateCheckBox_CheckedChanged(object sender, EventArgs e)
{
Response.Write("Graduate Checkbox Selection changed");
}
Part 10 - TextBox Control
Part 11 - RadioButton Control
In this video we will learn about the properties, methods and events of an asp.net CheckBox control
CheckBox Control is used, when you want the user to select more than one option from the available choices. For example, the education of a person. A person can have a graduate degree, post graduate degree and a doctrate. In this case the user selects all the 3 checkboxes. Where as a person, may just have a graduate degree, in which case he only selects, the graduate checkbox.

Another example, would be when you want the user to select the days of his availability.

In short, if you want to provide the user with more than one option to select from, then choose a check box Control.
Important Properties of the CheckBox Control
Checked - This is a boolean property, that is used to check if the check box is checked or not.
Text - This is a string property used to get or set the text associated with the check box control
TextAlign - right or left. On which side of the check box the text should appear
AutoPostBack - Set this property to true, if you want the webform to be posted immediately when the checked status of the check box changes.
Methods:
Focus() - Just like TextBox, checkbox also supports, Focus() method. If you want to set the input focus, to a specific checkbox, Call this method for that check box control.
Events:
CheckedChanged - This event is fired when the checked status of the check button control is changed.
HTML of the ASPX page, we used in the example
<div style="font-family:Arial">
<fieldset style="width:350px">
<legend><b>Education</b></legend>
<asp:CheckBox ID="GraduateCheckBox" Checked="true" Text="Graduate" runat="server"
oncheckedchanged="GraduateCheckBox_CheckedChanged" />
<asp:CheckBox ID="PostGraduateCheckBox" Text="Post Graduate" runat="server" />
<asp:CheckBox ID="DoctrateCheckBox" Text="Doctrate" runat="server" />
</fieldset>
<br /><br />
<asp:Button ID="Button1" runat="server" Text="Submit" onclick="Button1_Click" />
</div>
Code from the CodeBehind file
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
PostGraduateCheckBox.Focus();
}
}
protected void Button1_Click(object sender, EventArgs e)
{
StringBuilder sbUserChoices = new StringBuilder();
if (GraduateCheckBox.Checked)
{
sbUserChoices.Append(GraduateCheckBox.Text);
}
if (PostGraduateCheckBox.Checked)
{
sbUserChoices.Append(", " + PostGraduateCheckBox.Text);
}
if (DoctrateCheckBox.Checked)
{
sbUserChoices.Append(", " + DoctrateCheckBox.Text);
}
Response.Write("Your Selections: " + sbUserChoices.ToString());
}
protected void GraduateCheckBox_CheckedChanged(object sender, EventArgs e)
{
Response.Write("Graduate Checkbox Selection changed");
}
ASP.NET Hyperlink
control - Part 13
The ASP.NET Hyperlink control is used to create a link to another Web page.
Properties:
Text - The link text that will be shown to the user
Navigate URL - The URL of the page to which the user will be sent
ImageURL - The URL of the image, that will be displayed for the link. If you specify both the Text and ImageUrl, the image will be displayed instead of the text. If for some reason, the image is not unavailable, the text will be displayed.
Target - If target is not specified, the web page to which the hyperlink is linked, will be displayed in the same window. If you set the Target to _blank, the web page will be opened in a new window.
Methods:
Focus() - Call this method to Set the input focus when the page loads.
Events:
No HyperLink control specific events
ASP.NET Button,
LinkButton and ImageButton Controls - Part 14
Suggested Videos:
Part 11. RadioButton Control
Part 12. CheckBox Control
Part 13. HyperLink Control
The Button, LinkButton and ImageButton controls in ASP.NET are used to post a page to the server.
1. Button - The Button control is used to display a push button. Use the Text property to change the Text on the Button control.
2. LinkButton - LinkButton displays the button like a HyperLink. Use the Text property to change the LinkText.
3. ImageButton - ImageButton provides the flexibility of associating an Image with the button, using the ImageURL property.
All the 3 button controls support CommandName and CommandArgument properties. We will talk about these properties in the next video session. These 3 button controls also support CuasesValidation and ValidationGroup properties. We will discuss about these properties, when we talk about validation controls in asp.net. We will discuss about PostBackURL property, when we talk about cross page post back.
All the 3 button controls, exposes client side click event and server side click event. You can associate the javascript, that you want to run in response to the click event on the client side using OnClientClick property as shown below.
<asp:Button ID="Button1" runat="server"
OnClientClick="alert('You are about to submit this page')"
Text="Button" />
When you click this button, you will get a popup as shown below. Once you click OK, the webform will be submitted to the server for processing server side click event.
In the above example we are using javascript, alert() function. The client side alert message box, can be used to communicate important information to the user. For example messages like
1. You are about to place an order
2. You are about to leave this website
Sometimes, we may accidentally click on a delete button, which deletes the record permanently. So, whenever, we do things like this, we want to be double sure, if the user really wants to delete the record. The javascript confirm(), function can be used for this purpose.
<asp:Button ID="Button1" runat="server"
OnClientClick="return confirm('Are you sure you want to delete this record?')"
Text="Button" />
When you click the button now, the user will be shown a confirmation box, as shown below.

If you click cancel, the confirm() function returns false and the webform will not be submitted. If you click OK, the confirm() function returns true, and the webform will be posted to the server.
So, far we have associated the javascript, to the client click event of a button control at design time. It is also, possible, to do the same at runtime using the Button controls attribute collection as shown below.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Button1.Attributes.Add("onclick", "return confirm('Do you want to delete the record?');");
}
}
Part 11. RadioButton Control
Part 12. CheckBox Control
Part 13. HyperLink Control
The Button, LinkButton and ImageButton controls in ASP.NET are used to post a page to the server.
1. Button - The Button control is used to display a push button. Use the Text property to change the Text on the Button control.
2. LinkButton - LinkButton displays the button like a HyperLink. Use the Text property to change the LinkText.
3. ImageButton - ImageButton provides the flexibility of associating an Image with the button, using the ImageURL property.
All the 3 button controls support CommandName and CommandArgument properties. We will talk about these properties in the next video session. These 3 button controls also support CuasesValidation and ValidationGroup properties. We will discuss about these properties, when we talk about validation controls in asp.net. We will discuss about PostBackURL property, when we talk about cross page post back.
All the 3 button controls, exposes client side click event and server side click event. You can associate the javascript, that you want to run in response to the click event on the client side using OnClientClick property as shown below.
<asp:Button ID="Button1" runat="server"
OnClientClick="alert('You are about to submit this page')"
Text="Button" />
When you click this button, you will get a popup as shown below. Once you click OK, the webform will be submitted to the server for processing server side click event.

In the above example we are using javascript, alert() function. The client side alert message box, can be used to communicate important information to the user. For example messages like
1. You are about to place an order
2. You are about to leave this website
Sometimes, we may accidentally click on a delete button, which deletes the record permanently. So, whenever, we do things like this, we want to be double sure, if the user really wants to delete the record. The javascript confirm(), function can be used for this purpose.
<asp:Button ID="Button1" runat="server"
OnClientClick="return confirm('Are you sure you want to delete this record?')"
Text="Button" />
When you click the button now, the user will be shown a confirmation box, as shown below.

If you click cancel, the confirm() function returns false and the webform will not be submitted. If you click OK, the confirm() function returns true, and the webform will be posted to the server.
So, far we have associated the javascript, to the client click event of a button control at design time. It is also, possible, to do the same at runtime using the Button controls attribute collection as shown below.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Button1.Attributes.Add("onclick", "return confirm('Do you want to delete the record?');");
}
}
Command Event of an
asp.net button control - Part 15
Suggested
Videos:
Part
12 - CheckBox Control
Part
13 - HyperLink Control
Part
14 - Button, LinkButton and ImageButton Controls
ASP.NET button control exposes 2 events - Click and Command events. In Part
14, we have discussed about the click event. In this session we
will discuss about the Command event. When the Button is clicked, both the
events are raised. Click event happens before the Command event.
To prove this drag and drop a button control onto the webform
1. Double click the Button control. This will automatically generate the click
event handler in the code behind file
2. To generate the command event handler, right click the button control and
select properties. Click the events icon, in the properties window. Double
click on the command event. The event handler for the command event should now
be generated.
If you are following along with me. At this stage the HTML for the button
control in the aspx page, should look as shown below.
<asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click"
CommandName="Button1" oncommand="Button1_Command"
/>
Please copy and paste the following code in the code behind file.
protected void Button1_Click(object sender, EventArgs
e)
{
Response.Write("Button1 Click event handled
<br/>");
}
protected void Button1_Command(object sender, CommandEventArgs
e)
{
Response.Write("Button1 Command event handled
<br/>");
}
When you click the Button now, you should see the following output. This proves
that when a button is clicked, first the Click event and then the Command event
is fired.
Button1 Click event handled
Button1 Command event handled
The click event handler and the command event handlers, are attached to the
respective Click and Command events in the HTML using onclick and oncommand
attributes. The event handlers can also be attached
programatically as shown below.
protected void Page_Load(object sender, EventArgs
e)
{
Button1.Click += new EventHandler(Button1_Click);
Button1.Command += new CommandEventHandler(Button1_Command);
}
Note: Eventhandlers can be associated to the events of a control in 2 ways.
1. Declaratively at design time in the HTML
2. Programatically using delegates
If you have multiple button controls on a webform, and if you want to
programmatically determine which Button control is clicked, we can make use of Command event,
along with CommandName and CommandArgument properties. Command event, makes it
possible to have a single event handler method responding to the click event of
multiple buttons. The command event, CommandName and CommandArgument properties
are extremely useful when working with data-bound controls like Repeater,
GridView, DataList. We will discuss about Repeater, GridView, and DataList in a
later video session.
Let's understand this with an example. Consider the HTML below. Here we have 4
buttons. Notice that all the button controls have the same command event
handler method - oncommand="CommandButton_Click". Also, notice the CommandName
and CommandArgument properties. We will later use these properties, in the code
behind to determine which button is clicked.
<asp:Button ID="PrintButton" runat="server"
Text="Print" oncommand="CommandButton_Click"
CommandName="Print"/>
<asp:Button ID="DeletButton" runat="server"
Text="Delete" oncommand="CommandButton_Click" CommandName="Delete"/>
<asp:Button ID="Top10Button" runat="server"
Text="Show Top 10 Employees"
oncommand="CommandButton_Click"
CommandName="Show"
CommandArgument="Top10"/>
<asp:Button ID="Bottom10Button" runat="server"
Text="Show Bottom 10 Employees" oncommand="CommandButton_Click"
CommandName="Show"
CommandArgument="Bottom10"/>
<asp:Label ID="OutputLabel"
runat="server"></asp:Label>
Copy and Paste the following code in your code behind file. The
CommandEventArgs object, has the CommandName and CommandArgument properties,
that are used to programatically determine which button the user has clicked.
protected void CommandButton_Click(object sender, CommandEventArgs
e)
{
switch (e.CommandName)
{
case "Print":
OutputLabel.Text = "You
clicked Print Button";
break;
case "Delete":
OutputLabel.Text = "You
clicked Delete Button";
break;
case "Show":
if (e.CommandArgument.ToString()
== "Top10")
{
OutputLabel.Text = "You
clicked Show Top 10 Employees Button";
}
else
{
OutputLabel.Text = "You
clicked Show Bottom 10 Employees Button";
}
break;
default:
OutputLabel.Text = "We
don't know which button you clicked";
break;
}
}
Note: All the 3 button controls - Button, LinkButton and ImageButton, expose
Command event, the CommandName and CommandArgument properties. Dropdownlist
in asp.net - Part 16
Suggested Videos
Part 13 - HyperLink Control
Part 14 - Button, LinkButton and ImageButton Controls
Part 15 - Command Event of an asp.net button control
In this video we will learn about
1. Adding items to the DropDownList control at design time using the HTML
2. Adding items to the DropDownList control at runtime using the code
Drag and drop a DropDownList control onto the webform.
To add items to the DropDownList at deign time
1. Right click on the DropDownList control and select properties.
2. In the properties, click on the ellipsis button next to Items property.
3. In the ListItem Collection Editor window, click the Add button
4. Set the Text to Male and Value to 1.
5. Click the Add button again, which will add another ListItem object
6. Set the Text to Female and Value to 2.
7. Finally click OK
Now switch the webform to source mode. Notice that in the HTML it has added ListItem object, as shown below.
<asp:DropDownList ID="DropDownList1" runat="server">
<asp:ListItem Value="1">Male</asp:ListItem>
<asp:ListItem Value="1">Female</asp:ListItem>
</asp:DropDownList>
If you run the web application now, you should see that Male and Female items shown in the DropDownList.
If you want a specific listitem to be selected in the dropdownlist, when the page loads, then set the Selected property of the ListItem object to true. This can be done in 2 ways.
1. Using the ListItem Collection Editor window or
2. In the HTML of the webform
The HTML with the Selected property is shown below.
<asp:DropDownList ID="DropDownList1" runat="server">
<asp:ListItem Value="1">Male</asp:ListItem>
<asp:ListItem Value="1" Selected="True">Female</asp:ListItem>
</asp:DropDownList>
To hide a ListItem in the DropDownList, set the Enabled property to False.
To add items to the DropDownList at run time using code
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
ListItem maleListItem = new ListItem("Male", "1");
ListItem femaleListItem = new ListItem("Female", "2");
DropDownList1.Items.Add(maleListItem);
DropDownList1.Items.Add(femaleListItem);
}
}
If you are adding listitem objects, to the DropDownList in the Page_Load event, make sure you do only when the page is loaded for the first time. Otherwise, every time, you post the page back, by clicking a button, the list items will be added again causing duplication.
A DropDownList is a collection of ListItem objects. Along the same lines, the following controls are also a collection of ListItem objects. So, adding items to these controls is also very similar to DropDownList.
1. CheckBoxList
2. RadioButtonList
3. BulletedList
4. ListBox
In the next video session, we will discuss about binding the dropdownlist to the data from a database and an XML file.
Part 13 - HyperLink Control
Part 14 - Button, LinkButton and ImageButton Controls
Part 15 - Command Event of an asp.net button control
In this video we will learn about
1. Adding items to the DropDownList control at design time using the HTML
2. Adding items to the DropDownList control at runtime using the code
Drag and drop a DropDownList control onto the webform.
To add items to the DropDownList at deign time
1. Right click on the DropDownList control and select properties.
2. In the properties, click on the ellipsis button next to Items property.
3. In the ListItem Collection Editor window, click the Add button
4. Set the Text to Male and Value to 1.
5. Click the Add button again, which will add another ListItem object
6. Set the Text to Female and Value to 2.
7. Finally click OK
Now switch the webform to source mode. Notice that in the HTML it has added ListItem object, as shown below.
<asp:DropDownList ID="DropDownList1" runat="server">
<asp:ListItem Value="1">Male</asp:ListItem>
<asp:ListItem Value="1">Female</asp:ListItem>
</asp:DropDownList>
If you run the web application now, you should see that Male and Female items shown in the DropDownList.
If you want a specific listitem to be selected in the dropdownlist, when the page loads, then set the Selected property of the ListItem object to true. This can be done in 2 ways.
1. Using the ListItem Collection Editor window or
2. In the HTML of the webform
The HTML with the Selected property is shown below.
<asp:DropDownList ID="DropDownList1" runat="server">
<asp:ListItem Value="1">Male</asp:ListItem>
<asp:ListItem Value="1" Selected="True">Female</asp:ListItem>
</asp:DropDownList>
To hide a ListItem in the DropDownList, set the Enabled property to False.
To add items to the DropDownList at run time using code
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
ListItem maleListItem = new ListItem("Male", "1");
ListItem femaleListItem = new ListItem("Female", "2");
DropDownList1.Items.Add(maleListItem);
DropDownList1.Items.Add(femaleListItem);
}
}
If you are adding listitem objects, to the DropDownList in the Page_Load event, make sure you do only when the page is loaded for the first time. Otherwise, every time, you post the page back, by clicking a button, the list items will be added again causing duplication.
A DropDownList is a collection of ListItem objects. Along the same lines, the following controls are also a collection of ListItem objects. So, adding items to these controls is also very similar to DropDownList.
1. CheckBoxList
2. RadioButtonList
3. BulletedList
4. ListBox
In the next video session, we will discuss about binding the dropdownlist to the data from a database and an XML file.
Data bind asp.net
dropdownlist with data from the database - Part 17
Suggested Videos
Part 14 - Button, LinkButton and ImageButton Controls
Part 15 - Command Event of an asp.net button control
Part 16 - DropDownList in asp.net
In this video, we will learn about, binding data from a database table, to a dropdownlist. We will be using tblCity table for this demo. Please find the script below, to create and populate the table.
Create table tblCity
(
CityId int primary key,
CityName nvarchar(50),
Country nvarchar(50)
)
Insert into tblCity values(101, 'Delhi', 'India')
Insert into tblCity values(102, 'London', 'UK')
Insert into tblCity values(103, 'New York', 'US')
Insert into tblCity values(104, 'Tokyo', 'Japan')
Create an ASP.NET web application. Drag and drop a DropDownList control onto the webform. Copy and paste the following code in the code behind page.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
string CS = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
using (SqlConnection con = new SqlConnection(CS))
{
SqlCommand cmd = new SqlCommand("Select CityId, CityName, Country from tblCity", con);
con.Open();
SqlDataReader rdr = cmd.ExecuteReader();
DropDownList1.DataSource = rdr;
DropDownList1.DataBind();
}
}
}
Run the application. Notice that, the DropDownList displays, System.Data.Common.DataRecordInternal instead of the City names. This is because, we haven't specified the DataTextField and DataValueField properties of the DropDownList. The code below specifes both the properties.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
string CS = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
using (SqlConnection con = new SqlConnection(CS))
{
SqlCommand cmd = new SqlCommand("Select CityId, CityName, Country from tblCity", con);
con.Open();
SqlDataReader rdr = cmd.ExecuteReader();
DropDownList1.DataTextField = "CityName";
DropDownList1.DataValueField = "CityId";
DropDownList1.DataSource = rdr;
DropDownList1.DataBind();
}
}
}
Run the application now. The city names are displayed as expected. But make sure to set the properties(DataTextField, DataValueField) before calling DataBind() method. Also, note that, these properties can be set in the HTML of the aspx page as well.
<asp:DropDownList ID="DropDownList1" DataTextField="CityName"
DataValueField="CityId" runat="server">
</asp:DropDownList>
Part 14 - Button, LinkButton and ImageButton Controls
Part 15 - Command Event of an asp.net button control
Part 16 - DropDownList in asp.net
In this video, we will learn about, binding data from a database table, to a dropdownlist. We will be using tblCity table for this demo. Please find the script below, to create and populate the table.
Create table tblCity
(
CityId int primary key,
CityName nvarchar(50),
Country nvarchar(50)
)
Insert into tblCity values(101, 'Delhi', 'India')
Insert into tblCity values(102, 'London', 'UK')
Insert into tblCity values(103, 'New York', 'US')
Insert into tblCity values(104, 'Tokyo', 'Japan')
Create an ASP.NET web application. Drag and drop a DropDownList control onto the webform. Copy and paste the following code in the code behind page.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
string CS = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
using (SqlConnection con = new SqlConnection(CS))
{
SqlCommand cmd = new SqlCommand("Select CityId, CityName, Country from tblCity", con);
con.Open();
SqlDataReader rdr = cmd.ExecuteReader();
DropDownList1.DataSource = rdr;
DropDownList1.DataBind();
}
}
}
Run the application. Notice that, the DropDownList displays, System.Data.Common.DataRecordInternal instead of the City names. This is because, we haven't specified the DataTextField and DataValueField properties of the DropDownList. The code below specifes both the properties.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
string CS = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
using (SqlConnection con = new SqlConnection(CS))
{
SqlCommand cmd = new SqlCommand("Select CityId, CityName, Country from tblCity", con);
con.Open();
SqlDataReader rdr = cmd.ExecuteReader();
DropDownList1.DataTextField = "CityName";
DropDownList1.DataValueField = "CityId";
DropDownList1.DataSource = rdr;
DropDownList1.DataBind();
}
}
}
Run the application now. The city names are displayed as expected. But make sure to set the properties(DataTextField, DataValueField) before calling DataBind() method. Also, note that, these properties can be set in the HTML of the aspx page as well.
<asp:DropDownList ID="DropDownList1" DataTextField="CityName"
DataValueField="CityId" runat="server">
</asp:DropDownList>
Binding an asp.net
dropdownlist with an XML file - Part 18
Suggested Videos
Part 15 - Command Event of an asp.net button control
Part 16 - DropDownList in asp.net
Part 17 - Data bind asp.net dropdownlist with data from the database
In Part 17 of this video series we have discussed about binding a DropDownList to data that is retrieved from a database. In this part, we will learn about binding the DropDownList to Data from an XML file.
First add an XML file, to the web application project. To do this
1. Right click on the web application project, and select Add => New Item.
2. In the Add New Item dialog box, select XML File.
3. Give the XML file a meaningful name. In our case let's name it Countries.xml and click Add.
4. In the Countries.xml file, copy and paste the following
<?xml version="1.0" encoding="utf-8" ?>
<Countries>
<Country>
<CountryId>101</CountryId>
<CountryName>India</CountryName>
</Country>
<Country>
<CountryId>102</CountryId>
<CountryName>US</CountryName>
</Country>
<Country>
<CountryId>103</CountryId>
<CountryName>Australia</CountryName>
</Country>
<Country>
<CountryId>104</CountryId>
<CountryName>UK</CountryName>
</Country>
</Countries>
Drag and drop a DropDownList on the webform. Copy and paste the following code in the code behind page.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
//Create a new DataSet
DataSet DS = new DataSet();
//Read the xml data from the XML file using ReadXml() method
DS.ReadXml(Server.MapPath("Countries.xml"));
DropDownList1.DataTextField = "CountryName";
DropDownList1.DataValueField = "CountryId";
DropDownList1.DataSource = DS;
DropDownList1.DataBind();
ListItem li = new ListItem("Select", "-1");
DropDownList1.Items.Insert(0, li);
}
}
The important thing to notice here is that, we are using ReadXml() method of the DataSet object, to read the data from the Countries.xml file into a DataSet. Server.MapPath() method returns the physical path of the file from the provided virtual path. We will discuss about this method in a later video session.
To insert a ListItem at a specific location use the Insert() method specifying the index of the location where you want to insert, and the listitem object.
Part 15 - Command Event of an asp.net button control
Part 16 - DropDownList in asp.net
Part 17 - Data bind asp.net dropdownlist with data from the database
In Part 17 of this video series we have discussed about binding a DropDownList to data that is retrieved from a database. In this part, we will learn about binding the DropDownList to Data from an XML file.
First add an XML file, to the web application project. To do this
1. Right click on the web application project, and select Add => New Item.
2. In the Add New Item dialog box, select XML File.
3. Give the XML file a meaningful name. In our case let's name it Countries.xml and click Add.
4. In the Countries.xml file, copy and paste the following
<?xml version="1.0" encoding="utf-8" ?>
<Countries>
<Country>
<CountryId>101</CountryId>
<CountryName>India</CountryName>
</Country>
<Country>
<CountryId>102</CountryId>
<CountryName>US</CountryName>
</Country>
<Country>
<CountryId>103</CountryId>
<CountryName>Australia</CountryName>
</Country>
<Country>
<CountryId>104</CountryId>
<CountryName>UK</CountryName>
</Country>
</Countries>
Drag and drop a DropDownList on the webform. Copy and paste the following code in the code behind page.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
//Create a new DataSet
DataSet DS = new DataSet();
//Read the xml data from the XML file using ReadXml() method
DS.ReadXml(Server.MapPath("Countries.xml"));
DropDownList1.DataTextField = "CountryName";
DropDownList1.DataValueField = "CountryId";
DropDownList1.DataSource = DS;
DropDownList1.DataBind();
ListItem li = new ListItem("Select", "-1");
DropDownList1.Items.Insert(0, li);
}
}
The important thing to notice here is that, we are using ReadXml() method of the DataSet object, to read the data from the Countries.xml file into a DataSet. Server.MapPath() method returns the physical path of the file from the provided virtual path. We will discuss about this method in a later video session.
To insert a ListItem at a specific location use the Insert() method specifying the index of the location where you want to insert, and the listitem object.
Mapping virtual path to
physical path using Server.MapPath method - Part 19
Suggested Videos
Part 16 - DropDownList in asp.net
Part 17 - Data bind asp.net dropdownlist with data from the database
Part 18 - Binding an asp.net dropdownlist with an XML file
In this video we will discuss about Server.MapPath() method. This method returns the physical path for a given virtual path. This method can be used in several different ways, depending on the characters that we use in the virtual path. Let's understand this with an example.
1. Create an asp.net web application in C:\ and name it SampleWeb.
2. Right click on the SampleWeb project in solution explorer and add a new webform and name it PageInRootDirectory.aspx
3. Add a new folder to the project and name it Categories.
4. Right click on the Categories folder, and add another folder. name it Electronics
5. Add a webform to the Electronics folder and name it PageInElectronicsFolder.aspx
6. At this point, right click on the web application project and add a new folder. Name it Data.
7. Add a sub folder to Data, and name it Countries
8. Right click on the Countries folder and add an XML file. Name it Countries.xml.
9. Copy and paste the following in Countries.xml file.
<?xml version="1.0" encoding="utf-8" ?>
<Countries>
<Country>
<CountryId>101</CountryId>
<CountryName>India</CountryName>
</Country>
<Country>
<CountryId>102</CountryId>
<CountryName>US</CountryName>
</Country>
<Country>
<CountryId>103</CountryId>
<CountryName>Australia</CountryName>
</Country>
<Country>
<CountryId>104</CountryId>
<CountryName>UK</CountryName>
</Country>
</Countries>
If you are following along with me, at this stage, the solution explorer should look as shown below.

Copy and paste the following code in PageInElectronicsFolder.aspx.cs
Response.Write(". returns " + Server.MapPath(".") + "<br/>");
Response.Write(".. returns " + Server.MapPath("..") + "<br/>");
Response.Write("~ returns " + Server.MapPath("~") + "<br/>");
Running this page would produce the following output.
. returns C:\SampleWeb\SampleWeb\Categories\Electronics
.. returns C:\SampleWeb\SampleWeb\Categories
~ returns C:\SampleWeb\SampleWeb
From the output, it should be clear that
Server.MapPath(".") returns the current physical directory of the page that you are running
Server.MapPath("..") returns the parent pysical directory of the page that you are running
Server.MapPath("~") returns the physical path of the root directory of the application
Part 16 - DropDownList in asp.net
Part 17 - Data bind asp.net dropdownlist with data from the database
Part 18 - Binding an asp.net dropdownlist with an XML file
In this video we will discuss about Server.MapPath() method. This method returns the physical path for a given virtual path. This method can be used in several different ways, depending on the characters that we use in the virtual path. Let's understand this with an example.
1. Create an asp.net web application in C:\ and name it SampleWeb.
2. Right click on the SampleWeb project in solution explorer and add a new webform and name it PageInRootDirectory.aspx
3. Add a new folder to the project and name it Categories.
4. Right click on the Categories folder, and add another folder. name it Electronics
5. Add a webform to the Electronics folder and name it PageInElectronicsFolder.aspx
6. At this point, right click on the web application project and add a new folder. Name it Data.
7. Add a sub folder to Data, and name it Countries
8. Right click on the Countries folder and add an XML file. Name it Countries.xml.
9. Copy and paste the following in Countries.xml file.
<?xml version="1.0" encoding="utf-8" ?>
<Countries>
<Country>
<CountryId>101</CountryId>
<CountryName>India</CountryName>
</Country>
<Country>
<CountryId>102</CountryId>
<CountryName>US</CountryName>
</Country>
<Country>
<CountryId>103</CountryId>
<CountryName>Australia</CountryName>
</Country>
<Country>
<CountryId>104</CountryId>
<CountryName>UK</CountryName>
</Country>
</Countries>
If you are following along with me, at this stage, the solution explorer should look as shown below.

Copy and paste the following code in PageInElectronicsFolder.aspx.cs
Response.Write(". returns " + Server.MapPath(".") + "<br/>");
Response.Write(".. returns " + Server.MapPath("..") + "<br/>");
Response.Write("~ returns " + Server.MapPath("~") + "<br/>");
Running this page would produce the following output.
. returns C:\SampleWeb\SampleWeb\Categories\Electronics
.. returns C:\SampleWeb\SampleWeb\Categories
~ returns C:\SampleWeb\SampleWeb
From the output, it should be clear that
Server.MapPath(".") returns the current physical directory of the page that you are running
Server.MapPath("..") returns the parent pysical directory of the page that you are running
Server.MapPath("~") returns the physical path of the root directory of the application
Mapping virtual path
to physical path using Server.MapPath method Example - Part 20
Suggested Videos
Part 17 - Data bind asp.net dropdownlist with data from the database
Part 18 - Binding an asp.net dropdownlist with an XML file
Part 19 - Mapping virtual path to physical path using Server.MapPath method
In Part 19 of asp.net video series, we discussed about Server.MapPath() method. In this video, we will continue with a practical application of this method. Please watch Part 19 first, if haven't already done so.
Drag and drop a DropDownList control onto PageInElectronicsFolder.aspx webform. Copy and paste the following code in the code behind file.
DataSet DS = new DataSet();
DS.ReadXml(Server.MapPath("../../Data/Countries/Countries.xml"));
DropDownList1.DataTextField = "CountryName";
DropDownList1.DataValueField = "CountryId";
DropDownList1.DataSource = DS;
DropDownList1.DataBind();
C:\SampleWeb\SampleWeb is the root directory for the sample asp.net web application that we used in the Demo. To get to this root directory we are passing ../../ to the Server.MapPath() method as shown below.
DS.ReadXml(Server.MapPath("../../Data/Countries/Countries.xml"));
The number of double dots, that you use, depends on how deep you are in the folder hierarchy. To avoid confusion, if any time you want to navigate to the root directory of the application, it is better to use ~(tilde) character as shown below.
DS.ReadXml(Server.MapPath("~/Data/Countries/Countries.xml"));
Tilde(~) symbol resolves to the root application directory, no matter how deep you are in the folder hierarchy. This is the advantage of using ~(tilde), over ..(2 Dots). The following code would work from any folder in our application.
DS.ReadXml(Server.MapPath("~/Data/Countries/Countries.xml"));
Where as, the following code will only work from folders, that are 2 levels deeper relative to the root directory of the application.
DS.ReadXml(Server.MapPath("../../Data/Countries/Countries.xml"));
Part 17 - Data bind asp.net dropdownlist with data from the database
Part 18 - Binding an asp.net dropdownlist with an XML file
Part 19 - Mapping virtual path to physical path using Server.MapPath method
In Part 19 of asp.net video series, we discussed about Server.MapPath() method. In this video, we will continue with a practical application of this method. Please watch Part 19 first, if haven't already done so.
Drag and drop a DropDownList control onto PageInElectronicsFolder.aspx webform. Copy and paste the following code in the code behind file.
DataSet DS = new DataSet();
DS.ReadXml(Server.MapPath("../../Data/Countries/Countries.xml"));
DropDownList1.DataTextField = "CountryName";
DropDownList1.DataValueField = "CountryId";
DropDownList1.DataSource = DS;
DropDownList1.DataBind();
C:\SampleWeb\SampleWeb is the root directory for the sample asp.net web application that we used in the Demo. To get to this root directory we are passing ../../ to the Server.MapPath() method as shown below.
DS.ReadXml(Server.MapPath("../../Data/Countries/Countries.xml"));
The number of double dots, that you use, depends on how deep you are in the folder hierarchy. To avoid confusion, if any time you want to navigate to the root directory of the application, it is better to use ~(tilde) character as shown below.
DS.ReadXml(Server.MapPath("~/Data/Countries/Countries.xml"));
Tilde(~) symbol resolves to the root application directory, no matter how deep you are in the folder hierarchy. This is the advantage of using ~(tilde), over ..(2 Dots). The following code would work from any folder in our application.
DS.ReadXml(Server.MapPath("~/Data/Countries/Countries.xml"));
Where as, the following code will only work from folders, that are 2 levels deeper relative to the root directory of the application.
DS.ReadXml(Server.MapPath("../../Data/Countries/Countries.xml"));
Retrieving selected
item text, value and index of an asp.net dropdownlist - Part 21
Suggested Videos
Part 16 - Dropdownlist in asp.net
Part 17 - Data bind dropdownlist with data from the database
Part 18 - Data bind dropdownlist with data from an xml file
In this video we will discuss about retrieving the selected item text, index and value from a dropdownlist. Let's first add some items to the dropdownlist. To do this
1. Drag and drop a dropdownlist and a button control onto the webform
2. Copy and paste the following HTML on the webform.
<asp:DropDownList ID="DropDownList1" runat="server">
<asp:ListItem Text="Select Continent" Value="-1"></asp:ListItem>
<asp:ListItem Text="Asia" Value="1"></asp:ListItem>
<asp:ListItem Text="Europe" Value="2"></asp:ListItem>
<asp:ListItem Text="Africa" Value="3"></asp:ListItem>
<asp:ListItem Text="North America" Value="4"></asp:ListItem>
<asp:ListItem Text="South America" Value="5"></asp:ListItem>
</asp:DropDownList>
<br /><br />
<asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" />
Copy and paste the following code in the code behind file.
protected void Button1_Click(object sender, EventArgs e)
{
if (DropDownList1.SelectedValue != "-1")
{
Response.Write("Selected Item Text = " + DropDownList1.SelectedItem.Text + "<br/>");
Response.Write("Selected Item Value = " + DropDownList1.SelectedItem.Value + "<br/>");
Response.Write("Selected Item Index = " + DropDownList1.SelectedIndex.ToString());
}
else
{
Response.Write("Please select the continent");
}
}
Explanation of the code:
1. In the button click event, we first check if the user has made a selection. If the DropDownList1.SelectedValue is -1, then we know that user has not made a choice.
if (DropDownList1.SelectedValue != "-1")
2. If the user has made a selection in the DropDownList, then we retrieve the Text of the Selected ListItem object as shown below.
DropDownList1.SelectedItem.Text
3. To retrieve the Selected item value from the DropDownList, we can use
DropDownList1.SelectedItem.Value
OR
DropDownList1.SelectedValue
4. To get the index of the Selected ListItem object of the dropdownlist, we use SelectedIndex property as shown below.
DropDownList1.SelectedIndex
The SelectedIndex and SelectedValue properties of the DropDownList can also be used to have a list item selected in the DropDownList. For example, the following code would default the selection to Asia when the page loads for the first time.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DropDownList1.SelectedValue = "1";
}
}
The same thing can also be achieved using the SelectedIndex property as shown below.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DropDownList1.SelectedIndex = 1;
}
}
Part 16 - Dropdownlist in asp.net
Part 17 - Data bind dropdownlist with data from the database
Part 18 - Data bind dropdownlist with data from an xml file
In this video we will discuss about retrieving the selected item text, index and value from a dropdownlist. Let's first add some items to the dropdownlist. To do this
1. Drag and drop a dropdownlist and a button control onto the webform
2. Copy and paste the following HTML on the webform.
<asp:DropDownList ID="DropDownList1" runat="server">
<asp:ListItem Text="Select Continent" Value="-1"></asp:ListItem>
<asp:ListItem Text="Asia" Value="1"></asp:ListItem>
<asp:ListItem Text="Europe" Value="2"></asp:ListItem>
<asp:ListItem Text="Africa" Value="3"></asp:ListItem>
<asp:ListItem Text="North America" Value="4"></asp:ListItem>
<asp:ListItem Text="South America" Value="5"></asp:ListItem>
</asp:DropDownList>
<br /><br />
<asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" />
Copy and paste the following code in the code behind file.
protected void Button1_Click(object sender, EventArgs e)
{
if (DropDownList1.SelectedValue != "-1")
{
Response.Write("Selected Item Text = " + DropDownList1.SelectedItem.Text + "<br/>");
Response.Write("Selected Item Value = " + DropDownList1.SelectedItem.Value + "<br/>");
Response.Write("Selected Item Index = " + DropDownList1.SelectedIndex.ToString());
}
else
{
Response.Write("Please select the continent");
}
}
Explanation of the code:
1. In the button click event, we first check if the user has made a selection. If the DropDownList1.SelectedValue is -1, then we know that user has not made a choice.
if (DropDownList1.SelectedValue != "-1")
2. If the user has made a selection in the DropDownList, then we retrieve the Text of the Selected ListItem object as shown below.
DropDownList1.SelectedItem.Text
3. To retrieve the Selected item value from the DropDownList, we can use
DropDownList1.SelectedItem.Value
OR
DropDownList1.SelectedValue
4. To get the index of the Selected ListItem object of the dropdownlist, we use SelectedIndex property as shown below.
DropDownList1.SelectedIndex
The SelectedIndex and SelectedValue properties of the DropDownList can also be used to have a list item selected in the DropDownList. For example, the following code would default the selection to Asia when the page loads for the first time.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DropDownList1.SelectedValue = "1";
}
}
The same thing can also be achieved using the SelectedIndex property as shown below.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DropDownList1.SelectedIndex = 1;
}
}
Cascading dropdown in
asp.net - Part 22
Suggested Videos
Part 16 - Dropdownlist in asp.net
Part 17 - Data bind dropdownlist with data from the database
Part 21 - Retrieving selected item text, value and index of the dropdownlist
In this video we will discuss about cascading dropdownlists. First create the required tables and populate them, with some sample data using the SQL script below.
Create Table tblContinents
(
ContinentId int identity primary key,
ContinentName nvarchar(50)
)
Insert into tblContinents values ('Asia')
Insert into tblContinents values ('Europe')
Insert into tblContinents values ('South America')
Create Table tblCountries
(
CountryId int identity primary key,
CountryName nvarchar(50),
ContinentId int foreign key references dbo.tblContinents(ContinentId)
)
Insert into tblCountries values ('India', 1)
Insert into tblCountries values ('Japan', 1)
Insert into tblCountries values ('Malaysia', 1)
Insert into tblCountries values ('United Kingdom', 2)
Insert into tblCountries values ('France', 2)
Insert into tblCountries values ('Germany', 2)
Insert into tblCountries values ('Argentina', 3)
Insert into tblCountries values ('Brazil', 3)
Insert into tblCountries values ('Colombia', 3)
Create Table tblCities
(
CityId int identity primary key,
CityName nvarchar(50),
CountryId int foreign key references dbo.tblCountries(CountryId)
)
Insert into tblCities values ('Bangalore', 1)
Insert into tblCities values ('Chennai', 1)
Insert into tblCities values ('Mumbai', 1)
Insert into tblCities values ('Tokyo', 2)
Insert into tblCities values ('Hiroshima', 2)
Insert into tblCities values ('Saku', 2)
Insert into tblCities values ('Kuala Lumpur', 3)
Insert into tblCities values ('Ipoh', 3)
Insert into tblCities values ('Tawau', 3)
Insert into tblCities values ('London', 4)
Insert into tblCities values ('Manchester', 4)
Insert into tblCities values ('Birmingham', 4)
Insert into tblCities values ('Paris', 5)
Insert into tblCities values ('Cannes', 5)
Insert into tblCities values ('Nice', 5)
Insert into tblCities values ('Frankfurt', 6)
Insert into tblCities values ('Eutin', 6)
Insert into tblCities values ('Alsfeld', 6)
Insert into tblCities values ('Rosario', 7)
Insert into tblCities values ('Salta', 7)
Insert into tblCities values ('Corrientes', 7)
Insert into tblCities values ('Rio de Janeiro', 8)
Insert into tblCities values ('Salvador', 8)
Insert into tblCities values ('BrasÃlia', 8)
Insert into tblCities values ('Cali', 9)
Insert into tblCities values ('MonterÃa', 9)
Insert into tblCities values ('Bello', 9)
Create procedure spGetContinents
as
Begin
Select ContinentId, ContinentName from tblContinents
End
Create procedure spGetCountriesByContinentId
@ContinentId int
as
Begin
Select CountryId, CountryName from tblCountries
where ContinentId = @ContinentId
End
Create procedure spGetCitiesByCountryId
@CountryId int
as
Begin
Select CityId, CityName from tblCities
where CountryId = @CountryId
End
Let's understand cascading dropdownlists with an example. The following are the 3 dropsownlist controls, that we will have in our asp.net web application.
1. Continents DropDownList
2. Countries DropDownList
3. Cities DropDownList
When the webform first loads, only the continents dropdownlist should be populated. Countries and Cities dropdownlist should be disabled and should not allow the user to select anything from these 2 dropdownlists. Once, the user makes a selection in the continents dropdownlist, then Countries dropdownlist should be enabled and populated with the countries that belong to the selected continent. The same logic applies for the cities dropdownlist.
To achieve this drag and drop 3 dropdownlist controls onto the webform. The HTML of the Webform should be as shown below.
<asp:DropDownList ID="ddlContinents" Width="200px" DataTextField="ContinentName"
DataValueField="ContinentId" runat="server" AutoPostBack="True"
onselectedindexchanged="ddlContinents_SelectedIndexChanged">
</asp:DropDownList>
<br /><br />
<asp:DropDownList ID="ddlCountries" DataValueField="CountryId"
DataTextField="CountryName" Width="200px" runat="server" AutoPostBack="True"
onselectedindexchanged="ddlCountries_SelectedIndexChanged">
</asp:DropDownList>
<br /><br />
<asp:DropDownList ID="ddlCities" Width="200px" DataTextField="CityName"
DataValueField="CityId" runat="server">
</asp:DropDownList>
Copy and paste the following code in the code behind page
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
PopulateContinentsDropDownList();
}
}
private void PopulateContinentsDropDownList()
{
ddlContinents.DataSource = GetData("spGetContinents", null);
ddlContinents.DataBind();
ListItem liContinent = new ListItem("Select Continent", "-1");
ddlContinents.Items.Insert(0, liContinent);
ListItem liCountry = new ListItem("Select Country", "-1");
ddlCountries.Items.Insert(0, liCountry);
ListItem liCity = new ListItem("Select City", "-1");
ddlCities.Items.Insert(0, liCity);
ddlCountries.Enabled = false;
ddlCities.Enabled = false;
}
private DataSet GetData(string SPName, SqlParameter SPParameter)
{
string CS = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
SqlConnection con = new SqlConnection(CS);
SqlDataAdapter da = new SqlDataAdapter(SPName, con);
da.SelectCommand.CommandType = CommandType.StoredProcedure;
if (SPParameter != null)
{
da.SelectCommand.Parameters.Add(SPParameter);
}
DataSet DS = new DataSet();
da.Fill(DS);
return DS;
}
protected void ddlContinents_SelectedIndexChanged(object sender, EventArgs e)
{
if (ddlContinents.SelectedValue == "-1")
{
ddlCities.SelectedIndex = 0;
ddlCountries.SelectedIndex = 0;
ddlCities.Enabled = false;
ddlCountries.Enabled = false;
}
else
{
ddlCountries.Enabled = true;
SqlParameter parameter = new SqlParameter();
parameter.ParameterName = "@ContinentId";
parameter.Value = ddlContinents.SelectedValue;
ddlCountries.DataSource = GetData("spGetCountriesByContinentId", parameter);
ddlCountries.DataBind();
ListItem liCountry = new ListItem("Select Country", "-1");
ddlCountries.Items.Insert(0, liCountry);
ddlCities.SelectedIndex = 0;
ddlCities.Enabled = false;
}
}
protected void ddlCountries_SelectedIndexChanged(object sender, EventArgs e)
{
if (ddlCountries.SelectedValue == "-1")
{
ddlCities.SelectedIndex = 0;
ddlCities.Enabled = false;
}
else
{
ddlCities.Enabled = true;
SqlParameter parameter = new SqlParameter();
parameter.ParameterName = "@CountryId";
parameter.Value = ddlCountries.SelectedValue;
ddlCities.DataSource = GetData("spGetCitiesByCountryId", parameter);
ddlCities.DataBind();
ListItem liCity = new ListItem("Select City", "-1");
ddlCities.Items.Insert(0, liCity);
}
}
Part 16 - Dropdownlist in asp.net
Part 17 - Data bind dropdownlist with data from the database
Part 21 - Retrieving selected item text, value and index of the dropdownlist
In this video we will discuss about cascading dropdownlists. First create the required tables and populate them, with some sample data using the SQL script below.
Create Table tblContinents
(
ContinentId int identity primary key,
ContinentName nvarchar(50)
)
Insert into tblContinents values ('Asia')
Insert into tblContinents values ('Europe')
Insert into tblContinents values ('South America')
Create Table tblCountries
(
CountryId int identity primary key,
CountryName nvarchar(50),
ContinentId int foreign key references dbo.tblContinents(ContinentId)
)
Insert into tblCountries values ('India', 1)
Insert into tblCountries values ('Japan', 1)
Insert into tblCountries values ('Malaysia', 1)
Insert into tblCountries values ('United Kingdom', 2)
Insert into tblCountries values ('France', 2)
Insert into tblCountries values ('Germany', 2)
Insert into tblCountries values ('Argentina', 3)
Insert into tblCountries values ('Brazil', 3)
Insert into tblCountries values ('Colombia', 3)
Create Table tblCities
(
CityId int identity primary key,
CityName nvarchar(50),
CountryId int foreign key references dbo.tblCountries(CountryId)
)
Insert into tblCities values ('Bangalore', 1)
Insert into tblCities values ('Chennai', 1)
Insert into tblCities values ('Mumbai', 1)
Insert into tblCities values ('Tokyo', 2)
Insert into tblCities values ('Hiroshima', 2)
Insert into tblCities values ('Saku', 2)
Insert into tblCities values ('Kuala Lumpur', 3)
Insert into tblCities values ('Ipoh', 3)
Insert into tblCities values ('Tawau', 3)
Insert into tblCities values ('London', 4)
Insert into tblCities values ('Manchester', 4)
Insert into tblCities values ('Birmingham', 4)
Insert into tblCities values ('Paris', 5)
Insert into tblCities values ('Cannes', 5)
Insert into tblCities values ('Nice', 5)
Insert into tblCities values ('Frankfurt', 6)
Insert into tblCities values ('Eutin', 6)
Insert into tblCities values ('Alsfeld', 6)
Insert into tblCities values ('Rosario', 7)
Insert into tblCities values ('Salta', 7)
Insert into tblCities values ('Corrientes', 7)
Insert into tblCities values ('Rio de Janeiro', 8)
Insert into tblCities values ('Salvador', 8)
Insert into tblCities values ('BrasÃlia', 8)
Insert into tblCities values ('Cali', 9)
Insert into tblCities values ('MonterÃa', 9)
Insert into tblCities values ('Bello', 9)
Create procedure spGetContinents
as
Begin
Select ContinentId, ContinentName from tblContinents
End
Create procedure spGetCountriesByContinentId
@ContinentId int
as
Begin
Select CountryId, CountryName from tblCountries
where ContinentId = @ContinentId
End
Create procedure spGetCitiesByCountryId
@CountryId int
as
Begin
Select CityId, CityName from tblCities
where CountryId = @CountryId
End
Let's understand cascading dropdownlists with an example. The following are the 3 dropsownlist controls, that we will have in our asp.net web application.
1. Continents DropDownList
2. Countries DropDownList
3. Cities DropDownList
When the webform first loads, only the continents dropdownlist should be populated. Countries and Cities dropdownlist should be disabled and should not allow the user to select anything from these 2 dropdownlists. Once, the user makes a selection in the continents dropdownlist, then Countries dropdownlist should be enabled and populated with the countries that belong to the selected continent. The same logic applies for the cities dropdownlist.
To achieve this drag and drop 3 dropdownlist controls onto the webform. The HTML of the Webform should be as shown below.
<asp:DropDownList ID="ddlContinents" Width="200px" DataTextField="ContinentName"
DataValueField="ContinentId" runat="server" AutoPostBack="True"
onselectedindexchanged="ddlContinents_SelectedIndexChanged">
</asp:DropDownList>
<br /><br />
<asp:DropDownList ID="ddlCountries" DataValueField="CountryId"
DataTextField="CountryName" Width="200px" runat="server" AutoPostBack="True"
onselectedindexchanged="ddlCountries_SelectedIndexChanged">
</asp:DropDownList>
<br /><br />
<asp:DropDownList ID="ddlCities" Width="200px" DataTextField="CityName"
DataValueField="CityId" runat="server">
</asp:DropDownList>
Copy and paste the following code in the code behind page
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
PopulateContinentsDropDownList();
}
}
private void PopulateContinentsDropDownList()
{
ddlContinents.DataSource = GetData("spGetContinents", null);
ddlContinents.DataBind();
ListItem liContinent = new ListItem("Select Continent", "-1");
ddlContinents.Items.Insert(0, liContinent);
ListItem liCountry = new ListItem("Select Country", "-1");
ddlCountries.Items.Insert(0, liCountry);
ListItem liCity = new ListItem("Select City", "-1");
ddlCities.Items.Insert(0, liCity);
ddlCountries.Enabled = false;
ddlCities.Enabled = false;
}
private DataSet GetData(string SPName, SqlParameter SPParameter)
{
string CS = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
SqlConnection con = new SqlConnection(CS);
SqlDataAdapter da = new SqlDataAdapter(SPName, con);
da.SelectCommand.CommandType = CommandType.StoredProcedure;
if (SPParameter != null)
{
da.SelectCommand.Parameters.Add(SPParameter);
}
DataSet DS = new DataSet();
da.Fill(DS);
return DS;
}
protected void ddlContinents_SelectedIndexChanged(object sender, EventArgs e)
{
if (ddlContinents.SelectedValue == "-1")
{
ddlCities.SelectedIndex = 0;
ddlCountries.SelectedIndex = 0;
ddlCities.Enabled = false;
ddlCountries.Enabled = false;
}
else
{
ddlCountries.Enabled = true;
SqlParameter parameter = new SqlParameter();
parameter.ParameterName = "@ContinentId";
parameter.Value = ddlContinents.SelectedValue;
ddlCountries.DataSource = GetData("spGetCountriesByContinentId", parameter);
ddlCountries.DataBind();
ListItem liCountry = new ListItem("Select Country", "-1");
ddlCountries.Items.Insert(0, liCountry);
ddlCities.SelectedIndex = 0;
ddlCities.Enabled = false;
}
}
protected void ddlCountries_SelectedIndexChanged(object sender, EventArgs e)
{
if (ddlCountries.SelectedValue == "-1")
{
ddlCities.SelectedIndex = 0;
ddlCities.Enabled = false;
}
else
{
ddlCities.Enabled = true;
SqlParameter parameter = new SqlParameter();
parameter.ParameterName = "@CountryId";
parameter.Value = ddlCountries.SelectedValue;
ddlCities.DataSource = GetData("spGetCitiesByCountryId", parameter);
ddlCities.DataBind();
ListItem liCity = new ListItem("Select City", "-1");
ddlCities.Items.Insert(0, liCity);
}
}
Suggested Videos
Part 16 - Dropdownlist in asp.net
Part 17 - Data bind dropdownlist with data from the database
Part 21 - Retrieving selected item text, value and index of the dropdownlist
In this video we will learn about asp.net checkboxlist control. Just like DropDownList
1. CheckBoxList is collection of ListItem objects.
2. Items can be added to the CheckBoxList in the HTML source or in the code behind file
3. CheckBoxList can be bound to a database table or an xml file
DropDownList is generally used, when you want to present the user with multiple choices, from which you want him to select only one option. Where as if you want the user to select more than one option, then a CheckBoxList control can be used.
Create an asp.net web application. Copy and paste the following HTML
<asp:CheckBoxList ID="checkboxListEducation" runat="server"
RepeatDirection="Horizontal">
<asp:ListItem Text="Diploma" Value="1"></asp:ListItem>
<asp:ListItem Text="Graduate" Value="2"></asp:ListItem>
<asp:ListItem Text="Post Graduate" Value="3"></asp:ListItem>
<asp:ListItem Text="Doctrate" Value="4"></asp:ListItem>
</asp:CheckBoxList>
<br />
<asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" />
Copy and paste the following code in Button1_Click event. The sample code prints the Text, Value and Index of the selected list item object.
// Loop thru each list item in the checkboxlist
foreach (ListItem li in checkboxListEducation.Items)
{
// If the list item is selected
if (li.Selected)
{
// Retrieve the text of the selected list item
Response.Write("Text = " + li.Text + ", ");
// Retrieve the value of the selected list item
Response.Write("Value = " + li.Value + ", ");
// Retrieve the index of the selected list item
Response.Write("Index = " + checkboxListEducation.Items.IndexOf(li).ToString());
Response.Write("<br/>");
}
}
By default, the ListItem objects are laid out in vertical direction. If you want to change the direction, use RepeatDirection property
<asp:CheckBoxList ID="checkkboxListEducation" runat="server" RepeatDirection="Horizontal">
RepeatColumns property specifies the number of columns used to lay out the items.
Set the Enabled property of the ListItem object to false, to disable the selection, in the CheckBoxList control.
SelectedIndex property of the CheckBoxList control can also be used to get the index of the selected item in the checkboxlist. But this property, returns only one selected item, and that too, the item with the lowest index. SelectedIndex property returns -1, if nothing is selected.
SelectedValue property returns the selected Item's value, but only for one selected item. If no item is selected this property returns empty string.
To retrieve the Text of the selected item, SelectedItem.Text property can be used. SelectedItem will be NULL, if nothing is selected, and hence, calling Text and Value properties may cause NullReferenceException. Hence, it is important to check for null, when using SelectedItem property of a CheckBoxList control.
if (checkboxListEducation.SelectedItem != null)
{
Response.Write(checkboxListEducation.SelectedItem.Text);
}
Part 16 - Dropdownlist in asp.net
Part 17 - Data bind dropdownlist with data from the database
Part 21 - Retrieving selected item text, value and index of the dropdownlist
In this video we will learn about asp.net checkboxlist control. Just like DropDownList
1. CheckBoxList is collection of ListItem objects.
2. Items can be added to the CheckBoxList in the HTML source or in the code behind file
3. CheckBoxList can be bound to a database table or an xml file
DropDownList is generally used, when you want to present the user with multiple choices, from which you want him to select only one option. Where as if you want the user to select more than one option, then a CheckBoxList control can be used.
Create an asp.net web application. Copy and paste the following HTML
<asp:CheckBoxList ID="checkboxListEducation" runat="server"
RepeatDirection="Horizontal">
<asp:ListItem Text="Diploma" Value="1"></asp:ListItem>
<asp:ListItem Text="Graduate" Value="2"></asp:ListItem>
<asp:ListItem Text="Post Graduate" Value="3"></asp:ListItem>
<asp:ListItem Text="Doctrate" Value="4"></asp:ListItem>
</asp:CheckBoxList>
<br />
<asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" />
Copy and paste the following code in Button1_Click event. The sample code prints the Text, Value and Index of the selected list item object.
// Loop thru each list item in the checkboxlist
foreach (ListItem li in checkboxListEducation.Items)
{
// If the list item is selected
if (li.Selected)
{
// Retrieve the text of the selected list item
Response.Write("Text = " + li.Text + ", ");
// Retrieve the value of the selected list item
Response.Write("Value = " + li.Value + ", ");
// Retrieve the index of the selected list item
Response.Write("Index = " + checkboxListEducation.Items.IndexOf(li).ToString());
Response.Write("<br/>");
}
}
By default, the ListItem objects are laid out in vertical direction. If you want to change the direction, use RepeatDirection property
<asp:CheckBoxList ID="checkkboxListEducation" runat="server" RepeatDirection="Horizontal">
RepeatColumns property specifies the number of columns used to lay out the items.
Set the Enabled property of the ListItem object to false, to disable the selection, in the CheckBoxList control.
SelectedIndex property of the CheckBoxList control can also be used to get the index of the selected item in the checkboxlist. But this property, returns only one selected item, and that too, the item with the lowest index. SelectedIndex property returns -1, if nothing is selected.
SelectedValue property returns the selected Item's value, but only for one selected item. If no item is selected this property returns empty string.
To retrieve the Text of the selected item, SelectedItem.Text property can be used. SelectedItem will be NULL, if nothing is selected, and hence, calling Text and Value properties may cause NullReferenceException. Hence, it is important to check for null, when using SelectedItem property of a CheckBoxList control.
if (checkboxListEducation.SelectedItem != null)
{
Response.Write(checkboxListEducation.SelectedItem.Text);
}
Asp.net checkboxlist,
select or deselect all list items - Part 24
Suggested Videos
Part 17 - Data bind dropdownlist with data from the database
Part 21 - Retrieving selected item text, value and index of the dropdownlist
Part 23 - Asp.net checkboxlist control
In this video we will learn about
1. Selecting a specific ListItem with-in a CheckBoxList control using SelectedValue and SelectedIndex properties
2. Selecting or De-Selecting all ListItems of a CheckBoxList control
To have a ListItem pre-selected, when the page renders, we can do that in the HTML by setting the Selected property to True as shown below.
<asp:ListItem Text="Diploma" Selected="True" Value="1"></asp:ListItem>
This can be programmatically done, using the SelectedValue property as shown below.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
CheckBoxList1.SelectedValue = "1";
}
}
SelectedIndex property can also be used.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
CheckBoxList1.SelectedIndex = 2;
}
}
Copy and paste the following HTML and Code in the ASPX and the code behind page
<asp:Button ID="buttonSelectAll" runat="server" Text="Select All"
onclick="buttonSelectAll_Click" />
<asp:Button ID="buttonDeselectAll" runat="server" Text="De-Select All"
onclick="buttonDeselectAll_Click" />
<br /><br />
<asp:CheckBoxList ID="CheckBoxList1" runat="server"
RepeatDirection="Horizontal">
<asp:ListItem Text="Diploma" Value="1"></asp:ListItem>
<asp:ListItem Text="Graduate" Value="2"></asp:ListItem>
<asp:ListItem Text="Post Graduate" Value="3"></asp:ListItem>
<asp:ListItem Text="Doctrate" Value="4"></asp:ListItem>
</asp:CheckBoxList>
protected void buttonSelectAll_Click(object sender, EventArgs e)
{
foreach (ListItem li in CheckBoxList1.Items)
{
li.Selected = true;
}
}
protected void buttonDeselectAll_Click(object sender, EventArgs e)
{
foreach (ListItem li in CheckBoxList1.Items)
{
li.Selected = false;
}
}
Part 17 - Data bind dropdownlist with data from the database
Part 21 - Retrieving selected item text, value and index of the dropdownlist
Part 23 - Asp.net checkboxlist control
In this video we will learn about
1. Selecting a specific ListItem with-in a CheckBoxList control using SelectedValue and SelectedIndex properties
2. Selecting or De-Selecting all ListItems of a CheckBoxList control
To have a ListItem pre-selected, when the page renders, we can do that in the HTML by setting the Selected property to True as shown below.
<asp:ListItem Text="Diploma" Selected="True" Value="1"></asp:ListItem>
This can be programmatically done, using the SelectedValue property as shown below.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
CheckBoxList1.SelectedValue = "1";
}
}
SelectedIndex property can also be used.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
CheckBoxList1.SelectedIndex = 2;
}
}
Copy and paste the following HTML and Code in the ASPX and the code behind page
<asp:Button ID="buttonSelectAll" runat="server" Text="Select All"
onclick="buttonSelectAll_Click" />
<asp:Button ID="buttonDeselectAll" runat="server" Text="De-Select All"
onclick="buttonDeselectAll_Click" />
<br /><br />
<asp:CheckBoxList ID="CheckBoxList1" runat="server"
RepeatDirection="Horizontal">
<asp:ListItem Text="Diploma" Value="1"></asp:ListItem>
<asp:ListItem Text="Graduate" Value="2"></asp:ListItem>
<asp:ListItem Text="Post Graduate" Value="3"></asp:ListItem>
<asp:ListItem Text="Doctrate" Value="4"></asp:ListItem>
</asp:CheckBoxList>
protected void buttonSelectAll_Click(object sender, EventArgs e)
{
foreach (ListItem li in CheckBoxList1.Items)
{
li.Selected = true;
}
}
protected void buttonDeselectAll_Click(object sender, EventArgs e)
{
foreach (ListItem li in CheckBoxList1.Items)
{
li.Selected = false;
}
}
Asp.net ListBox
control - Part 25
Suggested Videos
Part 22 - Cascading dropdown asp.net
Part 23 - Asp.net checkboxlist control
Part 24 - Asp.net checkboxlist, select or deselect all list items
In this video we will discuss about ListBox control. Just like DropDownList and CheckBoxList, ListBox control is also a collection of ListItem objects. Working with ListBox control is very similar to DropDownList and CheckBoxList. Adding items and binding to a datasource is exactly similar. In this part of the video, let's discuss about the properties that are specific to the ListBox control.
Properties
Rows : The number of visible rows in the Listbox. A scrollbar is automatically generated, if the total number of item are greater than the number of visible rows in the listbox.
SelectionMode : SelectionMode can be Single or Multimple. By default, this property value is Single, meaning when the listbox renders, the user can select only one item from the listbox. Set this property to Multimple, to enable multiple item selections. To select, multiple items from the listbox, hold-down the CTRL key, while the listitem's are selected.
Please note that, it is not possible to set the Selected property of more than one ListItem object to true, if the SelectionMode of the listbox is to Single.
Retrieving the selected item's Text, Value and Index is similar to DropDownList and CheckBoxList
ASPX Page code:
<asp:ListBox ID="ListBox1" runat="server" SelectionMode="Multiple">
<asp:ListItem Text="Diploma" Value="1"></asp:ListItem>
<asp:ListItem Text="Graduate" Value="2"></asp:ListItem>
<asp:ListItem Text="Post Graduate" Value="3"></asp:ListItem>
<asp:ListItem Text="Doctrate" Value="4"></asp:ListItem>
</asp:ListBox>
<br />
<br />
<asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Button" />
Code Behind Code:
protected void Button1_Click(object sender, EventArgs e)
{
foreach (ListItem li in ListBox1.Items)
{
if (li.Selected)
{
Response.Write("Text = " + li.Text + ", ");
Response.Write("Value = " + li.Value + ", ");
Response.Write("Index = " + ListBox1.Items.IndexOf(li).ToString());
Response.Write("<br/>");
}
}
}
ASP.NET ListBox Example:

Part 22 - Cascading dropdown asp.net
Part 23 - Asp.net checkboxlist control
Part 24 - Asp.net checkboxlist, select or deselect all list items
In this video we will discuss about ListBox control. Just like DropDownList and CheckBoxList, ListBox control is also a collection of ListItem objects. Working with ListBox control is very similar to DropDownList and CheckBoxList. Adding items and binding to a datasource is exactly similar. In this part of the video, let's discuss about the properties that are specific to the ListBox control.
Properties
Rows : The number of visible rows in the Listbox. A scrollbar is automatically generated, if the total number of item are greater than the number of visible rows in the listbox.
SelectionMode : SelectionMode can be Single or Multimple. By default, this property value is Single, meaning when the listbox renders, the user can select only one item from the listbox. Set this property to Multimple, to enable multiple item selections. To select, multiple items from the listbox, hold-down the CTRL key, while the listitem's are selected.
Please note that, it is not possible to set the Selected property of more than one ListItem object to true, if the SelectionMode of the listbox is to Single.
Retrieving the selected item's Text, Value and Index is similar to DropDownList and CheckBoxList
ASPX Page code:
<asp:ListBox ID="ListBox1" runat="server" SelectionMode="Multiple">
<asp:ListItem Text="Diploma" Value="1"></asp:ListItem>
<asp:ListItem Text="Graduate" Value="2"></asp:ListItem>
<asp:ListItem Text="Post Graduate" Value="3"></asp:ListItem>
<asp:ListItem Text="Doctrate" Value="4"></asp:ListItem>
</asp:ListBox>
<br />
<br />
<asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Button" />
Code Behind Code:
protected void Button1_Click(object sender, EventArgs e)
{
foreach (ListItem li in ListBox1.Items)
{
if (li.Selected)
{
Response.Write("Text = " + li.Text + ", ");
Response.Write("Value = " + li.Value + ", ");
Response.Write("Index = " + ListBox1.Items.IndexOf(li).ToString());
Response.Write("<br/>");
}
}
}
ASP.NET ListBox Example:

Suggested Videos
Part 23 - Asp.net checkboxlist control
Part 24 - Asp.net checkboxlist, select or deselect all list items
Part 25 - ASP.NET ListBox control
In this video we will discuss about a simple real time example using asp.net checkboxlist and listbox.
Copy and Paste the following HTML on the ASPX page
<asp:CheckBoxList ID="CheckBoxList1" runat="server"
RepeatDirection="Horizontal" AutoPostBack="True"
onselectedindexchanged="CheckBoxList1_SelectedIndexChanged">
<asp:ListItem Text="Diploma" Value="1"></asp:ListItem>
<asp:ListItem Text="Graduate" Value="2"></asp:ListItem>
<asp:ListItem Text="Post Graduate" Value="3"></asp:ListItem>
<asp:ListItem Text="Doctrate" Value="4"></asp:ListItem>
</asp:CheckBoxList>
<br />
<asp:ListBox ID="ListBox1" runat="server" Height="78px" Width="127px">
</asp:ListBox>
<br /><br />
<asp:Label ID="lblMessage" runat="server" Font-Bold="true"></asp:Label>
Copy and Paste the following code in the code behind page
protected void CheckBoxList1_SelectedIndexChanged(object sender, EventArgs e)
{
// Everytime the selection changes, clear the items in the listbox
ListBox1.Items.Clear();
// Loop thru each litemitem in the checkboxlist
foreach (ListItem li in CheckBoxList1.Items)
{
// If the listitem is selected
if (li.Selected)
{
// Add the listitem text to the listbox
ListBox1.Items.Add(li.Text);
// Add the lisitem as an object. This ensures the listitem is
// selected in the listbox. For this to work, listbox,
// SelectionMode must be set to Multiple. The SelectionMode
// Property can be set in the HTML source also.
// ListBox1.SelectionMode = ListSelectionMode.Multiple
// ListBox1.Items.Add(li);
}
}
// If nothing is selected from the checkboxlist
if (CheckBoxList1.SelectedIndex == -1)
{
// Set the label ForeColor to Red
lblMessage.ForeColor = System.Drawing.Color.Red;
}
// If atleast one listitem is selected
else
{
// Set the label forecolor to black
lblMessage.ForeColor = System.Drawing.Color.Black;
}
// Display the total number of items selected from the checkboxlist
lblMessage.Text = ListBox1.Items.Count.ToString() + " item(s) selected";
}
Part 23 - Asp.net checkboxlist control
Part 24 - Asp.net checkboxlist, select or deselect all list items
Part 25 - ASP.NET ListBox control
In this video we will discuss about a simple real time example using asp.net checkboxlist and listbox.
Copy and Paste the following HTML on the ASPX page
<asp:CheckBoxList ID="CheckBoxList1" runat="server"
RepeatDirection="Horizontal" AutoPostBack="True"
onselectedindexchanged="CheckBoxList1_SelectedIndexChanged">
<asp:ListItem Text="Diploma" Value="1"></asp:ListItem>
<asp:ListItem Text="Graduate" Value="2"></asp:ListItem>
<asp:ListItem Text="Post Graduate" Value="3"></asp:ListItem>
<asp:ListItem Text="Doctrate" Value="4"></asp:ListItem>
</asp:CheckBoxList>
<br />
<asp:ListBox ID="ListBox1" runat="server" Height="78px" Width="127px">
</asp:ListBox>
<br /><br />
<asp:Label ID="lblMessage" runat="server" Font-Bold="true"></asp:Label>
Copy and Paste the following code in the code behind page
protected void CheckBoxList1_SelectedIndexChanged(object sender, EventArgs e)
{
// Everytime the selection changes, clear the items in the listbox
ListBox1.Items.Clear();
// Loop thru each litemitem in the checkboxlist
foreach (ListItem li in CheckBoxList1.Items)
{
// If the listitem is selected
if (li.Selected)
{
// Add the listitem text to the listbox
ListBox1.Items.Add(li.Text);
// Add the lisitem as an object. This ensures the listitem is
// selected in the listbox. For this to work, listbox,
// SelectionMode must be set to Multiple. The SelectionMode
// Property can be set in the HTML source also.
// ListBox1.SelectionMode = ListSelectionMode.Multiple
// ListBox1.Items.Add(li);
}
}
// If nothing is selected from the checkboxlist
if (CheckBoxList1.SelectedIndex == -1)
{
// Set the label ForeColor to Red
lblMessage.ForeColor = System.Drawing.Color.Red;
}
// If atleast one listitem is selected
else
{
// Set the label forecolor to black
lblMessage.ForeColor = System.Drawing.Color.Black;
}
// Display the total number of items selected from the checkboxlist
lblMessage.Text = ListBox1.Items.Count.ToString() + " item(s) selected";
}
ASP.NET
RadioButtonList Control - Part 27
Suggested Videos
Part 24 - ASP.NET CheckBoxList, select or deselect all list items
Part 25 - ASP.NET ListBox control
Part 26 - ASP.NET CheckBoxList and ListBox real time example
In ASP.NET there are several list controls, like
1. DropDownList
2. CheckBoxList
3. BulletedList
4. ListBox
5. RadioButtonList
In this video we will learn about asp.net RadioButtonList control. Just like every other list control
1. RadioButtonList is also a collection of ListItem objects.
2. Items can be added to the RadioButtonList in the HTML source or in the code behind file
3. RadioButtonList like any other list control supports databinding. For example, RadioButtonList can be bound to a database table or an xml file
CheckBoxList is generally used, when you want to present the user with multiple choices, from which you want him to select one or more options. Where as if you want the user to select only one option, then a RadioButtonList control can be used, i.e RadioButtonList is commonly used to present mutually exclusive choices.
Create an asp.net web application. Copy and paste the following HTML
<asp:RadioButtonList ID="ColorRadioButtonList" runat="server"
RepeatDirection="Horizontal">
<asp:ListItem Text="Red" Value="1"></asp:ListItem>
<asp:ListItem Text="Green" Value="2"></asp:ListItem>
<asp:ListItem Text="Blue" Value="3"></asp:ListItem>
<asp:ListItem Text="Orange" Value="4"></asp:ListItem>
</asp:RadioButtonList>
<br />
<asp:Button ID="btnSubmit" runat="server" Text="Submit"
onclick="btnSubmit_Click"/>
<asp:Button ID="btnClearSelection" runat="server" Text="Clear Selection"
onclick="btnClearSelection_Click"/>
Copy and paste the following code in your code-behind page
protected void btnSubmit_Click(object sender, EventArgs e)
{
// If the user has made a choice
if (ColorRadioButtonList.SelectedIndex != -1)
{
Response.Write("Text = " + ColorRadioButtonList.SelectedItem.Text + "<br/>");
Response.Write("Value = " + ColorRadioButtonList.SelectedItem.Value + "<br/>");
Response.Write("Index = " + ColorRadioButtonList.SelectedIndex.ToString());
}
// If the user has not selected anything
else
{
Response.Write("Please select your favourite color");
}
}
protected void btnClearSelection_Click(object sender, EventArgs e)
{
// Clear the user selection
ColorRadioButtonList.SelectedIndex = -1;
}
RadioButtonList Example

By default, the ListItem objects are laid out in vertical direction. If you want to change the direction, use RepeatDirection property
<asp:RadioButtonList ID="ColorRadioButtonList" runat="server" RepeatDirection="Horizontal">
RepeatColumns property specifies the number of columns used to lay out the items.
RepeatLayout property, specifies the layout to be used by each list item. The following are the values allowed by RepeatLayout property
1. Table
2. Flow
3. OrderedList
4. UnorderedList
Please note that the, OrderedList and UnorderedList layouts are only supported, if the RepeatDirection is vertical.
Set the Enabled property of the ListItem object to false, to disable the selection, in the RadioButtonList control.
To retrieve the Text of the selected item, SelectedItem.Text property can be used. SelectedItem will be NULL, if nothing is selected, and hence, calling Text and Value properties may cause NullReferenceException. Hence, it is important to check for null, when using SelectedItem property of a RadioButtonList control.
if (ColorRadioButtonList.SelectedItem != null)
{
Response.Write(ColorRadioButtonList.SelectedItem.Text);
}
NullReferenceException can also be avoided, using the SelectedIndex property
if (ColorRadioButtonList.SelectedIndex != -1)
{
Response.Write(ColorRadioButtonList.SelectedItem.Text);
}
Part 24 - ASP.NET CheckBoxList, select or deselect all list items
Part 25 - ASP.NET ListBox control
Part 26 - ASP.NET CheckBoxList and ListBox real time example
In ASP.NET there are several list controls, like
1. DropDownList
2. CheckBoxList
3. BulletedList
4. ListBox
5. RadioButtonList
In this video we will learn about asp.net RadioButtonList control. Just like every other list control
1. RadioButtonList is also a collection of ListItem objects.
2. Items can be added to the RadioButtonList in the HTML source or in the code behind file
3. RadioButtonList like any other list control supports databinding. For example, RadioButtonList can be bound to a database table or an xml file
CheckBoxList is generally used, when you want to present the user with multiple choices, from which you want him to select one or more options. Where as if you want the user to select only one option, then a RadioButtonList control can be used, i.e RadioButtonList is commonly used to present mutually exclusive choices.
Create an asp.net web application. Copy and paste the following HTML
<asp:RadioButtonList ID="ColorRadioButtonList" runat="server"
RepeatDirection="Horizontal">
<asp:ListItem Text="Red" Value="1"></asp:ListItem>
<asp:ListItem Text="Green" Value="2"></asp:ListItem>
<asp:ListItem Text="Blue" Value="3"></asp:ListItem>
<asp:ListItem Text="Orange" Value="4"></asp:ListItem>
</asp:RadioButtonList>
<br />
<asp:Button ID="btnSubmit" runat="server" Text="Submit"
onclick="btnSubmit_Click"/>
<asp:Button ID="btnClearSelection" runat="server" Text="Clear Selection"
onclick="btnClearSelection_Click"/>
Copy and paste the following code in your code-behind page
protected void btnSubmit_Click(object sender, EventArgs e)
{
// If the user has made a choice
if (ColorRadioButtonList.SelectedIndex != -1)
{
Response.Write("Text = " + ColorRadioButtonList.SelectedItem.Text + "<br/>");
Response.Write("Value = " + ColorRadioButtonList.SelectedItem.Value + "<br/>");
Response.Write("Index = " + ColorRadioButtonList.SelectedIndex.ToString());
}
// If the user has not selected anything
else
{
Response.Write("Please select your favourite color");
}
}
protected void btnClearSelection_Click(object sender, EventArgs e)
{
// Clear the user selection
ColorRadioButtonList.SelectedIndex = -1;
}
RadioButtonList Example

By default, the ListItem objects are laid out in vertical direction. If you want to change the direction, use RepeatDirection property
<asp:RadioButtonList ID="ColorRadioButtonList" runat="server" RepeatDirection="Horizontal">
RepeatColumns property specifies the number of columns used to lay out the items.
RepeatLayout property, specifies the layout to be used by each list item. The following are the values allowed by RepeatLayout property
1. Table
2. Flow
3. OrderedList
4. UnorderedList
Please note that the, OrderedList and UnorderedList layouts are only supported, if the RepeatDirection is vertical.
Set the Enabled property of the ListItem object to false, to disable the selection, in the RadioButtonList control.
To retrieve the Text of the selected item, SelectedItem.Text property can be used. SelectedItem will be NULL, if nothing is selected, and hence, calling Text and Value properties may cause NullReferenceException. Hence, it is important to check for null, when using SelectedItem property of a RadioButtonList control.
if (ColorRadioButtonList.SelectedItem != null)
{
Response.Write(ColorRadioButtonList.SelectedItem.Text);
}
NullReferenceException can also be avoided, using the SelectedIndex property
if (ColorRadioButtonList.SelectedIndex != -1)
{
Response.Write(ColorRadioButtonList.SelectedItem.Text);
}
Bulleted list in
asp.net - Part 28
Suggested Videos
Part 25 - ASP.NET ListBox control
Part 26 - ASP.NET CheckBoxList and ListBox real time example
Part 27 - ASP.NET RadioButtonList control
In this video we will discuss about BulletedList in asp.net.
In ASP.NET there are several list controls, like
1. DropDownList
2. CheckBoxList
3. RadioButtonList
4. ListBox
5. BulletedList
Just like every other list control
1. BulletedList is also a collection of ListItem objects.
2. Items can be added to the BulletedList in the HTML source or in the code behind file
3. BulletedList like any other list control supports databinding. For example, BulletedList can be bound to a database table or an xml file
Properties of BulletedList
BulletStyle - This property, is used to customize the bullets style. If CustomImage is specified as the BulletStyle, then BulletImageURL, also needs to be specified.
<asp:BulletedList ID="CountriesBulletedList" runat="server" BulletStyle="Numbered">
<asp:ListItem Text="India" Value="1"></asp:ListItem>
<asp:ListItem Text="US" Value="2"></asp:ListItem>
<asp:ListItem Text="UK" Value="3"></asp:ListItem>
<asp:ListItem Text="France" Value="4"></asp:ListItem>
</asp:BulletedList>
FirstBulletNumber - The Number at which the ordered list starts.
DisplayMode - Can be Text, HyperLink or LinkButton. The default is Text.
The following HTML, sets the DisplayMode="HyperLink". By default, the target page is displayed in the same browser window. Set the Target property of the BulletedList to _blank, to open the target page in it's own window.
<asp:BulletedList ID="CountriesBulletedList" runat="server"
BulletStyle="Numbered" DisplayMode="HyperLink">
<asp:ListItem Text="Google" Value="http://google.com"></asp:ListItem>
<asp:ListItem Text="Youtube" Value="http://Youtube.com"></asp:ListItem>
<asp:ListItem Text="Blogger" Value="http://Blooger.com"></asp:ListItem>
<asp:ListItem Text="Gmail" Value="http://Gmail.com"></asp:ListItem>
</asp:BulletedList>
The following HTML, sets DisplayMode="LinkButton" and onclick="CountriesBulletedList_Click"
<asp:BulletedList ID="CountriesBulletedList" runat="server"
DisplayMode="LinkButton" onclick="CountriesBulletedList_Click">
<asp:ListItem Text="Google" Value="1"></asp:ListItem>
<asp:ListItem Text="Microsoft" Value="2"></asp:ListItem>
<asp:ListItem Text="Dell" Value="3"></asp:ListItem>
<asp:ListItem Text="IBM" Value="4"></asp:ListItem>
</asp:BulletedList>
Code behind code
protected void CountriesBulletedList_Click(object sender, BulletedListEventArgs e)
{
ListItem li = CountriesBulletedList.Items[e.Index];
Response.Write("Text = " + li.Text + "<br/>");
Response.Write("Value = " + li.Value + "<br/>");
Response.Write("Index = " + e.Index.ToString());
}
Part 25 - ASP.NET ListBox control
Part 26 - ASP.NET CheckBoxList and ListBox real time example
Part 27 - ASP.NET RadioButtonList control
In this video we will discuss about BulletedList in asp.net.
In ASP.NET there are several list controls, like
1. DropDownList
2. CheckBoxList
3. RadioButtonList
4. ListBox
5. BulletedList
Just like every other list control
1. BulletedList is also a collection of ListItem objects.
2. Items can be added to the BulletedList in the HTML source or in the code behind file
3. BulletedList like any other list control supports databinding. For example, BulletedList can be bound to a database table or an xml file
Properties of BulletedList
BulletStyle - This property, is used to customize the bullets style. If CustomImage is specified as the BulletStyle, then BulletImageURL, also needs to be specified.
<asp:BulletedList ID="CountriesBulletedList" runat="server" BulletStyle="Numbered">
<asp:ListItem Text="India" Value="1"></asp:ListItem>
<asp:ListItem Text="US" Value="2"></asp:ListItem>
<asp:ListItem Text="UK" Value="3"></asp:ListItem>
<asp:ListItem Text="France" Value="4"></asp:ListItem>
</asp:BulletedList>
FirstBulletNumber - The Number at which the ordered list starts.
DisplayMode - Can be Text, HyperLink or LinkButton. The default is Text.
The following HTML, sets the DisplayMode="HyperLink". By default, the target page is displayed in the same browser window. Set the Target property of the BulletedList to _blank, to open the target page in it's own window.
<asp:BulletedList ID="CountriesBulletedList" runat="server"
BulletStyle="Numbered" DisplayMode="HyperLink">
<asp:ListItem Text="Google" Value="http://google.com"></asp:ListItem>
<asp:ListItem Text="Youtube" Value="http://Youtube.com"></asp:ListItem>
<asp:ListItem Text="Blogger" Value="http://Blooger.com"></asp:ListItem>
<asp:ListItem Text="Gmail" Value="http://Gmail.com"></asp:ListItem>
</asp:BulletedList>
The following HTML, sets DisplayMode="LinkButton" and onclick="CountriesBulletedList_Click"
<asp:BulletedList ID="CountriesBulletedList" runat="server"
DisplayMode="LinkButton" onclick="CountriesBulletedList_Click">
<asp:ListItem Text="Google" Value="1"></asp:ListItem>
<asp:ListItem Text="Microsoft" Value="2"></asp:ListItem>
<asp:ListItem Text="Dell" Value="3"></asp:ListItem>
<asp:ListItem Text="IBM" Value="4"></asp:ListItem>
</asp:BulletedList>
Code behind code
protected void CountriesBulletedList_Click(object sender, BulletedListEventArgs e)
{
ListItem li = CountriesBulletedList.Items[e.Index];
Response.Write("Text = " + li.Text + "<br/>");
Response.Write("Value = " + li.Value + "<br/>");
Response.Write("Index = " + e.Index.ToString());
}
Suggested Videos
Part 26 - ASP.NET CheckBoxList and ListBox real time example
Part 27 - ASP.NET RadioButtonList control
Part 28 - Bulleted list in asp.net
In ASP.NET there are several list controls, like
1. DropDownList
2. CheckBoxList
3. RadioButtonList
4. ListBox
5. BulletedList
All these controls are
1. Collection of ListItem objects
2. ListItems can be added in the HTML source or in the code behind file
3. Supports Databinding
The only difference here is the tag name, otherwise adding ListItems is very identical.
<asp:DropDownList ID="DropDownList1" runat="server">
<asp:ListItem Text="Item1" Value="1"></asp:ListItem>
<asp:ListItem Text="Item2" Value="2"></asp:ListItem>
<asp:ListItem Text="Item3" Value="3"></asp:ListItem>
</asp:DropDownList>
<br />
<asp:CheckBoxList ID="CheckBoxList1" runat="server">
<asp:ListItem Text="Item1" Value="1"></asp:ListItem>
<asp:ListItem Text="Item2" Value="2"></asp:ListItem>
<asp:ListItem Text="Item3" Value="3"></asp:ListItem>
</asp:CheckBoxList>
<br />
<asp:RadioButtonList ID="RadioButtonList1" runat="server">
<asp:ListItem Text="Item1" Value="1"></asp:ListItem>
<asp:ListItem Text="Item2" Value="2"></asp:ListItem>
<asp:ListItem Text="Item3" Value="3"></asp:ListItem>
</asp:RadioButtonList>
<br />
<asp:ListBox ID="ListBox1" runat="server">
<asp:ListItem Text="Item1" Value="1"></asp:ListItem>
<asp:ListItem Text="Item2" Value="2"></asp:ListItem>
<asp:ListItem Text="Item3" Value="3"></asp:ListItem>
</asp:ListBox>
<br />
<asp:BulletedList ID="BulletedList1" runat="server">
<asp:ListItem Text="Item1" Value="1"></asp:ListItem>
<asp:ListItem Text="Item2" Value="2"></asp:ListItem>
<asp:ListItem Text="Item3" Value="3"></asp:ListItem>
</asp:BulletedList>
Adding ListItems using code. Since all the list controls inherit from ListControl class, AddListItems() method can be used to add listitems to any list control. A parent class reference variable can point to a derived class object.
This fact allows us to pass any list control into the AddListItems() method as a parameter. We have discussed about inheritance in Part 21 and polymorphism in Part 23 of C# Video Tutorial Series.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
AddListItems(DropDownList1);
AddListItems(CheckBoxList1);
AddListItems(RadioButtonList1);
AddListItems(ListBox1);
AddListItems(BulletedList1);
}
}
private void AddListItems(ListControl listControl)
{
ListItem li1 = new ListItem("Item1", "1");
ListItem li2 = new ListItem("Item2", "2");
ListItem li3 = new ListItem("Item3", "3");
listControl.Items.Add(li1);
listControl.Items.Add(li2);
listControl.Items.Add(li3);
}
ListBox (If SelectionMode=Multiple) and CheckBoxList allows user to select multiple items. So, to retrieve all the selected listitem's Text, Value and Index use a foreach loop.
Reusable method that can be used with any control that derives from ListControl class, but works best with controls that allows multiple selections.
private void RetrieveMultipleSelections(ListControl listControl)
{
foreach (ListItem li in listControl.Items)
{
if (li.Selected)
{
Response.Write("Text = " + li.Text + ", Value = " + li.Value +
", Index = " + listControl.Items.IndexOf(li).ToString() + "<br/>");
}
}
}
ListBox (If SelectionMode=Single), RadioButtonList and DropDownList allows user to select only one item. So, use SelectedIndex and SelectedItem properties to retrieve the Text, Value and Index of the selected listitem.
Reusable method that can be used with any control that derives from ListControl class, but works best with controls that allows single selection.
private void RetrieveSelectedItemTextValueandIndex(ListControl listControl)
{
if (listControl.SelectedIndex != -1)
{
Response.Write("Text = " + listControl.SelectedItem.Text + "<br/>");
Response.Write("Value = " + listControl.SelectedItem.Value + "<br/>");
Response.Write("Index = " + listControl.SelectedIndex.ToString());
}
}
BulletedList(If DisplayMode=LinkButton) - In the click event handler, use the BulletedListEventArgs parameter object to retrieve the Text, Value and Index of the listitem, the user has clicked.
protected void BulletedList1_Click(object sender, BulletedListEventArgs e)
{
ListItem li = BulletedList1.Items[e.Index];
Response.Write("Text = " + li.Text + "<br/>");
Response.Write("Value = " + li.Value + "<br/>");
Response.Write("Index = " + e.Index.ToString());
}
Part 26 - ASP.NET CheckBoxList and ListBox real time example
Part 27 - ASP.NET RadioButtonList control
Part 28 - Bulleted list in asp.net
In ASP.NET there are several list controls, like
1. DropDownList
2. CheckBoxList
3. RadioButtonList
4. ListBox
5. BulletedList
All these controls are
1. Collection of ListItem objects
2. ListItems can be added in the HTML source or in the code behind file
3. Supports Databinding
The only difference here is the tag name, otherwise adding ListItems is very identical.
<asp:DropDownList ID="DropDownList1" runat="server">
<asp:ListItem Text="Item1" Value="1"></asp:ListItem>
<asp:ListItem Text="Item2" Value="2"></asp:ListItem>
<asp:ListItem Text="Item3" Value="3"></asp:ListItem>
</asp:DropDownList>
<br />
<asp:CheckBoxList ID="CheckBoxList1" runat="server">
<asp:ListItem Text="Item1" Value="1"></asp:ListItem>
<asp:ListItem Text="Item2" Value="2"></asp:ListItem>
<asp:ListItem Text="Item3" Value="3"></asp:ListItem>
</asp:CheckBoxList>
<br />
<asp:RadioButtonList ID="RadioButtonList1" runat="server">
<asp:ListItem Text="Item1" Value="1"></asp:ListItem>
<asp:ListItem Text="Item2" Value="2"></asp:ListItem>
<asp:ListItem Text="Item3" Value="3"></asp:ListItem>
</asp:RadioButtonList>
<br />
<asp:ListBox ID="ListBox1" runat="server">
<asp:ListItem Text="Item1" Value="1"></asp:ListItem>
<asp:ListItem Text="Item2" Value="2"></asp:ListItem>
<asp:ListItem Text="Item3" Value="3"></asp:ListItem>
</asp:ListBox>
<br />
<asp:BulletedList ID="BulletedList1" runat="server">
<asp:ListItem Text="Item1" Value="1"></asp:ListItem>
<asp:ListItem Text="Item2" Value="2"></asp:ListItem>
<asp:ListItem Text="Item3" Value="3"></asp:ListItem>
</asp:BulletedList>
Adding ListItems using code. Since all the list controls inherit from ListControl class, AddListItems() method can be used to add listitems to any list control. A parent class reference variable can point to a derived class object.
This fact allows us to pass any list control into the AddListItems() method as a parameter. We have discussed about inheritance in Part 21 and polymorphism in Part 23 of C# Video Tutorial Series.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
AddListItems(DropDownList1);
AddListItems(CheckBoxList1);
AddListItems(RadioButtonList1);
AddListItems(ListBox1);
AddListItems(BulletedList1);
}
}
private void AddListItems(ListControl listControl)
{
ListItem li1 = new ListItem("Item1", "1");
ListItem li2 = new ListItem("Item2", "2");
ListItem li3 = new ListItem("Item3", "3");
listControl.Items.Add(li1);
listControl.Items.Add(li2);
listControl.Items.Add(li3);
}
ListBox (If SelectionMode=Multiple) and CheckBoxList allows user to select multiple items. So, to retrieve all the selected listitem's Text, Value and Index use a foreach loop.
Reusable method that can be used with any control that derives from ListControl class, but works best with controls that allows multiple selections.
private void RetrieveMultipleSelections(ListControl listControl)
{
foreach (ListItem li in listControl.Items)
{
if (li.Selected)
{
Response.Write("Text = " + li.Text + ", Value = " + li.Value +
", Index = " + listControl.Items.IndexOf(li).ToString() + "<br/>");
}
}
}
ListBox (If SelectionMode=Single), RadioButtonList and DropDownList allows user to select only one item. So, use SelectedIndex and SelectedItem properties to retrieve the Text, Value and Index of the selected listitem.
Reusable method that can be used with any control that derives from ListControl class, but works best with controls that allows single selection.
private void RetrieveSelectedItemTextValueandIndex(ListControl listControl)
{
if (listControl.SelectedIndex != -1)
{
Response.Write("Text = " + listControl.SelectedItem.Text + "<br/>");
Response.Write("Value = " + listControl.SelectedItem.Value + "<br/>");
Response.Write("Index = " + listControl.SelectedIndex.ToString());
}
}
BulletedList(If DisplayMode=LinkButton) - In the click event handler, use the BulletedListEventArgs parameter object to retrieve the Text, Value and Index of the listitem, the user has clicked.
protected void BulletedList1_Click(object sender, BulletedListEventArgs e)
{
ListItem li = BulletedList1.Items[e.Index];
Response.Write("Text = " + li.Text + "<br/>");
Response.Write("Value = " + li.Value + "<br/>");
Response.Write("Index = " + e.Index.ToString());
}
Fileupload control in
asp.net - Part 30
Suggested VideosPart 19 - Mapping virtual path to physical path using Server.MapPath method
Part 20 - Mapping virtual path to physical path using Server.MapPath method Example
In this video we will discuss about fileupload control. FileUpload control is a combination of a text box and a browse button that enable users to select a file to upload to the server.
Create an asp.net web application project. Drag and drop the FileUpload control on the webform.
The fileUpload control only allows the user to select the file. To upload the seleceted file, drag and drop a button control. Change the ID of the button to btnUpload and the Text to Upload File. Also drag and drop a label control, and change the ID of the label to lblMessage. At this stage the HTML of the webform should be as shown below.
<asp:FileUpload ID="FileUpload1" runat="server" />
<asp:Button ID="btnUpload" runat="server" Text="Upload File"
onclick="btnUpload_Click" />
<br />
<asp:Label ID="lblMessage" Font-Bold="true" runat="server">
</asp:Label>
Right click on the web application project and add a folder with name Uploads. This folder is going to store all the uploaded files.
Copy and paste the following code in btnUpload_Click() event handler
// If the user has selected a file
if (FileUpload1.HasFile)
{
// Get the file extension
string fileExtension = System.IO.Path.GetExtension(FileUpload1.FileName);
if (fileExtension.ToLower() != ".doc" && fileExtension.ToUpper() != ".docx")
{
lblMessage.ForeColor = System.Drawing.Color.Red;
lblMessage.Text = "Only files with .doc and .docx extension are allowed";
}
else
{
// Get the file size
int fileSize = FileUpload1.PostedFile.ContentLength;
// If file size is greater than 2 MB
if (fileSize > 2097152)
{
lblMessage.ForeColor = System.Drawing.Color.Red;
lblMessage.Text = "File size cannot be greater than 2 MB";
}
else
{
// Upload the file
FileUpload1.SaveAs(Server.MapPath("~/Uploads/" + FileUpload1.FileName));
lblMessage.ForeColor = System.Drawing.Color.Green;
lblMessage.Text = "File uploaded successfully";
}
}
}
else
{
lblMessage.ForeColor = System.Drawing.Color.Red;
lblMessage.Text = "Please select a file";
}
No comments:
Post a Comment