You are on page 1of 351

ASP.

net Basic Tutorials with Examples

1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14. 15. 16. 17. 18. 19. 20. 21. 22. 23. 24. 25. 26. 27. 28. 29. 30. 31. 32. 33. 34. 35. 36. 37. 38. 39. 40. 41. 42. 43. 44. 45. 46. 47.

Introduction of ASP.NET Architecture of ASP.NET Life Cycle of Web pages And Types Of Control in Asp.net Various Type of Application in Asp.net and Partial Class State Management in Asp.net And how to Implement Viewstate Cookies in Asp.net How to Implement Query String in Asp.net Server Side State Management Master Page In Asp.net Introduction Of Gridview Control Simple Databind In Gridview Control Simple Code For Edit Update And Delete In Gridview All Gridview Code In Asp.net Validation Control in Asp.net RequiredFieldvalidator in Asp.net RegularExpressionValidator control in Asp.net CustomValidator control in Asp.net Summary Validation Control in Asp.net Label Control TextBox Control Button Control ImageButton Control hyperlink literal LinkButton Control DropDownList Control How to Bind Data in DropDownList Control Listbox Control Checkbox Control CheckBoxList Control RadioButton Control RadioButtonList Control Image Control ImageMap Control Calender Control FileUpload Control Wizard Control DataList Control DetailView Control FormView Control ListView Control Repeater Control Pager Control Navigation Control Login Control How To Make UserControl in ASP.NET How to Encypt Data and Decrypt Data In ASP.NET

48. 49. 50. 51. 52. 53. 54. 55. 56. 57. 58. 59. 60. 61. 62. 63. 64. 65. 66. 67. 68. 69. 70. 71. 72. 73. 74. 75. 76. 77. 78. 79. 80. 81. 82. 83. 84. 85. 86. 87. 88. 89.
field:

Create Connection To Excel Data Add Flash file in Website in ASP.NET How to rotate image in asp.net How to download any file in asp.net How To get the values of selected How to insert picture in excel How to make setup of web application How to save image in database How to send email using asp.net Machine confiq in asp.net Reflection in asp.net Save File In project Folder Searching document from website in ASP.NET Selected country from drop down list Skin style and theme in asp.net Socket programming in asp Tracing in asp Upload Multiple Images On WEB Page What is virtual directory How to Add Manually CheckBox in C# using Asp.net How to Add StyleSheet in TextBox using ASP.NET How to Create Multi Language Web-Site in ASP.NET How to show Alert and Confirmation Message Box in ASP.NET How to write Gridview data to XML file in .NET How to get Line Count of a File using StreamReader in C# How to Calculate Textbox value Using JavaScript in ASP.NET How to create Dynamic textbox in asp.net How to convert text in TextBox to image with C# Language How to populate combobox from xml file using c# How to Get Particular Value From XML file in ASP.NET using C# Login Page IN ASP .NET Using C# How to Upload the Image in ASP .NET using C# Creating Directory or Folder using ASP.NET in C# Set style for label in ASPNET Using C# Change style for ListItem in ASP.NET How to change page theme dynamically at runtime in asp.net Important properties of ValidationSummary control Use Validation Summary to display message Box (C#) ValidationSummary DisplayMode=BulletList RequiredFieldValidatorSummary Display Mode CompareValidator performs a comparison against a fixed value: CompareValidator compares the value of one form field against another form

90. Using the CompareValidator to test values against other control values: 91. CompareValidator for number, text and password: 92. CompareValidator with age field:
93. How to Validate URL using Regular Expression: 94. How to validate name Using Regular Expression: 95. How to use Validation Group in ASP.NET: 96. Group based validation (C#):

97. How to Validate Form using Server Side Validation in ASp.NET|: 98. How to Enter only Ten Character in Textbox Using Custom validation: 99. How to Create a Login Page Using Form Authentication : 100. How to Use Logout Method Using Authentication: 101. Count Number of Visitors in WebSite using ASP.Net and C#: 102. Writing XML File using XmlWriter in ASP.NET: 103. A Simple DropDownList of links in ASP.NET Using C#: 104. Bind all column names in one Dropdownlist in ASP.NET using c#: 105. Bind an ASP.NET DropDownList to a Dictionary : 106. Convert Time in Different TimeZones in ASP.NET using C#: 107. Export gridview to pdf in asp.net using c#: 108. How to Add Image in PDf ASP.NET using C#: 109. How to Find String in RichtextBox: 110. How to Fill Ellipse with Brush in ASP.NET Using C#: 111. How to create custom error reporting pages in ASP.NET by using C# 112. How Dynamically Add Rows into ASP.NET Table using C# : 113. Adding Facebook Share Functionality to an ASP.NET Website: 114. How to make CountDown Timer in ASP.NET Using C#: 115. How to refresh an ASP.NET GridView automatically at regular Intervals: 116. Calculate Firstdate And Lastdate of Month in ASP.NET Using C# 117. How to get the list of ADO.NET data providers registered in the machine and
application configuration file 118. How To Create a Directory using C# in ASP .NET 119. How to Use Validation Summary in ASP .NET using C# 120. How to Load XML to DataSet in ASP.Net using C# 121. How to DataSet Merge in ASP.NET using C# 122. How to create an application domain in ASP .NET using C# 123. Updating Data Using Transactions in ASP .Net using C# 124. How to Read Bitmap from database in ASP .NET 125. How to Create DataViews from DataTable in ASP .NET using C# 126. Show in a Message Box using Validation Summary 127. Use HtmlHead control to set the page title and meta tags 128. How to specify the Session timeout in the web configuration file 129. How to call Page.Validate to validate groups 130. How to remapping URLs in your application's web configuration file 131. How to get the URL of Page (RawUrl) 132. How to Know the Type and Version of Browser 133. How to Bind a Array List to a RadioButtonList in ASP .Net Using C# 134. How to Bind a ArrayList to DropDownList in ASP.Net 135. HTML Control in ASP .NET 136. Input (Button) Control 137. Input (Reset) Control 138. Input (Submit) Control 139. Input (Text) Control 140. Input (File) Control 141. Input (Password) Control 142. Input (Check Box) Control 143. Input (Radio Button) Control 144. Input (Hidden) Control 145. Textarea Control

146. Table Control 147. Select Control 148. Image Control

Introduction of ASP.NET
ASP.NET is the next generation ASP, but it's not an upgraded version of ASP. ASP.NET is an entirely new technology for server-side scripting. ASP.NET is a part of the Microsoft .NET framework, and a powerful tool for creating dynamic and interactive web pages. ASP.NET is a server side scripting technology that enables scripts (embedded in web pages) to be executed by an Internet server ASP.NET is a Microsoft Technology. ASP stands for Active Server Pages ASP.NET is a program that runs inside IIS. IIS (Internet Information Services) is Microsoft's Internet server. IIS comes as a free component with Windows servers. IIS is also a part of Windows 2000 and XP Professional.

ASP.NET File
An ASP.NET file is just the same as an HTML file An ASP.NET file can contain HTML, XML, and scripts Scripts in an ASP.NET file are executed on the server An ASP.NET file has the file extension ".aspx"

Working of ASP.NET
When a browser requests an HTML file, the server returns the file. When a browser requests an ASP.NET file, IIS passes the request to the ASP.NET engine on the server. The ASP.NET engine reads the file, line by line, and executes the scripts in the file. Finally, the ASP.NET file is returned to the browser as plain HTML.

Difference Between ASP and ASP.NET


1. Code behind in asp. net allows separation of business logic from UI which is not possible in asp. 2. ASP. Net uses ADO .Net objects which are represented using XML and hence they are lightweight and can travel through firewalls. ASP uses ADO record sets which are binary COM objects heavier than ADO.Net counterparts and cannot travel through firewalls. 3. ASP.Net supports object oriented programming. ASP is procedural. 4. ASP.Net is compiled and hence performs better. ASP is pure scripting and hence interpreted at the time of page load. 5. ASP.Net has caching and exception handling which is not available with ASP. 6. ASP.NET has better language support, a large set of new controls, XML-based components, and better user authentication. 7. ASP.NET provides increased performance by running compiled code. 8. ASP.NET code is not fully backward compatible with ASP

Advantage of ASP.NET
1. ASP.NET drastically reduces the amount of code required to build large applications. 2. With built-in Windows authentication and per-application configuration, your applications are safe and secured. 3. It provides better performance by taking advantage of early binding, just-in-time compilation, native optimization, and caching services right out of the box. 4. The ASP.NET framework is complemented by a rich toolbox and designer in the Visual Studio integrated development environment. WYSIWYG editing, drag-anddrop server controls, and automatic deployment are just a few of the features this powerful tool provides. 5. Provides simplicity as ASP.NET makes it easy to perform common tasks, from simple form submission and client authentication to deployment and site configuration. 6. The source code and HTML are together therefore ASP.NET pages are easy to maintain and write. Also the source code is executed on the server. This provides a lot of power and flexibility to the web pages. 7. All the processes are closely monitored and managed by the ASP.NET runtime, so that if process is dead, a new process can be created in its place, which helps keep your application constantly available to handle requests. 8. It is purely server-side technology so, ASP.NET code executes on the server before it is sent to the browser. 9. Being language-independent, it allows you to choose the language that best applies to your application or partition your application across many languages. 10. ASP.NET makes for easy deployment. There is no need to register components because the configuration information is built-in. 11. The Web server continuously monitors the pages, components and applications running on it. If it notices any memory leaks, infinite loops, other illegal activities, it immediately destroys those activities and restarts itself. 12. Easily works with ADO.NET using data-binding and page formatting features. It is an application which runs faster and counters large volumes of users without having performance problems.

Architecture of ASP.NET

The configuration of ASP.NET is managed by information stored in XML-format in a configuration file (Web.Config). The cache allows for improved performance of ASP.NET, as the most commonly requested pages would be served from

the ASP.NET cache.State management services for ASP.NET are provided by the ASP.NET state service. The .NET Framework provides the Common Language Runtime (CLR) , which compiles and manages the execution of ASP.NET code, and the class libraries, which offer prebuilt programmatic functionality for Web Forms, XML support, and exception handling. ADO.NET provides ASP.NET with connections to databases.

3-Tier Architecture in ASP.NET with C#


3-Tier architecture generally contains UI or Presentation Layer, Business Access Layer (BAL) or Business Logic Layer and Data Access Layer (DAL). Presentation Layer (UI) Presentation layer contains pages like .aspx or windows form where data is presented to the user or input is taken from the user. Business Access Layer (BAL) or Business Logic Layer BAL contains business logic, validations or calculations related with the data.. Data Access Layer (DAL) DAL contains methods that helps business layer to connect the data and perform required action, might be returning data or manipulating data (insert, update, delete etc). Designing 3-Tier Architecture

Data Access Layer (DAL) Code

Code for Data Access Layer

using System; using System.Data; using System.Configuration; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; using System.Data.OleDb; public class PersonDAL { string connStr = ConfigurationManager.ConnectionStrings["connectionstring"].ToString(); public PersonDAL() { } public int Insert(string name, string address, int age) { OleDbConnection conn = new OleDbConnection(connStr); conn.Open(); OleDbCommand dCmd = new OleDbCommand("insert into insertrecord values(@P,@q,@r)",conn); try { dCmd.Parameters.AddWithValue("@p", name); dCmd.Parameters.AddWithValue("@q", address); dCmd.Parameters.AddWithValue("@r", age); return dCmd.ExecuteNonQuery(); } catch { throw;

Business Access Layer (BAL) Code Code for Business Access Layer

using System; using System.Data; using System.Configuration; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; public class PersonBAL { public PersonBAL() { } public int Insert(string name, string address, int age) { PersonDAL pDAL = new PersonDAL(); try { return pDAL.Insert(name, address, age); } catch { throw; } finally {

pDAL = null; } } }

Code for .cs file

using using using using using using using using using using using

System; System.Configuration; System.Data; System.Linq; System.Web; System.Web.Security; System.Web.UI; System.Web.UI.HtmlControls; System.Web.UI.WebControls; System.Web.UI.WebControls.WebParts; System.Xml.Linq;

public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } protected void Button1_Click(object sender, EventArgs e) { //Lets validate the page first if (!Page.IsValid) return; int intResult = 0; PersonBAL pBAL = new PersonBAL(); // Instantiate the object we have to deal with string name = txtname.Text; string address = txtaddress.Text; int age = Int32.Parse(txtAge.Text); try { intResult = pBAL.Insert(name, address, age); if (intResult > 0) lblMessage.Text = "New record inserted successfully."; else

lblMessage.Text = "FirstName [<b>" + txtname.Text + "</b>] alredy exists, try another name"; } catch (Exception ee) { lblMessage.Text = ee.Message.ToString(); } finally { pBAL = null; } } }

Presentation Layer

Code for .aspx page

<%@ Page Language="C#"AutoEventWireup="true"Codevirtual="Default.aspx.cs"Inherits="_Default"% > <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title>Untitled Page</title> <style type="text/css"> .style1 { width: 100%; height: 215px; background-color: #FFFFCC; } .style2 { width: 271px; } .style3 { width: 271px; height: 44px; } .style4 { height: 44px; } </style> </head> <body> <form id="form1" runat="server"> <div style="background-color: #008000; height: 253px;"> <table class="style1"> <tr> <td colspan="2"> ADD RECORDS&nbsp;</td> </tr> <tr> <td class="style2"> &nbsp;&nbsp;&nbsp;&nbsp;Name</td> <td> <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox> </td> </tr> <tr> <td class="style2"> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp&nbsp; Address&nbsp;</td> <td> <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox> </td> </tr> <tr> <td class="style3">

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Age&nbsp;</td> <td class="style4"> <asp:TextBox ID="TextBox3" runat="server"></asp:TextBox> </td> </tr> <tr> <td class="style2"> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <td> <asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Save Record" /> </td> </tr> <tr> <td class="style2"> &nbsp;</td> <td> &nbsp;</td> </tr> </table> </div> </form> </body> </html>

Life Cycle of ASP.NET


Page Life Cycle Events Page_Init: The server controls are loaded and initialized from the Web form's view state. it is basically used for initialized the object and control Page_Load: The server controls are loaded in the page object. View state information is available at this point, so this is where you put code to change control settings or display text on the page. Page_PreRender: The application is about to render the page object. Page_Unload: The page is unloaded from memory. Page_Disposed: The page object is released from memory. This is the last event in the life of a page object. Page_Error: An unhandled exception occurs. Page_AbortTransaction: A transaction is aborted. Page_CommitTransaction: A transaction is accepted. Page_DataBinding: A server control on the page binds to a data source.

Control in ASP.NET
HTML Controls - Traditional HTML tags Web Server Controls - New ASP.NET tags Validation Server Controls - For input validation

HTML Server Controls

HTML server controls are HTML tags understood by the server. HTML elements in ASP.NET files are, by default, treated as text. To make these elements programmable, add a runat="server" attribute to the HTML element. This attribute indicates that the element should be treated as a server control. The id attribute is added to identify the server control. The id reference can be used to manipulate the server control at run time. Note: All HTML server controls must be within a <form> tag with the runat="server" attribute. The runat="server" attribute indicates that the form should be processed on the server. It also indicates that the enclosed controls can be accessed by server scripts. DESIGN OF HTML CONTROL

<script language="javascript" type="text/javascript"> function Submit1_onclick() { alert("click me"); } </script> </head> <body> <form id="form1" runat="server"> <div> <input id="Text1" type="text" value="anil" /> <input id="Submit1" type="submit" value="submit" onclick="return Submit1_onclick()" /></div> </form> </body> </html>

Web Server Controls

Web server controls are special ASP.NET tags understood by the server. Like HTML server controls, Web server controls are also created on the server and they require a runat="server" attribute to work. However, Web server controls do not necessarily map to any existing HTML elements and they may represent more complex elements.

The syntax for creating a Web server control is:


<asp:control_name id="some_id" runat="server" />

DESIGN OF WEB SERVER CONTROL

.ASPX CODE
<html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title>Untitled Page</title> </head> <body> <form id="form1" runat="server"> <div style="width: 246px; background-color: #66FFFF;"> Name&nbsp; <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox> <br /> <asp:TextBox ID="TextBox2" runat="server" ></asp:TextBox> <br /> <br /> <asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="click me" /> <br /> <br />

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

.CS CODE

protected void Button1_Click(object sender, EventArgs e) { TextBox1.Text = "wiliam"; TextBox2.Text = "hello world"; }

Validation Server Controls

DESIGN OF VALIDATION SERVER CONTROL

Validation server controls are used to validate user-input. If the user-input does not pass validation, it will display an error message to the user.

.ASPX CODE

<html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title>Untitled Page</title> </head> <body> <form id="form1" runat="server"> <div style="width: 414px; background-color: #66FFFF;"> Name&nbsp; <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>

<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="TextBox1" ErrorMessage="Blank are not allowed" SetFocusOnError="True"></asp:RequiredFieldValidator> <br /> &nbsp;Address&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <asp:TextBox ID="TextBox2" runat="server" ontextchanged="TextBox2_TextChanged"></asp:TextBox> <br /> <br /> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="click me" /> <br /> <br /> </div> </form> </body> </html>

.CS CODE

protected void Button1_Click(object sender, EventArgs e) { TextBox1.Text = "123"; TextBox2.Text = "hello world"; Response.Write("hi display textbox 1 value"+TextBox1.Text); }

Various types of application that we can develop in .NET

When you hear the name .NET, it gives a feeling that it is something to do only with internet or networked applications. Even though it is true that .NET provides solid foundation for developing such applications it is possible to create many other types of applications.

Following list will give you an idea about various types of application that we can develop on .NET.

ASP.NET Web applications: These include dynamic and data driven browser based applications.

Windows Form based applications: These refer to traditional rich client applications.

Console applications: These refer to traditional DOS kind of applications like batch scripts.

Component Libraries: This refers to components that typically encapsulate some business logic.

Windows Custom Controls: As with traditional ActiveX controls, you can develop your own windows controls.

Web Custom Controls: The concept of custom controls can be extended to web applications allowing code reuse and modularization.

Web services: They are web callable functionality available via industry standards like HTTP, XML and SOAP.

What is Partial Class

The purpose of a partial class is to allow you to textually break up a class declaration into multiple parts, usually parts found in separate files. The motivation for this feature was machine-generated code that is to be extended by the user by adding to it directly. When you draw a form in the forms designer, the designer generates a class for you representing that form. You can then further customize that class by adding more code to it.

By the use of partial Class you can split the definition into multiple classes by using the partial keyword. When the application is complied, the C# complier will group all the partial classes together and treat them as a single class. There are a couple of good reasons to use partial classes. Programmers can work on different parts of a class without needing to share the same physical file. Also you can separate your application business logic from the designer-generated code.

Example of Partial Class

Public partial class Employee

public void display()

{}

Public partial class Employee

public void show()

{}

State Management in ASP.NET


State management is the process by which you maintain state and page information over multiple requests for the same or different pages.

Types of State Management


Client Side State Management ASP.NET provides various client side state management options like Cookies, Query Strings (URL), Hidden fields, View State and Control state (ASP.NET 2.0).This stores information on the client's computer by embedding the information into a Web page, a uniform resource locator (url), or a cookie. The techniques available to store the state information at the client computer. a. View State Asp .Net uses View State to track the values in the Controls. You can add custom values to the view state. It is used by the Asp .net page framework to automatically save the values of the page and of each control just prior to rendering to the page. When the page is posted, one of the first tasks performed by page processing is to restore view state.

Example of View state


Write code in .aspx page

<%@ Page Language="C#" AutoEventWireup="true" Codevirtual="Default.aspx.cs" Inherits="_Default" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head runat="server"> <title>ViewState</title> </head> <body> <form id="form1" runat="server"> <asp:TextBox runat="server" id="NameField" />

<asp:Button runat="server" id="SubmitForm" onclick="SubmitForm_Click" text="Submit & set name" /> <asp:Button runat="server" id="RefreshPage" text="Just submit" /> <br /><br /> Name retrieved from ViewState: <asp:Label runat="server" id="NameLabel" /> </form> </body> </html> .Cs Code

protected void Page_Load(object sender, EventArgs e) { if (ViewState["NameOfUser"] != null) NameLabel.Text = ViewState["NameOfUser"].ToString(); else NameLabel.Text = "Not set yet..."; } protected void SubmitForm_Click(object sender, EventArgs e) { ViewState["NameOfUser"] = NameField.Text; NameLabel.Text = NameField.Text; }

Advantages
The main advantage of view state is persisting controls properties without any programming and memory will not be occupied on the client system or on the server system.

Disadvantage
The disadvantage can be considered as a lot amount of data transmission between client and server.

1. Control State If you create a custom control that requires view state to work

properly, you should use control state to ensure other developers dont break your control by disabling view state. 2. Hidden fields Like view state, hidden fields store data in an HTML form without displaying it in the user's browser. The data is available only when the form is processed. 3. Cookies Cookies store a value in the user's browser that the browser sends with every page request to the same server. Cookies are the best way to store state data that must be available for multiple Web pages on a web site. 4. Query Strings - Query strings store values in the URL that are visible to the user. Use query strings when you want a user to be able to e-mail or instant message state data with a URL.

Cookies in ASP.NET
A cookie is a small bit of text file that browser creates and stores on your machine (hard drive). Cookie is a small piece of information stored as a string. Web server sends the cookie and browser stores it, next time server returns that cookie .Cookies are mostly used to store the information about the user. Cookies are stores on the client side .To store data in a cookie is not secure due to it's location at client end. Cookie was introduced with first version of Netscape navigator (that was 1.0).

Advantages
1. Cookies do not require any server resources since they are stored on the client. 2. Cookies are easy to implement. 3. You can configure cookies to expire when the browser session ends (session cookies) or they can exist for a specified length of time on the client computer (persistent cookies).

Disadvantages
1. Users can delete a cookies. 2. Users browser can refuse cookies ,so your code has to anticipate that possibility. 3. Cookies exist as plain text on the client machine and they may pose a possible security risk as anyone can open and tamper with cookies.

.ASPX CODE
<%@ Page Language="C#" AutoEventWireup="true" Codevirtual="Default3.aspx.cs" Inherits="Default3" %> <html xmlns="http://www.w3.org/1999/xhtml" > <head id="Head1" runat="server"> <title></title> </head> <body> <form id="form1" runat="server"> <div> <fieldset> <legend>rdfdf</legend> <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox> <asp:Button ID="Button1" runat="server" Text="Add" Width="70px" onclick="Button1_Click" /> <asp:Button ID="Button2" runat="server" Text="View" Width="84px" onclick="Button2_Click" /> <br /> <br /> <asp:Label ID="Label1" runat="server" Text="" Width="138px"></asp:Label> </fieldset> </div>

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

.CS CODE
(protected void Button1_Click(object sender, EventArgs e } Response.Cookies["MyCookie"]["Data"] = TextBox1.Text; // To Create Cookies ;("Response.Cookies["MyCookie"]["Time"] = DateTime.Now.ToString("G Response.Cookies["MyCookie"].Expires = DateTime.Now.AddMonths(1);// For Expire Cookies + "<Label1.Text = "Cookie created!<p>" + "Your cookie contains:<font color=red ["Request.Cookies["MyCookie"]["Data ;"<br>" + Request.Cookies["MyCookie"]["Time"] + "</font >" + ;("Response.Cookie("MyCookie").Expires = DateTime.FromString("2006-10-1// { (protected void Button2_Click(object sender, EventArgs e } (if (Request.Cookies["MyCookie"] == null ;":Label1.Text = "There is no cookie else Label1.Text = "Your cookie contains:" + "<font color=red>" + "<Request.Cookies["MyCookie"]["Data"] + "<br ;"<Request.Cookies["MyCookie"]["Time"] + "</font + {

Query String In ASP.NET


Query string is used to Pass the values or information form one page to another page. The query string is a holdover from the ASP days of web programming. You will see this a lot when you are surfing around the internet. Basically, it is passing information to the next page with the URL .You can use a query string to submit data back to your page or to another page through the URL. Query strings provide a simple but limited way of maintaining some state information.

The advantages of using query strings are


No server resources required. The query string is contained in the HTTP request for a specific URL. Broad support. Almost all browsers and client devices support passing values in a query string it is very easy

The disadvantages of using query strings are


Security. The information in the query string is directly visible to the user via the browser user interface. The query values are exposed to the Internet via the URL so in some cases security may be an issue. Limited capacity. Most browsers and client devices impose a 255-character limit on URL length .CS CODE

private void btnSubmit_Click(object sender, System.EventArgs e) { Response.Redirect("Default.aspx?Name=" + this.txtName.Text + "&LastName=" + this.txtLastName.Text); }

Our first code part builds a query string for your application and send contents of your textboxes to second page. Now how to retrieve this values from second page. Put this code to second page page_load. .ASPX CODE

private void Page_Load(object sender, System.EventArgs e) { this.txtBox1.Text = Request.QueryString["Name"]; this.txtBox2.Text = Request.QueryString["LastName"]; }

Server Side State Management


When users visit Web sites it becomes necessary to maintain session related and controls related information. In an HTTP exchange between a browser and a remote host, session related information which identifies state, such as a unique session ID, information about the user's preferences or authorization level is preserved. Note that sessions are maintained in the data being exchanged. State Management is the process by which we maintain session related information and additional information about the controls and its state. The necessity of state management arises when multiple users request for the same or different Web Pages of a Web Site. State management can be accomplished using Client Side options or the Server side options. Session State: Its nothing but defined as a period of time shared between the web application and user. Every user has individual session. Items/Objects can be placed into the Session which would only define these object for that user. Session contains key variables which help to identify the related values. This can be thought of as a hash table. Each user would represent a different key node in the hash identifying unique values. The Session variables will be clear by the application which can clear it, as well as through the

timeout property in the web config file. Usually the timeout is 20 minutes by default. ASP.NET allows you to save values using session state, a storage mechanism that is accessible from all pages requested by a single Web browser session. Therefore, you can use session state to store user-specific information. Session state is similar to application state, except that it is scoped to the current browser session. If different users are using your application, each user session has a different session state. In addition, if a user leaves your application and then returns later after the session timeout period, session state information is lost and a new session is created for the user. Session state is stored in the Session key/value dictionary. Session Variables are stored on the server, can hold any type of data including references, they are similar to global variables in a windows application and use HTTP cookies to store a key with which to locate user's session variables .The collection of session variables is indexed by the name of the variable or by an integer index. Session variables are created by referring to the session variable by name. You do not have to declare a session variable or explicitly add it to the collection. Example: //Storing informaton in session state Session["username"] = "Ashish"; //Retrieving information from session state string str = Session["username"]; Application State: Application State is used to store information which is shared among users of the ASP.Net web application. Application state is stored in the memory of the windows process which is processing user requests on the web server. Application state is useful in storing small amount of often-used data. If application state is used for such data instead of frequent trips to database, then it increases the response time/performance of the web application. In ASP.Net, application state is an instance of HttpApplicationState class and it exposes keyvalue pairs to store information. Its instance is automatically created when a first request is made to web application by any user and same state object is being shared across all subsequent users. Application state can be used in similar manner as session state but it should be noted that many user might be accessing application state simultaneously so any call to application state object needs to be thread safe. This can be easily achieved in ASP.Net by using lock keyword on the statements which are accessing application state object. This lock keyword places a mutually exclusive lock on the statements and only allows a single thread to access the application state at a time. Code Sample //Stroing information in application state lock (this) { Application["username"] = "william"; }

//Retrieving value from application state lock (this) { string str = Application["username"].ToString(); }

Master Page
Introduction Of Master Page Microsoft ASP.NET 2.0 introduces a new feature .Master Pages. that permits you to define common user interface (UI) elements and common structure in a template that can be applied to multiple content pages in a Web application. Standard elements are, for example, navigational menus, logos, and other stock graphical elements. This allows you to have a common appearance and functionality across your Web site, avoids duplication of code, and makes the site easier to maintain. If the content pages are based on the master page, all the elements defined in the master page would automatically be defined in the content pages. The page layout for Master Pages is easy to create, simple to maintain, and simple to assign to a Web application. The Master page provides a single point of reference for all pages to display standardized Web content. Master pages are completely transparent to end users and permit developers to create Web sites where pages share a common layout. Defining a Master page is similar to defining a normal page, but saving a Master page is different from saving a normal page. You must save the Master pages by using the .master file extension. How to Add Master Page in Your Application Adding a master page to your web application is straight forward. Just right click on the project and select "Add New Item" and than select "Master Page". This will add the master page to your project. The master page already has the content place holder control which is used to hold and display your contents. Let's delete that content placeholder and add it by our self. In this case we will create two content place holders. One will be on the left and other one on the right .After you insert the content placeholder control inside your table your master page will look something like this:

Using the master page in your aspx pages Just add a new aspx page and name it as "first .aspx". Now you want to use the Sample1.master file in your aspx page. Just go to the html view of your page and add a Master Page File attribute in the page directive and delete all the other html that is written in the aspx page. The Master Page File attribute denotes that the Page is inheriting from the master page. <%@ Page Master Page virtual="~/Sample1.master" %>

Gridview in ASP.NET
The GridView control displays data as a table and provides the capability to sort columns, page through data, and edit or delete a single record. the GridView control offers improvements such as the ability to define multiple primary key fields, improved user interface customization using bound fields and templates, and a new model for handling or canceling events. Displays the values of a data source in a table where each column represents a field and each row represents a record. The GridView control enables you to select, sort, and edit these items. Namespace: System.Web.UI.WebControls . Assembly: System.Web (in System.Web.dll) .

GridView Control Features


Enhanced data source binding capabilities (Direct interaction with Data Source with any writing any ADO.NET code) Built-in support for sorting and paging functionalities Improved Design time features(Smart Panel Tag) Customized pager user interface with PagerTemplate property. Additional Column types(ImageField). New Event model with support for pre event and post event operations

Difference between Datagrid,DataList and Data Repeater


Datagrid has paging while Datalist doesnt. Datalist has a property called repeat. Direction = vertical/horizontal. (This is of great help in designing layouts). This is not there in Datagrid. A repeater is used when more intimate control over html generation is required. When only checkboxes/radiobuttons are repeatedly served then a checkboxlist or radio button list are used as they involve fewer overheads than a Datagrid. Design of Gridview:

.CS Code

protected void Page_Load(object sender, EventArgs e) { OleDbConnection con; OleDbDataAdapter da; string conn = System.Configuration.ConfigurationManager.AppSettings["x"].ToString(); con = new OleDbConnection(conn); da = new OleDbDataAdapter("select purchase1,tax,issue_date from purchase", con); DataSet ds=new DataSet(); da.Fill( ds, "purchase"); GridView1.DataSource = ds.Tables["purchase"]; GridView1.DataBind(); }

.ASPX Code

<%@ Page Language="C#" AutoEventWireup="true" Codevirtual="Default.aspx.cs" Inherits="_Default" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/ TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title>Untitled Page</title> <style type="text/css"> .style1 { width: 100%; } </style> </head> <body> <form id="form1" runat="server"> <div> <asp:GridView ID="GridView1" runat="server" AllowPaging="True" BackColor="#DEBA84" BorderColor="#DEBA84" BorderStyle="None" BorderWidth="1px" CellPadding="3" CellSpacing="2" Height="341px" onselectedindexchanged="GridView1_SelectedIndexChanged" Width="192px"> <FooterStyle BackColor="#F7DFB5" ForeColor="#8C4510" /> <RowStyle BackColor="#FFF7E7" ForeColor="#8C4510" /> <PagerStyle ForeColor="#8C4510" HorizontalAlign="Center" /> <SelectedRowStyle BackColor="#738A9C" Font-Bold="True" ForeColor="White" /> <HeaderStyle BackColor="#A55129" Font-Bold="True" ForeColor="White" /> </asp:GridView> <table class="style1"> <tr> <td> <marquee direction="up" behavior="scroll" onmouseover="this.stop()" onmouseout="this.start()" scrollamount="2"> <a href="#">Retail Express Distribution</a><br /><br /> <a href="#">Global Express Consolidation Service</a><br /><br /> <a href="#">Import Express </a><br /><br /> <a href="#">Collect charges and cash on delivery</a><br /><br /></marquee>&nbsp;</td> <td> &nbsp;</td> </tr> <tr> <td> &nbsp;</td> <td> &nbsp;</td> </tr> </table> </div> </form> </body> </html>

How to EDIT/UPDATE/CANCEL/DELETE in Gridview

Introduction This article explains the methods of binding Asp.Net GridView control with simple DataSet or DataTable, and also explains the methods like Insert, Edit, Update and Delete function in the GridView control. Design of Gridview

Simple DataBind in Gridview

public void bindgrid() { OleDbConnection con; OleDbDataAdapter da; con = new OleDbConnection("provider=microsoft.jet.oledb.4.0;Data source=D:\\invent.mdb"); da = new OleDbDataAdapter("select item_id, Item,tax from purchase", con); DataSet ds = new DataSet(); da.Fill(ds, "purchase"); GridView1.DataSource = ds.Tables["purchase"]; GridView1.DataBind(); }

How to Call bindgrid Method

protected void {

Page_Load(object sender, EventArgs e)

if (!Page.IsPostBack) { bindgrid(); } }

Simple Code For Edit Update And Delete In Gridview Design of EDIT Gridview

How to Edit Gridview


protected void GridView1_RowEditing(object sender,

GridViewEditEventArgs e) { GridView1.EditIndex = e.NewEditIndex; } bindgrid();

Design of Update in Gridview

How to Update Gridview


This event will update information in database.

protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e) { string UserID = GridView1.DataKeys[e.RowIndex].Value.ToString(); string l = ((TextBox)GridView1.Rows[e.RowIndex].Cells[1].Controls[0]).Text; string k = ((TextBox)GridView1.Rows[e.RowIndex].Cells[2].Controls[0]).Text; OleDbConnection can = new OleDbConnection("provider=microsoft.jet.oledb.4.0;Data source=D:\\invent.mdb"); can.Open();

OleDbCommand com1 = new OleDbCommand("update purchase set purchase1='" +l + "', tax='" + k + "' where item_id='" + UserID + "'", can); com1.ExecuteNonQuery(); can.Close(); //to go back to the previous position GridView1.EditIndex = -1; // // fetch and rebind the data. bindgrid(); } Note-- item_id must be primary key And right click on gridview go to property datakey names=item_id(primary key)

How to Delete Gridview Design of Delete Row from Gridview

How to Delete Particular Row From Gridview


This event shows how to delete a row from datebase

protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e) {

string UserID = GridView1.DataKeys[e.RowIndex].Value.ToString(); OleDbConnection can = new OleDbConnection("provider=microsoft.jet. oledb.4.0;Data source=D:\\invent.mdb"); can.Open(); OleDbCommand com1 = new OleDbCommand("delete from purchase where item_id ='"+UserID+"'" , can); com1.ExecuteNonQuery(); can.Close(); //to go back to the previous position GridView1.EditIndex = -1; // // fetch and rebind the data. bindgrid();

How to cancel editable mode.


protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e) { GridView1.EditIndex = -1; bindgrid(); }

Simple Select, Edit, Update and Delete in Asp.Net GridView


Design Of Gridview

.ASPX CODE

<%@ Page Language="C#" AutoEventWireup="true" Codevirtual="Default.aspx.cs" Inherits="_Default" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/ DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title>Untitled Page</title> </head> <body> <form id="form1" runat="server"> <div> <asp:GridView ID="GridView1" runat="server" AllowPaging="True" AutoGenerateColumns="False" BackColor="#DEBA84" BorderColor="#DEBA84" BorderStyle="None" BorderWidth="1px" CellPadding="3" CellSpacing="2" DataKeyNames="item_id" onrowcancelingedit="GridView1_RowCancelingEdit" onrowcommand="GridView1_RowCommand" onrowdeleting="GridView1_RowDeleting" onrowediting="GridView1_RowEditing" onrowupdating="GridView1_RowUpdating" onselectedindexchanged="GridView1_SelectedIndexChanged"> <FooterStyle BackColor="#F7DFB5" ForeColor="#8C4510" /> <RowStyle BackColor="#FFF7E7" ForeColor="#8C4510" /> <Columns> <asp:BoundField DataField="item_id" HeaderText="ITEM" /> <asp:BoundField DataField="purchase1" HeaderText="name" /> <asp:BoundField DataField="tax" HeaderText="tax" /> <asp:CommandField ShowEditButton="True" /> <asp:CommandField ShowSelectButton="True" /> <asp:CommandField ShowDeleteButton="True" /> </Columns> <PagerStyle ForeColor="#8C4510" HorizontalAlign="Center" /> <SelectedRowStyle BackColor="#738A9C" Font-Bold="True" ForeColor="White" /> <HeaderStyle BackColor="#A55129" Font-Bold="True" ForeColor="White" /> <AlternatingRowStyle BorderColor="#FF99FF" /> </asp:GridView> </div> </form> </body> </html>

.CS CODE
using System;

using using using using using using using using using using using

System.Configuration; System.Data; System.Linq; System.Web; System.Web.Security; System.Web.UI; System.Web.UI.HtmlControls; System.Web.UI.WebControls; System.Web.UI.WebControls.WebParts; System.Xml.Linq; System.Data.OleDb;

public partial class _Default : System.Web.UI.Page { public void bindgrid() { OleDbConnection con; OleDbDataAdapter da; con = new OleDbConnection("provider=microsoft.jet.oledb.4.0;Data source=D:\\invent.mdb"); da = new OleDbDataAdapter("select item_id, purchase1,tax from purchase", con); DataSet ds = new DataSet(); da.Fill(ds, "purchase"); GridView1.DataSource = ds.Tables["purchase"]; GridView1.DataBind(); } protected void Page_Load(object sender, EventArgs e) { if (!Page.IsPostBack) { } bindgrid();

} protected void Button1_Click(object sender, EventArgs e) { } protected void GridView1_SelectedIndexChanged(object sender, EventArgs e) { } protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e) { GridView1.EditIndex = e.NewEditIndex; bindgrid();

} protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e) { string UserID = GridView1.DataKeys[e.RowIndex].Value.ToString(); string l = ((TextBox)GridView1.Rows[e.RowIndex].Cells[1].Controls[0]).Text; string k = ((TextBox)GridView1.Rows[e.RowIndex].Cells[2].Controls[0]).Text; OleDbConnection can = new OleDbConnection("provider=microsoft.jet.oledb.4.0;Data source=D:\\invent.mdb"); can.Open(); OleDbCommand com1 = new OleDbCommand("update purchase set purchase1='" +l + "',tax='" + k + "' where item_id='" + UserID + "'", can); com1.ExecuteNonQuery(); can.Close(); //to go back to the previous position GridView1.EditIndex = -1; // // fetch and rebind the data. bindgrid(); } protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e) { GridView1.EditIndex = -1; bindgrid(); } protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e) { } protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e) { string UserID = GridView1.DataKeys[e.RowIndex].Value.ToString(); OleDbConnection can = new OleDbConnection("provider=microsoft.jet.oledb.4.0;Data source=D:\\invent.mdb"); can.Open(); OleDbCommand com1 = new OleDbCommand("delete from purchase where item_id ='"+UserID+"'" , can); com1.ExecuteNonQuery(); can.Close(); //to go back to the previous position GridView1.EditIndex = -1; // // fetch and rebind the data. bindgrid(); } }

Validation Control In ASP.NET


Introduction ASP.NET validation controls provide an easy-to-use but powerful mechanism of ensuring that data is entered correctly on the forms. There are 6 validation controls included in the ASP.NET 2.0 and ASP.NET 3.5 versions. ASP.NET validation controls also provide two ways of validation: Server-side or Client-side. The nice thing about these Validation controls is that it will perform client-side validation when it detects the browser is able (unless client-side validation has been disabled). Thus reducing roundtrips. And it will perform server-side where necessary. This clientside/server-side detection and validation is done without extra work by the developer! In ASP.NET, there are five(6) Validation controls included. They are: Validation Server Control CompareValidator CustomValidator RangeValidator RegularExpressionValidator RequiredFieldValidator ValidationSummary Description Compares the value of one input control to the value of another input control or to a fixed value Allows you to write a method to handle the validation of the value entered Checks that the user enters a value that falls between two values Ensures that the value of an input control matches a specified pattern Makes an input control a required field Displays a report of all validation errors occurred in a Web page

How to use Validation Control IN Website: Create a new website project and you have an Empty default.aspx page. In your Solution Explorer double click it and go to its design view. Look for your toolbar on the left hand side of your window. In the Toolbar look for the Validation Section as depicted below

These controls are used to validate the user input provided at the standard controls. Note: *If the validation control returns false then the data will not be submitted to the server. *A single validation control can validate a single standard control. *A single standard control can be binded with any no. of validation controls. *Validation scripts should not be altered from ASP. Net 2.0 onwards. If any modifications are performed on the scripts then all the ASP.Net websites which uses validation controls will not function properly. *Validation controls can be grouped together from ASP. Net 2.0 onwards Difference Between Server side Control And Client Side Control 1..Client side validation is processed the client side before submitting the form. The advantage of using the client side validation is it reduces the network traffic since the validation is processed in the client machine itself. 2..Server side validation is processed in the server. Some data cannot be validated in the client side and it has to be validated in the server side. E.g. Date between the two dates in the database. 3..Client-side is faster than server-side as the networking time from client to server is saved. 4..server-side is done on the server. Then the server converts the data into an html page and sends to the browser. 5..server-side is more secure as the user cannot see the code even he does a view-source.

6..The disadvantage of javascript validation is that users can have javascript turned off and therefore can submit invalid data. 7..The difference is that the javascript validation is done on the client side (if the user's browser supports it, so never depend on javascript alone), before the page is submitted to the server. The advantage is that the user gets immediate feedback and does not need to wait for the page to reload. It also reduces server load.

Required FieldValidator control


It is used to verify if a value has been provided for a control or not. As the name suggest, this validation control make sure that control mention in Control ToValidate cannot be empty. Common properties for all the validation controls: ControlToValidate ErrorMessage Specifies the name of the control which has to be validated. Specifies the error message to be displayed if the validation control returns false.

Note: If customization or if validation controls has to be extended then the Text property for the validation controls should be set. If more than one validation control validates a standard control then it is mandatory that the Display property for all the validation controls should be set as Dynamic. Other than the RequiredFieldValidator control, remaining validation controls will not validate the controls if the value for the control is empty. .Aspx Code <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox> <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="TextBox1" ErrorMessage="* Blank are not allowed" SetFocusOnError="True" Display="Dynamic"></asp:RequiredFieldValidator>

Output:

CompareValidator control
This Control is used to compare the value or one control to the value of another control or to a fixed value. One catch here is that validation pass if both the fields are empty. To handle that one require to apply Required field validator along with CompareValidator.

<asp:TextBox ID="TextBox1" runat="server" /> <asp:TextBox ID="TextBox2" runat="server" /> <asp:CompareValidator ID="CompareValidator1" runat="server" ControlToValidate="TextBox2" Display="Dynamic" ValidationGroup="MyGroup" ToolTip=" password not matched No Match" ControlToCompare="TextBox1" >* password not matche pls reenter password</asp:CompareValidator>

ControlToCompare - This take the Id of control with which comparison is being done. Comparison can be made on following data types: Currency, Date, Double, Integer and String Properties ControlToCompare Type Specifies the name of the control which acts like a source control Specifies the data type to be used for validating the input. Default type is string. Specifies the operator to be used for validating the user input. Default is Equal. Grouping the validation controls together: In order to group the validation controls together ValidationGroup property for all the controls which belongs to the group should be set with the same name

Operator

Output: if password are same

Otherwise

RangeValidator
Range validator control is another validator control which checks to see if a control value is within a valid range. The attributes that are necessary to this control are: Maximum Value, Minimum Value, and Type. Properties: MaximumValue MinimumValue Type .ASPX Code <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox> <asp:RangeValidator ID="RangeValidator1" runat="server" ControlToValidate="TextBox2" ErrorMessage="Age should be 18 to 35" MaximumValue="35" MinimumValue="18" Type="Integer"></asp:RangeValidator> Output: Specifies the upper range Specifies the lower range Specifies the data type to be used for validating the user input

RegularExpressionValidator control
It is used to validate the user input based on the validation expression. Meta characters used to prepare the expression for single digit \d Accepts a single digit

/D \w \s [A-Za-z] [0-9] ^[0-9] Occurrences:

Accepts a single character Accepts any character other than a white space (spacebar) Accepts a space Accepts upper or lower case characters Accepts a numerical value Accepts any characters other than numeric value

It is used to specify the occurrence of the meta characters within the expression. {number} Accepts the input if the length of the expression is equal to the specified number E.g.: \d{5} accepts 5 digits number {Minnumber, } Accepts the input if the length after expression is greater than or equal to the specified Minnumber. E.g: [A-Za-z0-9_]{6, }

{Minnumber, Maxnumber}

Accepts the input if the length of the expression is between the specified range. e.g.: \D{6,8}

Modes: It is used to specify the occurrence of the meta characters within the expression. Mode ? . or * + E.g.: \d{1, } <==> \d+ [ma+am] => accepts madam, Malayalam .ASPX CODE MinOccurrence 0 0 1 MaxOccurrence 1 Any Any

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

<asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server" ControlToValidate="TextBox1" ErrorMessage="plese enter email ID" ToolTip="plese Enter email id" ValidationExpression="\w+([-+.']\w+)*@\w+ ([-.]\w+)*\.\w+([-.]\w+)*"></asp:RegularExpressionValidator>

Output:

Custom Validator control


It is used to validate user input based on the user defined functionality. OR Custom validator control is used to capture the validation that cannot be handled by the validator controls provided by ASP.NET. Here user is at the freedom to define his own custom method, both Client side and Server side. CustomValidator is the only validator control which has the capability to validate the user input at the client side and also at the server side. Other than the CustomValidator, all the controls will validate the user input at the client side. Property ClientValidationFunction Specifies the JavaScript function name, which provides the definition to validate the user input at the client side.

Event ServerValidate The code written within this event will be used to validate the user input at the server side.

.ASPX CODE

Custom text:<br /> <asp:TextBox runat="server" id="txtCustom" /> <asp:CustomValidator runat="server" id="cusCustom" controltovalidate="txtCustom" onservervalidate="cusCustom_ServerValidate" errormessage="The text must be exactly 8 characters long!" /> <br /><br />

.CS CODE

protected void CustomValidator1_ServerValidate(object sender, ServerValidateEventArgs e) { if (e.Value.Length == 8) e.IsValid = true; else e.IsValid = false; }

ValidateEmptyText is a boolean attribute that if set to true, the input control will be validated even if it is empty. ClientValidationFunction contains name of client validation function. OnServerValidate contains name of server validation function.

Validation Summary control


This control is used to display the list of all the validation error that has occurred on the page. The error message displayed is the one set for the ErrorMessage attribute of the validation control. No error message will be displayed if this attribute is not set. ASP.NET has provided an additional control that complements the validator controls .The validation summary control will collect all the error messages of all the non-valid controls and put them in a tidy list. The list can be either shown on the web page (as shown in the example above) or with a popup box (by specifying ShowMessageBox="True").. DisplayMode has three options List, BulletList and SingleParagraph ShowMessageBox when set to true will display the error as a alert popup ShowSummary will display the error on the page. By default it is true. .ASPX CODE

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

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/ xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title>Untitled Page</title> <style type="text/css"> .style1 { width: 52%; border-left-style: solid; border-left-width: 1px; border-right: 1px solid #C0C0C0; border-top-style: solid; border-top-width: 1px; border-bottom: 1px solid #C0C0C0; background-color: #008000; } .style2 { color: #FFFFFF; } .style3 { width: 126px; } </style> </head> <body> <form id="form1" runat="server"> <div> <table class="style1"> <tr> <td class="style2" colspan="2"> &nbsp; Regular&nbsp; Expression Validator&nbsp;</td> <tr> <td class="style2"> Email ID</td> <td class="style3"> <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox> </td> <td> <asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server" ControlToValidate="TextBox1" ErrorMessage="plese enter email ID" ToolTip="plese Enter email id"

ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*"> </asp:RegularExpressionValidator> </td> </tr> <tr> <td class="style2"> Name</td> <td class="style3"> <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox> </td> <td> <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="TextBox2" ErrorMessage="Blank not Allowed" SetFocusOnError="True"></asp:RequiredFieldValidator> </td> </tr> <tr> <td class="style2"> Age</td> <td class="style3"> <asp:TextBox ID="TextBox3" runat="server"></asp:TextBox> </td> <td> <asp:RangeValidator ID="RangeValidator1" runat="server" ControlToValidate="TextBox3" ErrorMessage="Age should be Between !8 to 35" MaximumValue="35" MinimumValue="18"></asp:RangeValidator> </td> </tr> <tr> <td class="style2"> &nbsp;</td> <td class="style3">

<asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Button" Width="123px" /> </td> <td> <asp:ValidationSummary ID="ValidationSummary1" runat="server" ShowMessageBox="True" ShowSummary="False" /> </td> </tr> <tr> <td class="style2"> &nbsp;</td> <td class="style3">

&nbsp;</td> <td> &nbsp;</td> </tr> </table> </div> </form> </body> </html>

Output::

Label Control in ASP.NET


It is used to provide the static information on the webform. Common properties for all the server side controls Id Used to specify the unique identifier for the control placed on the webform..

runat="Server" all control run on sever Text It is used to set or get the value from the server side control..

The id attribute is used to uniquely identify the <asp:label> control so you can refer to it in your ASP.NET code. The runat="server" attribute tells the server to process the control and generate HTML code to be sent to the client. The class hierarchy for this control is as follows 1. 2. 3. 4. Object Control Web Control Label

Syntax of Label Control <asp: Label ID="Label1" runat="server" Text="This is a label control"> </asp: Label> Simple Example of Lebel Control protected void Button1_Click(object sender, EventArgs e) { } Label1.Text = "Hi I AM Label control";

Click On Button

How To Write Line Break In ASP.NET Label Control To write text in lines in standard ASP.NET label control you need to use HTML tag <br />. This is example label control that contains text in Four Lines lines:

<asp:Label ID="Label1" runat="server" Text="This is Aditya<br />This is kamal<br /> This is Anil<br/> This is Ashish"> </asp:Label>

Example

TextBox Control in ASP.NET


TextBox Control is used for user to enter the input like any string eg., Name, Password , number etc., Asp.NET TextBox itself is a class which is present under System.Web.UI.WebControls namespace. It is used to accept SingleLine, MultiLine or Password characters as the input. Syntax Of Textbox <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox> Properties Property Description Specifies the AutoComplete behavior of a TextBox A Boolean value that specifies whether the control is automatically posted back to the server when the contents change or not. Default is false Specifies if a page is validated when a Postback occurs The width of the textbox The maximum number of characters allowed in the textbox Specifies whether or not the text in the text box can be changed The height of the textbox (only used if TextMode="Multiline") Specifies that the control is a server control. Must be set to "server" The contents of the textbox Specifies the behavior mode of a TextBox control (SingleLine, MultiLine or Password) The group of controls that is validated when a Postback occurs A Boolean value that indicates whether the contents of the textbox should wrap or not The name of the function to be executed when the text in the

AutoCompleteType AutoPostBack CausesValidation Columns MaxLength ReadOnly Rows


runat TagKey

Text TextMode ValidationGroup Wrap


OnTextChanged

textbox has changed Example .CS CODE

protected void Button1_Click(object sender, EventArgs e) { ListBox1.Items.Add("Name:"+TextBox3.Text); ListBox1.Items.Add("father Name:" + TextBox4.Text); ListBox1.Items.Add("Course:" + TextBox5.Text); ListBox1.Items.Add("college:" + TextBox6.Text); }

Output

Button Control in ASP.NET


Button control is generally used to post the form or fire an event either client side or server side. When it is rendered on the page, it is generally implemented through <input type=submit> HTML tag. However, if UserSubmitBehavior property is set to false then control will render out as <input type=button>. Its properties like BackColor, ForeColor, BorderColor, BorderStyle, BorderWidth, Height etc. are implemented through style properites of <input> tag. You can set its Text property either by setting Text property in the .aspx page or from server side page. (other properties can also be set from both pages)

The Button control is used to display a push button. The push button may be a submit button or a command button. By default, this control is a submit button. A submit button does not have a command name and it posts the page back to the server when it is clicked. It is possible to write an event handler to control the actions performed when the submit button is clicked. A command button has a command name and allows you to create multiple Button controls on a page. It is possible to write an event handler to control the actions performed when the command button is clicked. Properties

Properties CausesValidation CommandArgument CommandName OnClientClick PostBackUrl runat Text UseSubmitBehavior ValidationGroup Example

Description Specifies if a page is validated when a button is clicked Specifies additional information about the command to perform Specifies the command associated with the Command event Specifies the name of the function to be executed when a button is clicked Specifies the URL of the page to post to from the current page when a button is clicked Specifies that the control is a server control. Must be set to "server" Specifies the text on a button Specifies whether or not a button uses the browser's submit mechanism or the ASP.NET postback mechanism Specifies the group of controls a button causes validation, when it posts back to the server

.Cs Code protected void Button1_Click(object sender, EventArgs e) { Response.Write("Hi... Friends your College Name is:"+TextBox1.Text); }

Image Button in ASP.NET


ImageButton control is used to display an image that responds to mouse clicks. Specify the image to display in the control by setting the ImageUrl property. Both the Click and Command events are raised when the ImageButton control is clicked. By using the OnClick event handler, you can programmatically determine the coordinates where the image is clicked. You can then code a response based on the values of the coordinates. Note the origin (0, 0) is located at the upper-left corner of the image. You can use the OnCommand event handler to make the ImageButton control behave like a command button. A command name can be associated with the control by using the CommandName property. This allows multiple ImageButton controls to be placed on the same Web page. The value of the CommandName property can then be programmatically identified in the OnCommand event handler to determine the appropriate action to perform when each ImageButton control is clicked. The CommandArgument property can also be used to pass additional information about the command, such as specifying ascending order. Property Description Specifies if a page is validated when an CausesValidation ImageButton control is clicked Additional information about the command to CommandArgument perform The command associated with the Command CommandName event Specifies whether or not the control creates an GenerateEmptyAlternateText empty string as an alternate text The name of the function to be executed when OnClientClick the image is clicked The URL of the page to post to from the current PostBackUrl page when the ImageButton control is clicked Specifies that the control is a server control. ValidationGroup Must be set to "server" The group of controls for which the ImageButton runat control causes validation when it posts back to the server Property

How to Set Image On Button

Output

Hyperlink control in ASP.NET


The Hyperlink Web server control is used to create a link to another Web page. The text in the HyperLink control is specified using the Text property. We can also display a image on this control instead of text. Properties: These are the following properties of the Hyperlink control.

Figure 1. Text - The text to be shown for the link. ImageUrl - gets\sets The image to be displayed in the hyperlink. NavigateUrl - The URL to navigate to when the hyperlink is clicked. Target - The target property allows us to set new page/content to be displayed in a new browser window, same window, etc. The values are as follows: _blank: displays the linked content in a new window without frames. _parent: displays the linked content in the immediate frameset parent.

_self: displays the linked content in the frame with focus. _top: displays the linked content in the full window without frames. ToolTip - ToolTip displayed when the mouse is over the control.

Example Design

Right Click on Home

Output When you click On Hyperlink it will show home Page of website

Literal Control in ASP.NET


The Literal Control is similar to the Label Control as they both are used to display static text on a web page. The Literal Control is not inherited from WebControl namespace. The Literal Control doesn't provide substantial functionality but Literal text is programmable. It doesn't add any HTML elements to the web page. This control makes it possible to add HTML code directly in the code designer window without switching to design view and clicking the HTML button to edit the HTML. You cannot apply a style to a literal control. Unlike Label control, there is no property like BackColor, ForeColor, BorderColor, BorderStyle, BorderWidth, Height etc. for Literal control. That makes it more powerful, you can even put a pure HTML contents into it.

The Literal control is used to display text; that is, it renders static text on a Web page without adding additional HTML tags. It passes content directly to the client browser unless you use the Mode property to encode the content.

Syntax of Literal Control <asp:Literal ID="LiteralText" runat="server" Text="This is example of Literal"></asp:Literal> Important Properties of Asp.NET Webserver Literal control are given below. You can Set /Get these properties at Design time or at Runtime. Mode - Enumerator - To specify how to render literal control in a web page. Text - Accept String - Commenly Used property to Get/Set the text that you want to render in your webpage There are three Mode enumerator available. These are PassThrough : If you set this property, then the content will not be modified and rendered as is. For eg., if string contains <hr> tag then its dependent on your browser, of how it handles <hr> tag. Encode : If you set this property then content will be encoded and sent to browser for eg., if your string contains <hr> tag, then your string will be converted to &lt;Hr&gt; and sent to browser. Transform : If you set Mode property to Transform then the string render depends upon the type of the markup. Events available in Asp.Net Web server Literal Control are: Click Init Load PreRender UnLoad The difference between a Label Control and a Literal Control? The main difference is, you can apply style to a Label control where as you can not apply styles in a literal control. Label control renders as span tag in a webpage while Literal Control only shows the text without any tag associated to it. Literal control does not maintain its viewstate. It's always a good practice to use literal control when you want to display a plain text in your web page. ASP.NET Literal itself is a class which is present under System.Web.UI namespace.

.aspx code:

<asp:Literal ID="Literal1" runat="server"></asp:Literal> <asp:Literal ID="Literal2" runat="server"></asp:Literal>

<asp:Literal ID="Literal3" runat="server"></asp:Literal>

.CS CODE:

(protected void ImageButton1_Click(object sender, ImageClickEventArgs e ;"Label1.Text = "Hi I am Ashish Kumar Gupta// ;Literal1.Mode = LiteralMode.Encode ;Literal1.Mode = LiteralMode.PassThrough ;Literal1.Mode = LiteralMode.Transform Literal1.Text = @"<font size=4 color=red>Literal1 with Encode property <example</font ;"<script>alert(""Literal with Encode property"");</script></br></br > Literal2.Text = @"<font size=4 color=green>Literal2 with PassThrough property <example</font ;"<script>alert(""Literal with PassThrough property"");</script></br></br > Literal3.Text = @"<font size=4 color=blue>Literal3 with Encode Transform <example</font ;"<script>alert(""Literal with Transform property"");</script></br></br > { { }

Output:

ASP.NET LinkButton Control


Link Button Control is similar to Button Control. Everything is similar in properties and events,except that user can see it as a Link. Syntax Of Link Button <asp:LinkButton ID="LinkButton1" runat="server" >Home</asp:LinkButton> Important Properties AccessKey: specify a key that navigates to the Button control. CommandArgument: specify a command argument that is passed to the Command event. CommandName: specify a command name that is passed to the Command event. Enabled: disable the LinkButton control. OnClientClick: specify a client-side script that executes when the Link Button is clicked. PostBackUrl: post a form to a particular page. TabIndex: specify the tab order of the LinkButton control. Text: label the LinkButton control. Focus: set the initial form focus to the LinkButton control.

LinKButton Event Event Click Command Example .CS Code Description occurs when the LinkButton control is clicked by the user.

occurs when the LinkButton control is clicked and passes its associated CommandName and CommandArgument to the server side event handler.

protected void LinkButton1_Click(object sender, EventArgs e)

{ } { }

Label1.Text = "This is my Home Page"; protected void LinkButton2_Click(object sender, EventArgs e) Label1.Text = "My Company name R4r TechSoft Solution ";

protected void LinkButton3_Click(object sender, EventArgs e) { Label1.Text = "My Name is Rituraj Tyagi And My Contact No... 9717009112"; }

DropDownList in ASP .NET


A DropDownList is also commonly known as combo box. It can contain multiple data members, but unlike a normal list box the users can choose only one value from this control. Though the functionality of this DropDownList is much like a Single Row Select List Box, a DropDownList can save a lot of GUI space as it is rendered on a Single line and is expanded only when the user clicks on the Control. This DropDownList is provided as a Server Control in ASP .Net like many other controls. This DropDownList can be used to add data manually or even for dynamic binding with data base. A simple declaration for DropDownList can be done as below. <asp:DropDownList ID="DropDownList1" runat="server" Height="47px" Width="73px"></asp:DropDownList> Properties Of DropDownList Control Properties BorderColor BorderStyle BorderWidth SelectedIndex Discription enables to get or set the border color of the web server control. [Not Applicable] enables to get or set the border style of the control. [Not Applicable] enables to get or set the border width for the control. [Not Applicable] enables to get or set an Integer value to specify the zero-based index for the currently selected list item.

AppendDataBoundItems

AutoPostBack DataTextField DataTextFormatString DataValueField Items SelectedItem SelectedValue Text ValidationGroup

DataMember

DataSourceID

DataSourceObject DataSource CausesValidation

enables to get or set a Boolean value to indicate whether to clear the list items before binding the data to the control. enables to get or set a Boolean value that indicates whether to postback the web page when list item of DropDownList control is clicked. enables to get or set the name of the data source field that provides the text for the list items. enables to get or set the string formatting to control the text of each list item that is to be displayed. enables to get or set the name of the data source field that provides the value for the list items. enables to manage the list items of the DropDownList control. enables to get the currently selected list item in DropDownList control. enables to get the value property of selected list item that returns ListItem object enables to get or set the text for the control. enables to get or set the name of the group of controls to which it belongs to and causes validation when posts back to the server. enables to get or set the name of the list of data that the data-bound control binds to. The list of data items may have more than one data members. enables to get or set the ID of the DataSource control from which the data-bound control retrieves its list of data items. enables to get an object that implements the IDataSource interface and provides the access to the data items. enables to get or set the object from which the databound control retrieves its list of data items. enables to get or set a Boolean value to indicate whether to perform the validation when any list item of the control is clicked.

Events SelectedIndexChanged: Occurs when selected item of list control changes between postbacks to the server. TextChanged: Occurs when Text and SelectedValue properties change between postbacks to the server. Example:

.CS Code:

protected void Page_Load(object sender, EventArgs e) { if (!Page.IsPostBack) { DropDownList1.Items.Add("pototo"); DropDownList1.Items.Add("Tamato"); DropDownList1.Items.Add("brinjal"); DropDownList1.Items.Add("Lime"); DropDownList1.Items.Add("Pea"); /////////////////////////////////////////////// DropDownList2.Items.Add("Jeans"); DropDownList2.Items.Add("Shirt"); DropDownList2.Items.Add("Cap"); DropDownList2.Items.Add("Blaser"); DropDownList2.Items.Add("Tie"); ////////////////////////////////////////////////// DropDownList3.Items.Add("Lather"); DropDownList3.Items.Add("Canvas"); DropDownList3.Items.Add("Sports"); DropDownList3.Items.Add("Sandle"); DropDownList3.Items.Add("Sleeper"); ///////////////////////////////////////////// DropDownList4.Items.Add("Fan"); DropDownList4.Items.Add("TybeLight"); DropDownList4.Items.Add("Plug"); DropDownList4.Items.Add("Holder"); DropDownList4.Items.Add("Wire"); }

protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e) { ListBox1.Items.Add("Vegitables:" + DropDownList1.SelectedItem.Text); //DropDownList1.Items.Clear(); } protected void ListBox1_SelectedIndexChanged(object sender, EventArgs e) { } protected void DropDownList2_SelectedIndexChanged(object sender, EventArgs e) { ListBox1.Items.Add("Cloths:" + DropDownList2.SelectedItem.Text); } protected void DropDownList3_SelectedIndexChanged(object sender, EventArgs e) { ListBox1.Items.Add("Showes:" + DropDownList3.SelectedItem.Text); } protected void DropDownList4_SelectedIndexChanged(object sender, EventArgs e) { ListBox1.Items.Add("Electronics:" + DropDownList4.SelectedItem.Text); }

How to Bind Data in DropDownList


Here I used a DropDownList in which on the load of form the Name value will come from a purchase table.In fetching data from database in a DropDownList we have to set a property of DropDownList like as. DroplistData.DataTextField = "Name"; In DropDownList we can fetch only one column value at a time. Firstly we designed a form where I used a DopDownList. In which all value of one selected column will come. Example:

.aspx Code:

<td class="style2"> <asp:DropDownList ID="DropDownList2" runat="server" Height="25px" Width="160px"> </asp:DropDownList> </td>

.CS Code:

public void bindgrid() { OleDbConnection con; OleDbDataAdapter da; con = new OleDbConnection("provider=microsoft.jet.oledb.4.0;Data source=D:\\invent.mdb"); da = new OleDbDataAdapter("select * from purchase", con); //DataTable dt = new DataTable(); DataSet ds = new DataSet(); da.Fill(ds); DropDownList1.DataSource = ds.Tables[0]; DropDownList1.DataTextField = "ship_location"; DropDownList1.DataBind(); for (int i =0;i < DropDownList1.Items.Count ;i++ ) { DropDownList1.Items[i].Attributes.Add("style", "color:" + ds.Tables[0].Rows[i]["categorycolor"].ToString()); } } protected void Page_Load(object sender, EventArgs e) { bindgrid(); }

ListBox Control in ASP.NET

The ASP.Net ListBox control provides the functionality to display a list of items in the form of menu that allows single or multiple items selection. You can select the multiple list items of ListBox control by changing their selected state. The selected items of ListBox return the Boolean type result as true or false that determine the selected state of an individual list item or multiple list items based on the C# code logic applied on it. If the list item is in selected state then it returns true and if it is in un-selected state then the associated list item returns false. You can use the ASP.Net ListBox web server control to get the user input as multiple items selected under a specific group. A simple example of ListBox control is displaying a list of items to display country, state or cities that can be used to select multiple locations to search any desired object based on filter criteria specified by using multiple selection of items of ListBox controls. Properties: Rows: The number of rows displayed in the list. SelectionMode: Allows single or multiple selections. Items: The collections of items in the list. ForeColor: Color of the text within the control. For example: Drag the control ListBox and a Button on the form and select ListBox control property items to add the items in list. Such as:

Handling ListBox Control Events : The SelectedIndexChanged event in the ListBox class is fired whenever the SelectedIndex in the ListBox changes as and when your web page postbacks to the Web Server. In order for the Postback to happen when the user select the values of the ListBox, you need to set the property AutoPostBack = true

private void lstBox_SelectedIndexChanged(object sender,System.EventArgs e) { Response.write(lstBox.SelectedItem.Value); }

Example:

.aspx Code:

<%@ Page Language="C#" AutoEventWireup="true" Codevirtual="simple databinding.aspx.cs" Inherits="simple_databinding" %>

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

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

<title>Untitled Page</title> <style type="text/css"> .style1 { width: 25%; border: 1px solid #000080; background-color: #FFCC99; height: 112px; } .style2 { width: 689px; } .style3 { width: 40px; } </style> </head> <body> <form id="form1" runat="server"> <div>

<table class="style1"> <tr> <td colspan="2"> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbs p;&nbsp; Registration Form</td> </tr> <tr> <td class="style3"> Name</td> <td class="style2"> <asp:TextBox ID="TextBox1" runat="server" Height="18px" Width="154px"></asp:TextBox> </td> </tr> <tr> <td class="style3"> Location</td> <td class="style2"> <asp:DropDownList ID="DropDownList1" runat="server" Height="25px" Width="158px"> </asp:DropDownList> </td> </tr> <tr>

<td class="style3"> CollegeList</td> <td class="style2"> <asp:DropDownList ID="DropDownList2" runat="server" Height="25px" Width="160px"> </asp:DropDownList> </td> </tr> <tr> <td class="style3"> Qualification</td> <td class="style2"> <asp:ListBox ID="ListBox1" runat="server" AutoPostBack="True" Height="202px" onselectedindexchanged="ListBox1_SelectedIndexChanged" SelectionMode="Multiple" Width="154px"></asp:ListBox> </td> </tr> <tr> <td class="style3"> <asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Show Detail" /> </td> <td class="style2">

<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label> </td> </tr> <tr> <td class="style3"> &nbsp;</td> <td class="style2"> &nbsp;</td> </tr> </table>

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

.CS Code:

public void bindgrid() //databinding In dropdownList1 {

OleDbConnection con;

OleDbDataAdapter da;

con = new OleDbConnection("provider=microsoft.jet.oledb.4.0;Data source=D:\\invent.mdb");

da = new OleDbDataAdapter("select * from purchase", con); //DataTable dt = new DataTable(); DataSet ds = new DataSet(); da.Fill(ds);

DropDownList1.DataSource = ds.Tables[0];

DropDownList1.DataTextField = "ship_location"; DropDownList1.DataBind();

for (int i = 0; i < DropDownList1.Items.Count; i++) { DropDownList1.Items[i].Attributes.Add("style", "color:" + ds.Tables[0]. Rows[i]["categorycolor"].ToString()); }

public void bindlist() { {

//databinding In dropdownList2

OleDbConnection con;

OleDbDataAdapter da;

con = new OleDbConnection("provider=microsoft.jet.oledb.4.0;Data source=D:\\invent.mdb");

da = new OleDbDataAdapter("select * from collegeList ", con); //DataTable dt = new DataTable(); DataSet ds = new DataSet(); da.Fill(ds);

DropDownList2.DataSource = ds.Tables[0];

DropDownList2.DataTextField = "colname"; DropDownList2.DataBind(); }

protected void Page_Load(object sender, EventArgs e) { bindgrid();// calling function for dropdownlist1

bindlist(); // calling function for dropdownlist2

//

Bind data in Listbox

if (!Page.IsPostBack) {

ListBox1.Items.Add("MCA"); ListBox1.Items.Add("M.TECH"); ListBox1.Items.Add("MBA"); ListBox1.Items.Add("B.TECH"); ListBox1.Items.Add("BCA"); ListBox1.Items.Add("BBA"); ListBox1.Items.Add("PGDCA");

string loc=""; protected void Button1_Click(object sender, EventArgs e) {

for (int i = 0; i < ListBox1.Items.Count; i++) { if (ListBox1.Items[i].Selected == true) { loc += ListBox1.Items[i].Text + "<br>"; }

// Select Multiple items from Listbox

Label1.Text = "Course::" + " " + loc + "Name::" + TextBox1.Text + "" + "<br>" + "Location::" + DropDownList1.SelectedItem.Text + "<br>" + "College Name::" + DropDownList2.SelectedItem.Text; ; } CheckBox in ASP.NET
It is used to select the Boolean value true or false, but not the multiple selections. The CheckBox control creates a check box on the Web Forms page that allows the user to switch between a true or false state. You can specify the caption to display in the control by setting the Text property. The caption can appear either on the right or left of the check box. Set the TextAlign property to specify the side that the caption appears on. Note Because the <asp:CheckBox> element has no content, you can close the tag with /> instead of using a separate closing tag.

To determine whether the CheckBox control is checked, test the Checked property. The CheckedChanged event is raised when the state of the CheckBox control changes between posts to the server. You can provide an event handler for the CheckedChanged event to perform a specific task when the state of the CheckBox control changes between posts to the server. Note: When creating multiple CheckBox controls, you can also use the CheckBoxList control. The CheckBoxList control is easier to use for creating a set of check boxes using data binding, while the individual CheckBox control gives you greater control over layout. By default, the CheckBox control does not automatically post the form to the server when it is clicked. To enable automatic posting, set the AutoPostBack property to true. Properties Property AutoPostBack CausesValidation Checked InputAttributes LabelAttributes runat Text TEXTALIGN ValidationGroup OnCheckedChanged Example: Output: Description Specifies whether the form should be posted immediately after the Checked property has changed or not. Default is false Specifies if a page is validated when a Button control is clicked Specifies whether the check box is checked or not Attribute names and values used for the Input element for the CheckBox control Attribute names and values used for the Label element for the CheckBox control Specifies that the control is a server control. Must be set to "server" The text next to the check box On which side of the check box the text should appear (right or left) Group of controls for which the Checkbox control causes validation when it posts back to the server The name of the function to be executed when the Checked property has changed

.aspx Code: <%@ Page Language="C#" AutoEventWireup="true" Codevirtual="Checkbox.aspx.cs" Inherits="Checkbox" %> "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title>Untitled Page</title> <style type="text/css"> .style1 { width: 34%; height: 520px; border: 4px solid #000080; background-color: #FFFF99; } .style2

} .style3 { height: 23px; width: 43px; } .style4 { height: 21px; width: 43px; } .style5 { width: 176px; } .style6 { height: 23px; width: 176px; } .style7 { height: 21px; width: 176px; } .style8 { height: 133px; width: 176px; } .style9 { width: 43px; } .style10 { width: 49px; } .style11 { height: 23px; width: 49px; } .style12 { height: 21px; width: 49px; } .style13 {

height: 133px; width: 43px;

height: 133px; width: 49px; } </style> </head> <body> <form id="form1" runat="server"> <div> <table class="style1"> <tr> <td class="style5"> Subject</td> <td class="style9"> Fees</td> <td class="style10"> &nbsp;</td> </tr> <tr> <td class="style5"> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Name&nbsp;</td> <td class="style9"> <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox> </td> <td class="style10"> &nbsp;</td> </tr> <tr> <td class="style5"> <asp:CheckBox ID="CheckBox1" runat="server" Text="C" /> </td> <td class="style9"> <asp:Label ID="Label1" runat="server" Text="1000"></asp:Label> </td> <td class="style10"> &nbsp;</td> </tr> <tr> <td class="style6"> <asp:CheckBox ID="CheckBox2" runat="server" Text="C++" /> </td> <td class="style3"> <asp:Label ID="Label2" runat="server" Text="1500"></asp:Label> </td> <td class="style11"> &nbsp;</td> </tr> <tr> <td class="style6"> <asp:CheckBox ID="CheckBox3" runat="server" oncheckedchanged="CheckBox3_CheckedChanged" Text="JAVA" /> </td> <td class="style3">

<asp:Label ID="Label3" runat="server" Text="3500"></asp:Label> </td> <td class="style11"> &nbsp;</td> </tr> <tr> <td class="style7"> <asp:CheckBox ID="CheckBox4" runat="server" Text="ORACLE" /> </td> <td class="style4"> <asp:Label ID="Label4" runat="server" Text="2000"></asp:Label> </td> <td class="style12"> &nbsp;</td> </tr> <tr> <td class="style5"> <asp:CheckBox ID="CheckBox5" runat="server" oncheckedchanged="CheckBox5_CheckedChanged" Text="COMPLETE .NET" /> </td> <td class="style9"> <asp:Label ID="Label5" runat="server" Text="1200"></asp:Label> </td> <td class="style10"> &nbsp;</td> </tr> <tr> <td class="style5"> <asp:CheckBox ID="CheckBox6" runat="server" Text="C#" /> </td> <td class="style9"> <asp:Label ID="Label6" runat="server" Text="1000"></asp:Label> </td> <td class="style10"> &nbsp;</td> </tr> <tr> <td class="style5"> <asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Calculate Fees" /> </td> <td class="style9"> &nbsp;</td> <td class="style10"> &nbsp;</td> </tr> <tr> <td class="style8"> &nbsp;</td> <td class="style2"> <asp:Label ID="Label7" runat="server" Text="Label"></asp:Label> </td>

<td class="style13"> </td> </tr> </table> </div> </form> </body> </html> .CS Code:

int p, q, r, s, t, u; protected void Button1_Click(object sender, EventArgs e) { if (CheckBox1.Checked == true) { p = Int32.Parse(Label1.Text); } if (CheckBox2.Checked == true) { q = Int32.Parse(Label2.Text); } if (CheckBox3.Checked == true) { r = Int32.Parse(Label3.Text); } if (CheckBox4.Checked == true) { s = Int32.Parse(Label4.Text); } if (CheckBox5.Checked == true) { t = Int32.Parse(Label5.Text); } if (CheckBox6.Checked == true) { u = Int32.Parse(Label6.Text); } int k = p + q + r + s + t + u; Label7.Text ="MR.." +TextBox1.Text +"<br>"+ "Your Total Fees::" +k.ToString(); }

CheckListBox Control in ASP.NET


The ASP.NET CheckBoxList control is used to create a defined list of options in which a user can choose from. With this control, you can select one item or multiple items. Each selectable item in a CheckBoxList control is considered a ListItem element. This control can

be loaded manually through ASP.NET code (like my example) as well as from a data source. The CheckBoxList control is part of the System.Web.UI.WebControls namespace. Important Properties: SelectedValue SelectedIndex SelectedItem TextAlign DataTextField Gets the value of first selected item. Gets or Sets the index of the first selected item. Gets the first selected item Gets or Sets the alignment of the checkbox text. Name of the data source field to supply the text of the items. (No need to set when you are adding items directly into .aspx page.) Name of the data source field to supply the value of the items. (No need to set when you are adding items directly into .aspx page.) ID of the datasource component to provide data. (Only used when you have any DataSource component on the page, like SqlDataSource, AccessDataSource etc.) The datasource that populates the items in the checkoxlist box. (Generally used when you are dynamically generating the items from Database.) true/false. If true, the form is automatically posted back to the server when user click any of the checkbox. It will also fire OnSelectedIndexChanged method. true/false. If true, the statically added item (added from .aspx page) is maintained when adding items dynamically (from code behind file) or items are cleared. Method name that fires when user click any of the checkbox in the list. (Fires only when AutoPostBack=true.) Gets the colleciton of the items from the list. table/flow. Gets or Sets the layout of the chekboxes when rendered to the page. Gets or Sets the no. of columns to display when the control is rendered. Horizontal/Vertical. Gets or Sets the the value to indicate whether the control will be rendered horizontally or vertically.

DataValueField

DataSourceID

DataSource

AutoPostBack

AppendDataBoundItems OnSelectedIndexChanged Items RepeatLayout RepeatColumns RepeatDirection

Example: Output:

.aspx Code: %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title>Untitled Page</title> .style1 { width: 17%; height: 380px; border: 1px solid #800000; background-color: #FFFF99; } .style2 { height: 374px; background-color: #66CCFF; } .style3 { height: 374px; width: 139px; background-color: #66CCFF;

} .style4 { width: 10px; } </style> </head> <body> <form id="form1" runat="server"> <div> <table class="style1"> <tr> <td colspan="2"> &nbsp;CheckBoxList&nbsp; Control&nbsp;</td> </tr> <tr> <td class="style2"> <br /> <br /> <br /> <br /> &nbsp;&nbsp; BIG BAZAR<asp:CheckBoxList ID="CheckBoxList1" runat="server" Width="109px"> <asp:ListItem>Jeans</asp:ListItem> <asp:ListItem>Shirt</asp:ListItem> <asp:ListItem>cap</asp:ListItem> <asp:ListItem>Blaser</asp:ListItem> <asp:ListItem>Tie</asp:ListItem> <asp:ListItem>Shocks</asp:ListItem> </asp:CheckBoxList> </td> <td class="style4"> <asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Show Items" /> </td> <td class="style3"> <asp:Label ID="Label1" runat="server" BackColor="White" ForeColor="#CC3300" Text="Label"></asp:Label> </td> </tr> </table> </div> </form> </body> </html> .CS Code:

string loc = ""; protected void Button1_Click(object sender, EventArgs e) { for (int i = 0; i < CheckBoxList1.Items.Count; i++) { if (CheckBoxList1.Items[i].Selected == true) { loc += CheckBoxList1.Items[i].Text + "<br>"; } } Label1.Text = "Items::" + " " + loc; }

RadioButton Control in ASP.NET


RadioButton control is used to give single select option to the user from multiple items. When it is rendered on the page, it is implemented through <input type=radio></input> HTML tag. Its properties like BackColor, ForeColor, BorderColor, BorderStyle, BorderWidth, Height etc. are implemented through style properties of <input>. Importent Properties: AutoPostBack CausesValidation Checked OnCheckedChanged ValidationGroup Form is automatically posted back when Radio button selection is changed. true/false. If true, Form is validated if Validation control has been used in the form. true/false. If true, Radio button is selected by default. Fires when Radio button selection changes. This works only if AutoPostBack property is set to true. Used to put a radio button under a particular validation group. It is used when you have many set of form controls and by clicking a paricular button you want to validate a particular set of controls only. It is used a group a set of radion buttons so only one of them can be selected at a time.

GroupName

Event: CheckedChanged Event: It enables you to handle the PostBack event of radiobutton control when user changes its state from selected state. When user clicks the radio button it raises the CheckedChanged event only if the AutoPostBack property of RadioButton control is set to true

Example: Output:

.CS Code:

protected void Button3_Click(object sender, EventArgs e) { if (RadioButton1.Checked == true) { Label2.Text = "Your Answer is Wrong"; } if (RadioButton2.Checked == true) { Label2.Text = "Your Answer is Wrong"; } if (RadioButton3.Checked == true) { Label2.Text = "Your Answer is Right "+"<br>"+"Yow win $100"; } if (RadioButton4.Checked == true) { Label2.Text = "Your Answer is Wrong"; } }

RadioButtonlist Control in ASP.NET


RadioButtonList Control is used for selecting one predefined (available in RadioButtonList) value. That means user can be able to select only one a time. For e.g.., it is useful for selecting the User Sex , Highest Qualification etc., ASP.NET RadioButtonList itself is a class like other controls which are present under System.Web.UI.WebControls namespace.

Important Properties AutoPostBack - Accept Boolean Value - If True, then page will submit to the server if the index of the Radiobutton is changed CausesValidation - Accept Boolean Value - Used to Validate the page when RadioButton click event fires. DataTextField - Accept String Value - Used to set the column Name from the DataSource which user Can see (eg., Name). DataValueField - Accept String Value - Used to set the column Name from the DataSource which user Can not see (eg., ID). Enabled - Accept Boolean Value- Used to Get/Set Radio button Enabled Height - Accept IntergerValue - Used to Set/Get height of the RadioButton RepeatColumns - Accept Interger Value - Used to set how Many RadioButtons you want to display in one line. RepeatDirection - Enumerator - "Vertical" or "Horizontal" Width - Accept IntergerValue - Used to set the width of the RadioButton Events : DataBound - This event will fire when you call the assigned dataSource property and you write this line of code to bind your RadioButtonList myRadioButtonList.DataBind(); SelectedIndexChanged - This event will fire when user has changed his/her selection and RadioButtonList's "AutoPostBack" property is set to true; Example: Output:

.CS Code:

protected void Page_Load(object sender, EventArgs e) { if(!Page.IsPostBack) { RadioButtonList1.Items.Add("Salman Khan"); RadioButtonList1.Items.Add("Sharukh Khan"); RadioButtonList1.Items.Add("Amir Khan"); RadioButtonList1.Items.Add("Hritik"); RadioButtonList1.Items.Add(" Ajay Devgan"); RadioButtonList1.Items.Add(" Ranveer kapoor"); RadioButtonList1.Items.Add("Akshay Kumar"); RadioButtonList1.Items.Add("Sahid kapoor"); RadioButtonList1.Items.Add("Sanjay Dutt"); } } protected void Button1_Click(object sender, EventArgs e) { Label1.Text ="Your Favrouite Actor::> "+ RadioButtonList1.SelectedItem.Text; }

Image Control in ASP.NET

ASP.Net 2.0 Image control provides the functionality to display images on ASP.Net web page. The image server control renders using HTML img tag in the web browser. As a web server control it can be accessed at server side that enables you to set the images dynamically using C# code or by specifying the image URL retrieved from SQL database table. It provides properties similar to HTML img tag that allow you to set the path of image file that you want to display on web page along with its alignment and alternate text properties that render as attributes of HTML img tag in the web browser. You can get or set these properties at design time as well as using C# code programmatically. The ASP.Net image control allows you to display the images only for design purposes or as a part of the page content but does not support any server events to execute the server side code if a user clicks on it or moves the mouse over it. Properties:

1. AlternateText: You can specify the text value for this property that appears as
tooltip for the displayed image in the web browsers. All web browsers do not support this property to display the text as tooltip. The web browsers display this alternate text value if the specified image does not load for any reason like unreachable or unavailable at that time. This property renders as alt attribute of img tag. DescriptionUrl: You can specify the URL of the web page containing the full description regarding the image. GenerateEmptyAlternateText: It is a Boolean type property that allows or disallows to generate the empty alt attribute while rendering the image control. ImageAlign : It enables you to specify the alignment of image as a part of inline content or web page elements. ImageUrl :You can specify the URL of the image that you want to display on the web page. ToolTip: It enables you to specify the tooltip text for the image control. The tooltip property generates the title attribute of img tag that appears as tooltip in some browsers.

2. 3. 4. 5. 6.

Apart from these properties there some other CSS based properties that enable you to set the border, background color, height and width of the image. The CSS based properties include: BackColor, BorderColor, BorderStyle, BorderWidth, CssClass, Height and Width that allow you to customize the appearance of image. Syntax: <asp:Image ID="Image1" runat="server" Height="215px" ImageUrl="~/Images/Sunset.jpg" /> Example:

Design:

ImageMap Control in ASP.NET


ImageMap control is used to create an image that contains clickable hotspot region. When user click on the region, the user is either sent to a URL or a sub program is called Imagemap. When it is rendered on the page, it is implemented through <img /> HTML tag. Hot spots features: o o o o o There is no limit on number of hotspots each image may contain. Each hotspot is characterized by various attributes like shape, location and size. Overlapping hotspots are perfectly valid. Hot spots are defined using x and y coordinates. Hot spots can be assigned Image URL's and are capable of postback.

Different types of hot spots: There are three different types of hot spots offered by ImageMap control. They are: o o o CircleHotspot RectangleHotspot PolygonHotspot

CircleHotspot: CircleHotspot defines circle shaped hot spot region in an ImageMap control. To define the region for a circle hot spot, we should define X and Y coordinates for circle as well as radius property which usually is the distance from the center of circle to the edge. RectangleHotspot: RectangleHotspot defines rectangle shaped hot spot region in an ImageMap control. To define the region for a Rectangle hot spot, we define Top, Bottom, Left and Right coordinates. Similar is the case for the Polygon hot spot Rightclick On Imagemap Control :

Example:

if you click the left side of the image you see below image

. if you click the Right side of the image you see below image

Calendar control In ASP.net


This control displays a one-month calendar that allows the user to select dates and move to the next and previous months. Properties: Property Description DayHeaderStyle The style for displaying the names of the days DayNameFormat The format for displaying the names of the days. Can take one of the following values:

FirstLetter FirstTwoLetters Full

Short SelectMonthText The text displayed for the month selection link SelectWeekText The text displayed for the week selection link The format for the title of the calendar. Can take one of the following values: TitleFormat Month

MonthYear TodaysDate Today's date VisibleDate The date that specifies the month that is currently visible in the calendar WeekendDayStyle The style for weekends

Here I show how we can use Calendar control in asp.net. Create a web form name Calendar.aspx, and then add a Calendar control and TextBox control. Here we use OnSelectionChanged event in calendar control. When someone selects a date from Calendar, the TextBox control shows the selected date. .ASPX Code:

<asp:TextBox ID="TextBox1" runat="server" Height="32px" Width="234px"></asp:TextBox> asp:Calendar ID="Calendar1" runat="server" BorderColor="#FFCC99" > "BorderStyle="Dashed "onselectionchanged="Calendar1_SelectionChanged SelectedDate="2010-11-01" ToolTip="Please </ "Select Date"> <TitleStyle BackColor="#FFFFCC <asp:Calendar />

.CS Code:

protected void Calendar1_SelectionChanged(object sender, EventArgs e) { TextBox1.Text = Calendar1.SelectedDate.ToLongDateString();//To display date in TextBox }

Output:

FileUpload Control in ASP.net


Finally ASP.NET 2.0 has a FileUpLoad control, which allows developers to drop the control on a page and let it browse a file and upload it on the server. To create a control, simply drop the FileUpload control from Toolbox to a Web page. .ASPX CODE

<asp:FileUpload ID="FileUpload1" runat="server" /> <asp:Label ID="Label1" runat="server" BackColor="White" Text="Label"></asp:Label> <asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Submit" />

.CS CODE

protected void Button1_Click(object sender, EventArgs e) {

if (FileUpload1.HasFile) { FileUpload1.SaveAs(@"D:\temp\" +FileUpload1.FileName); Label1.Text = "File Uploaded: " + FileUpload1.FileName +" "+System.DateTime.Now.ToLongDateString(); } else { Label1.Text = "No File Uploaded."; }

OUTPUT:

After Click on Submit Button file Saved in Folder Temp

Wizard control in ASP.NET


The Wizard control is a perfect fit when you need to develop a web site that requires multiple steps to collect and display the data. Advantages of using a Wizard Control * * * * A header for the title of a particular step A sidebar for left bar navigation collection of steps types of steps

Wizard Layout

A Header appears at the top of each WizardStep display. The easiest way to display a common heading is by coding the Wizards Header Text property as is done above. If no header is provided, none is displayed. A Sidebar menu appears along the left side of the display. It presents a menu of links to the Wizard Steps that comprise the sequence of page displays. A Side Bar is optional and can be suppressed by coding the Wizards DisplaySideBar="False" property. The Side Bar is centered vertically within the total height of the Wizard. .ASPX CODE

Download ASPX CODE .CS Code

using using using using using using using using using using using using

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

public partial class Wizard : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { Label2.Visible = false; Label3.Visible = false; Label4.Visible = false; Label5.Visible = false; // Wizard1.Visible = false; } protected void Button1_Click(object sender, EventArgs e) { if (TextBox1.Text == "ashish" && TextBox2.Text == "gupta") { Label1.Text = "Login Are successfully";

} else Label1.Text = "username And password wrong"; } protected void Button3_Click(object sender, EventArgs e) { Label2.Text = "Name:" + "" + TextBox3.Text; Label3.Text = " Father Name:" + "" + TextBox4.Text; Label4.Text = "Address:" + "" + TextBox5.Text; Label5.Text = "phone no:" + "" + TextBox6.Text; Label2.Visible = true; Label3.Visible = true; Label4.Visible = true; Label5.Visible = true; } }

OUTPUT: 1.LOGIN PAGE

2.REGISTRATION

3.Contact Us

The ASP.NET DataList Control


The DataList control like the Repeater control is a template driven, light weight control, and acts as a container of repeated data items. The templates in this control are used to define the data that it will contain. It is flexible in the sense that you can easily customize the display of one or more records that are displayed in the control. You have a property in the DataList control called RepeatDirection that can be used to customize the layout of the control. The RepeatDirection property can accept one of two values, that is, Vertical or Horizontal. The RepeatDirection is Vertical by default. However, if you change it to Horizontal, rather than displaying the data as rows and columns, the DataList control will display them as a list of records with the columns in the data rendered displayed as rows. the DataList control as a combination of the DataGrid and the Repeater controls. You can use templates with it much as you did with a Repeater control and you can also edit the records displayed in the control, much like the DataGrid control of ASP.NET. The next section compares the features of the three controls that we have mentioned so far, that is, the Repeater, the DataList, and the DataGrid control of ASP.NET. When the web page is in execution with the data bound to it using the Page_Load event, the data in the DataList control is rendered as DataListItem objects, that is, each item displayed is actually a DataListItem. Similar to the Repeater control, the DataList control does not have Paging and Sorting functionalities build into it. Using the DataList Control: To use this control, drag and drop the control in the design view of the web form onto a web form from the toolbox. Refer to the following screenshot, which displays a DataList control on a web form:

DataList Control Contain Following Templates: 1. 2. 3. 4. 5. 6. 7. ItemTemplate AlternatingItemTemplate EditItemTemplate FooterTemplate HeaderTemplate SelectedItemTemplate SeparatorTemplate

Here is a sample of how your DataList control's templates are arranged:

< asp:DataList id="dlEmployee" runat="server"> <HeaderTemplate> ... </HeaderTemplate> <ItemTemplate> ... </ItemTemplate> <AlternatingItemTemplate> ... </AlternatingItemTemplate> <FooterTemplate> ... </FooterTemplate> </asp:DataList>

Output:

.aspx Code:

<asp:DataList ID="DataList1" runat="server"> <HeaderTemplate> <table border="1"> <tr> <th> Item Name

</th> <th> Tax </th> <th> Location </th> <th> Issue Date </th> </tr> </HeaderTemplate> <ItemTemplate> <tr bgcolor="#0xbbbb"> <td> <%# DataBinder.Eval(Container.DataItem, "purchase1")%> </td> <td> <%# DataBinder.Eval(Container.DataItem, "tax")%> </td> <td> <%# DataBinder.Eval(Container.DataItem, "ship_location")%> </td> <td> <%# DataBinder.Eval(Container.DataItem, "issue_date")%> </td> </tr> </ItemTemplate> <FooterTemplate> </FooterTemplate> </asp:DataList>

.CS CODE:

public void bindgrid() { OleDbConnection con; OleDbDataAdapter da; con = new OleDbConnection("provider=microsoft.jet.oledb.4.0;Data source=D:\\invent.mdb"); da = new OleDbDataAdapter("select * from purchase", con);

//DataTable dt = new DataTable(); DataSet ds = new DataSet(); da.Fill(ds); DataList1.DataSource = ds.Tables[0]; DataList1.DataBind();

Detailview in ASP.NET
The DetailsView is a control that is complementary to the GridView control. It has been introduced in ASP.NET 2.0 to provide an ability to work with a single record or row from an associated data source. The default view of this control is vertical with each column of the record displayed on a line of its own. It is used for updating and inserting new records and used often in the Master-details scenario where the details of the record selected in the master is displayed in detail. The DetailsView, like the GridView rides on the data source capabilities to update, insert or delete rows. It renders a single data item at a time even when the data source exposes more items. If the data object represents the ICollection interface or the underlying data source exposes the paging operation, the DetailsView can page over the data, provided the AllowPaging property is set to true. Users can also navigate between rows of data using this control. The process of binding the DetailsView control to a data source is very simple. The DataSourceID property can be set declaratively or programmatically. The AutoGenerateEditButton property, if set to True, enables editing operations and the DetailsView renders the edit button in addition to the other columns in the control. The Edit mode can be invoked pressing this button. The Edit user interface can be customized using Styles, DataControlField objects and templates. The DetailsView control can be configured to display a Delete and insert button also. The AutoGenerateInsertButton, when set to true, generates a New button. The new button invokes the insert mode and appropriate user interfaces are rendered including the fields in the DataKeyNames collection. Using this collection the data source control can locate the unique row to be updated. The DetailsView control user interface can be customized using Style properties such as HeaderRowStyle, RowStyle, AlternatingRowStyle and so on. Templates also can be used to customize this control. EmptyDataTemplate, HeaderTemplate, FooterTemplate and PagerTemplate are some of the templates available for this control. A number of events can be used to customize the code including pre and post insert, update and delete data source events. This includes ItemCreated and ItemCommand events. There

is no selected event in the DetailsView control as the current event is treated as the selected event. DetailsView Fields in ASP.Net The DetailView control supports the following Fields Displays the value of a data item as text Displays the value of the data item as a check box

BoundField CheckBoxField

CommandField

Displays links for editing, deleting and selecting rows

ButtonField

Displays the value of a data item as a button, imagebutton, linkbutton Displays the value of a data item as a link

HyperlinkField

ImageField

Displays the value of a data item as an image

TemplateField

Customize the appearance of a data item

Example:

.aspx Code: <asp:DetailsView ID="DetailsView1" runat="server" BackColor="White" BorderColor="#DEDFDE" BorderStyle="None" BorderWidth="1px" CellPadding="4" ForeColor="Black" GridLines="Vertical" Height="229px" onpageindexchanging="DetailsView1_PageIndexChanging" Width="399px" AllowPaging="True" AutoGenerateRows="False"> <FooterStyle BackColor="#CCCC99" /> <RowStyle BackColor="#F7F7DE" /> <PagerStyle BackColor="#F7F7DE" ForeColor="Black" HorizontalAlign="Right" /> <Fields> <asp:BoundField DataField="tax" HeaderText="Tax" /> <asp:BoundField DataField="ship_location" HeaderText="Location" /> <asp:BoundField DataField="issue_date" HeaderText="Date" /> </Fields><HeaderStyle BackColor="#6B696B" Font-Bold="True" ForeColor="White" /> <EditRowStyle BackColor="#CE5D5A" Font-Bold="True" ForeColor="White" /> <AlternatingRowStyle BackColor="White" /> </asp:DetailsView> .CS CODE: public void bindgrid { OleDbConnection con; OleDbDataAdapter da; con = new OleDbConnection("provider=microsoft.jet.oledb.4.0;Data source=D:\\invent.mdb"); da = new OleDbDataAdapter("select purchase1,tax,issue_date,ship_location from purchase", con); //DataTable dt = new DataTable(); DataSet ds = new DataSet(); da.Fill(ds); DetailsView1.DataSource= ds.Tables[0]; DetailsView1.DataBind(); //for (int i = 0; i < DropDownList1.Items.Count; i++) //{ // DropDownList1.Items[i].Attributes.Add("style", "color:" + ds.Tables[0]. Rows[i]["categorycolor"].ToString()); //} }

protected void Page_Load(object sender, EventArgs e) { bindgrid(); }

Formview Control in ASP.NET


FormView is the new feature in the ASP.NET 2.0, for display the data in the FormView control; we use the Eval method in the ItemTemplate. You must create a Template for the mode in which the FormView control is configured. For example, a FormView control that supports updating records must have an EditItemTemplate defined. Types of Templates: HeaderTemplate FooterTemplate ItemTemplate InsertItemTemplate EditItemTemplate EmptyDataTemplate PagerTemplate

HeaderTemplate: Header Template defines the contents which we want to display in the header row of the FormView Control. FooterTemplate: Footer Template defines the contents which we want to display in the footer row of the FormView Control. ItemTemplate: ItemTemplates defines the contents for the FormView row when it is in read only mode. This template basically used for display the existing data from the data source. InsertItemTemplate: InsertItemTemplates defines the contents for the FormView row when it is in insert mode. This template contains the input controls and commands for inserting the new record. EditItemTemplate: EditItemTemplates defines the contents for the FormView row when it is in edit mode. This template contains the input controls and commands for editing the existing record. EmptyDataTemplate:

EmptyDataTemplate basically used for showing the alert to the user if there is no record in the bound column. PagerTemplate: PagerTemplate defines the content for the pager row when the "AllowPaging" property is true. It also contains the controls by using that, user can navigate to another record.

Output: .aspx Code:

<asp:FormView ID="FormViewStudent" runat="server" BackColor="White" BorderColor="#DEDFDE" BorderStyle="None" BorderWidth="1px" CellPadding="4" ForeColor="Black" GridLines="Vertical" Height="229px" <onpageindexchanging="FormViewStudent_PageIndexChanging <ItemTemplate> <table> <tr> <td align="right"> <b> ID:</b></td> <td> <%# Eval("ID") %> </td> </tr> <tr> <td align="right"> <b>Supplier Name:</b></td> <td> <%# Eval("supplier_name") %> </td> </tr> <tr> <td align="right">

<b>contact Person:</b></td> <td> <%# Eval("contact_person") %> </td> </tr> <tr> <td align="right"> <b>Address:</b></td> <td> <%# Eval("address") %> </td> </tr> </table> </ItemTemplate> </asp:FormView> .CS CODE:

public void bindformview() { OleDbConnection con; OleDbDataAdapter da; con = new OleDbConnection("provider=microsoft.jet.oledb.4.0;Data source=D:\\invent.mdb"); da = new OleDbDataAdapter("select ID,supplier_name,contact_person,address from supplier", con); //DataTable dt = new DataTable(); DataSet ds = new DataSet(); da.Fill(ds);

FormViewStudent.DataSource = ds.Tables[0]; FormViewStudent.DataBind(); } protected void Page_Load(object sender, EventArgs e) { bindformview(); }

Listview Control in ASP.NET


ListView is a new databound control that is shipped with ASP.Net 3.5. ListView control is similar to GridView, Repeater, and DataList which helps us to display a table of data with awesome additional features. We can use repeater control whenever we need to display the data in a custom format, as opposed to only tabular view in GridView control. The Repeater control lacks in certain features like edit, update and paging. Using GridView control it is possible to Edit/Update/Delete data but with a big limitation on the layout of the data display. There is no single control available in earlier versions of asp.net that accommodates all the above features. The introduction of ASP.Net 3.5 answers this with the new ListView control. ListView control can be thought as a hybrid between GridView and Repeater control. ListView control gives us more control on the rendered HTML output with edit/update/delete feature. Also, ListView control has a built in support for adding new row, sorting, etc Features of ListView Control: Can define our own template/Layout/Structure for the data display. Edit/Update/Delete capabilities on the data displayed. Built-in support for inserting new row. Built-in support for sorting Supports databinding via DataSource Controls including LINQ DataSource controls. Paging via DataPager control, which can be part of ListView control or can be kept outside the control. Means, DataPager can be kept at any part of page as opposed to GridView where the built-in paging is packed with the control itself. To start this tutorial you need to drag a ListView control on a Page and you need to add LayoutTemplate, ItemTemplate and SelectedItemTemplate as shown in the following code. Notice that the HTML markup in SelectedItemTemplate is almost identical to ItemTemplate with only one difference that I am changing the background and text color of the row in SelectedItemTemplate to give user visual clue that the item is selected. Also notice the LinkButton I am using in both templates. The CommandName of these buttons is set to Select which is required to enable selections in ListView.

The ListView control supports these templates Template Purpose

AlternatingItemTemplate Display alternating items with different markup to help viewers distinguish consecutive items. EditItemTemplate EmptyDataTemplate EmptyItemTemplate GroupTemplate InsertItemTemplate ItemSeparatorTemplate ItemTemplate LayoutTemplate Controls display when an item is in edit mode. Controls display when the ListView's data source returns no data. Controls the display for an empty item. Specifies a container object such as a table row, div, or span element for the content. Specifies content to render when users insert an item. Controls the content to display between individual items. Controls content to display for individual items. Specifies the root element that defines a container object, such as a table, div, or span element that surrounds content defined in the ItemTemplate or GroupTemplate. Specifies the content to display for the currently selected item.

GroupSeparatorTemplate Controls the content to display between groups of items.

SelectedItemTemplate Example: Output:

<asp:ListView ID="ListView1" runat="server" DataKeyNames="ID" OnSelectedIndexChanging="ListView1_SelectedIndexChanging" onselectedindexchanged="ListView1_SelectedIndexChanged"> <LayoutTemplate> <table style="border: solid 2px #336699;" cellspacing="0" cellpadding="3" rules="all"> <tr style="background-color: #336699; color: White;"> <th>Select</th> <th>Product ID</th> <th>Supplier Name</th> <th>Contact Person</th> <th>Address</th> </tr> <tbody> <asp:PlaceHolder ID="itemPlaceHolder" runat="server" /> </tbody> </table> </LayoutTemplate> <ItemTemplate> <tr> <td> <asp:LinkButton ID="lnkSelect" Text="Select" CommandName="Select" runat="server" /> </td> <td><%# Eval("ID")%></td> <td><%# Eval("supplier_name")%></td> <td><%# Eval("contact_Person")%></td> <td><%# Eval("address")%></td> </tr> </ItemTemplate> <SelectedItemTemplate> <tr style="background-color: #336699; color: White;"> <td> <asp:LinkButton ID="lnkSelect" Text="Select" CommandName="Select" runat="server" ForeColor="White" /> </td> <td><%# Eval("ID")%></td> <td><%# Eval("supplier_name")%></td> <td><%# Eval("contact_Person")%></td> <td><%# Eval("address")%></td> </tr> </SelectedItemTemplate> </asp:ListView> <br /> <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label> .CS CODE:

public void binddata() { OleDbConnection con; OleDbDataAdapter da; con = new OleDbConnection("provider=microsoft.jet.oledb.4.0;Data source=D:\\invent.mdb"); da = new OleDbDataAdapter("select ID,supplier_name,contact_person,address from supplier", con); //DataTable dt = new DataTable(); DataSet ds = new DataSet(); da.Fill(ds); ListView1.DataSource= ds.Tables[0]; ListView1.DataBind(); } protected void Page_Load(object sender, EventArgs e) { binddata(); } { protected void ListView1_SelectedIndexChanging(object sender, ListViewSelectEventArgs e) ListView1.SelectedIndex= e.NewSelectedIndex; string p = ListView1.SelectedDataKey.Value.ToString(); //string pid = ListView1.DataKeys[e.NewSelectedIndex].Value.ToString(); Label1.Text = "Selected Product ID: " + p; binddata(); }

Repeater Control in ASP.NET


Repeater control is a template based container control. you define layout for the Repeater control by creating different templates based on your needs. The Repeater control may be bound to a database table, an XML file, or another list of items. Here we will show how to bind data to a Repeater control.

A Repeater control is a light weight control which can be used for simple reporting purposes. It supports basic event-handling like Init, Load, Unload etc., This also supports some basic formatting of data and can be presented to the user. A Repeater control offers limited level of data editing or selecting capabilities. For such editing and updates ASP .Net offers DataList and DataGrid controls. Repeater control supports five templates which are as follows o o o o o ItemTemplate AlternatingItemTemplate HeaderTemplate FooterTemplate SeparatorTemplate

ItemTemplate: ItemTemplate defines how the each item is rendered from data source collection. AlternatingItemTemplate: AlternatingItemTemplates define the markup for each Item but for AlternatingItems in DataSource collection like different background color and styles. HeaderTemplate: HeaderTemplate will emit markup for Header element for DataSource collection FooterTemplate: FooterTemplate will emit markup for footer element for DataSource collection SeparatorTemplate: SeparatorTemplate will determine separator element which separates each Item in Item collection. Usually, SeparateTemplate will be <br> html element or <hr> html element. Example:

.aspx Code: <asp:Repeater ID="Repeater1" runat="server" onitemcommand="Repeater1_ItemCommand"> <HeaderTemplate> <table border="1" cellpadding="5" cellspacing="2"> <tr bgcolor="gray"> <td><b>Supplier Name</b> </td> <td><b>ContactPerson</b></td> <td><b>Address</b></td> </tr> </HeaderTemplate> <ItemTemplate> <tr> <td> <%#DataBinder.Eval(Container.DataItem, "supplier_name")%> </td> <td> <%#DataBinder.Eval(Container.DataItem, "contact_person")%> </td> <td> <%#DataBinder.Eval(Container.DataItem, "address")%> </td> </tr> </ItemTemplate> <AlternatingItemTemplate > <tr bgcolor="aqua" >

<td> <%#DataBinder.Eval(Container.DataItem, "supplier_name")%> </td> <td> <%#DataBinder.Eval(Container.DataItem, "contact_person")%> </td> <td> <%#DataBinder.Eval(Container.DataItem, "address")%> </td> </tr> </AlternatingItemTemplate> <FooterTemplate> </table> </FooterTemplate> </asp:Repeater> .CS CODE:

public void repeaterbinddata()

OleDbConnection con;

OleDbDataAdapter da;

con = new OleDbConnection("provider=microsoft.jet.oledb.4.0;Data source=D:\\invent.mdb"); da = new OleDbDataAdapter("select supplier_name,contact_person,address from supplier", con);

//DataTable dt = new DataTable();

DataSet ds = new DataSet();

da.Fill(ds);

Repeater1.DataSource= ds.Tables[0];

Repeater1.DataBind();

protected void Page_Load(object sender, EventArgs e)

repeaterbinddata();

DataPager Control in ASP.Net


ASP.NET 3.5 introduces a new control named as DataPager. It provides users to create interfaces for navigation through multiple pages containing multiple records within it. DataPager control can work with any control that supports IPageableItemContainer interface. In ASP.NET 3.5 ListView is one and the only control that supports this interface. The DataPager control is having some build in properties: PagedControlID: It is used to get or set the control to page. If the DataPager is inside the ListView, if you don't mention the PagedControlId it will take the ListView as the control to page. If your DataPager is outside of the ListView then you have to mention the PagedControlId to the id of the ListView. PageSize: It is used to get or set the number of data items to display in a page. StartRowIndex: It is used to get the index of the first item in a page. MaximumRow: You can use it to get the maximum number of rows to retrieve from the database for a page. TotalRowCount(read only): To get the total number of rows or items available in the datasource . Example: <asp:DataPager ID = "pager" runat = "server" PageSize = "10"> </asp:DataPager> Example: DataPager Control With ListView in ASP.NET: Output:

.aspx Code:

<asp:ListView ID="ListView1" runat="server" DataKeyNames="ID" OnSelectedIndexChanging="ListView1_SelectedIndexChanging" onselectedindexchanged="ListView1_SelectedIndexChanged"> <LayoutTemplate> <table style="border: solid 2px #336699;" cellspacing="0" cellpadding="3" rules="all"> <tr style="background-color: #336699; color: White;"> <th>Select</th> <th>Product ID</th> <th>Supplier Name</th> <th>Contact Person</th> <th>Address</th> </tr> <tbody> <asp:PlaceHolder ID="itemPlaceHolder" runat="server" /> </tbody> </table> //DATAPAGER CONTROL <asp:DataPager id="pg" PageSize="2" Runat="server"> <Fields> <asp:NumericPagerField /> </Fields> </asp:DataPager> </LayoutTemplate> <ItemTemplate> <tr> <td> <asp:LinkButton ID="lnkSelect" Text="Select" CommandName="Select" runat="server" /> </td> <td><%# Eval("ID")%></td> <td><%# Eval("supplier_name")%></td> <td><%# Eval("contact_Person")%></td>

<td><%# Eval("address")%></td> </tr> </ItemTemplate> <SelectedItemTemplate> <tr style="background-color: #336699; color: White;"> <td> <asp:LinkButton ID="lnkSelect" Text="Select" CommandName="Select" runat="server" ForeColor="White" /> </td> <td><%# Eval("ID")%></td> <td><%# Eval("supplier_name")%></td> <td><%# Eval("contact_Person")%></td> <td><%# Eval("address")%></td> </tr> </SelectedItemTemplate> </asp:ListView>

Navigation Control Example in ASP.NET


SiteMapPath Control: The SiteMapPath control is used to add a site map (breadcrumbs) to the website. A site map is a way to present all folders and pages of the website. Its properties like BackColor, ForeColor, BorderColor, BorderStyle, BorderWidth, Height etc. are implemented through style properites of <span/> tag. Generally current page reference is not rendered as a link, however, it can be made clickable by setting RenderCurrentNodeAsLink=true. Following are some important properties that are very useful PathSeparator NodeStyle CurrentNodeStyle RootNodeStyle PathSeparatorStyle Gets or sets Path separator text. (By default it is >.) Sets the style of all nodes that will be displayed. Sets the style on node that represent the current page. Sets the style on the absoulte root node. Sets the style of path separator.

The following sitemap file is used in this tutorial: <?xml version="1.0" encoding="utf-8" ?> <siteMap xmlns="http://schemas.microsoft.com/AspNet/SiteMap-File-1.0" > <siteMapNode url="" title="" description="">

<siteMapNode url="Default2.aspx" title="Home" description="" /> <siteMapNode url="Default3.aspx" title="About Us" description="" /> <siteMapNode url="Default.aspx.aspx" title="Product" description="" /> <siteMapNode url="Adrotator.aspx.aspx" title="Contact us" description="" /> </siteMapNode> </siteMap>

Rules for creating a sitemap file: The XML file must contain a <siteMap> tag surrounding the content The <siteMap> tag can only have one <siteMapNode> child node (the "home" page) Each <siteMapNode> can have several child nodes (web pages) Each <siteMapNode> has attributes defining page title and URL

Dynamic Menu: The <asp:Menu> control displays a standard site navigation menu. Code Example: <asp:SiteMapDataSource id="nav1" runat="server" /> <form runat="server"> <asp:Menu runat="server" DataSourceId="nav1" /> </form> The <asp:Menu> control in the example above is a placeholder for a server created navigation menu. The data source of the control is defined by the DataSourceId attribute. The id="nav1" connects it to the <asp:SiteMapDataSource> control. The <asp:SiteMapDataSource> control automatically connects to the default sitemap file (web.sitemap). TreeView: The <asp:TreeView> control displays a multi level navigation menu. The menu looks like a tree with branches that can be opened or closed with + or - symbol.

Code Example: <asp:SiteMapDataSource id="nav1" runat="server" /> <form runat="server"> <asp:TreeView runat="server" DataSourceId="nav1" /> </form> The <asp:TreeView> control in the example above is a placeholder for a server created navigation menu. The data source of the control is defined by the DataSourceId attribute. The id="nav1" connects it to the <asp:SiteMapDataSource> control. The <asp:SiteMapDataSource> control automatically connects to the default sitemap file (web.sitemap). Design Output:

Login Control in Asp.net


Login Controls are used to create features like user can login, change the password, create new user, password recovery etc. Such controls are very useful in web applications. Pointer: It is just a pointer. If we drag any other control on form it causes to create that control on form but pointer does not create any control on form. In other word we can say, we select it for to ignore any other selected control. ChangePassword: This control is used to provide the user a function to change the existing password. In the process of changing password user have to provide his old password and then new password. We can use functionality to this control to send the user password change confirmation by email. CreateUserWizard: This control is used to create new user. We can add additional steps to collect more information from user. We also can add functionality to this control to send the user email containing his username and password. Login: This control is used to provide the user functionality to login in website. This control contains two textboxes for username and password; one checkbox control for to remember password and one button. LoginName: This control is used to display the current logged-in/authenticated user name on web page. We can add the functionality to this control to display "Guest" when no one is authenticated to website. LoginStatus: This control is used to display the information that user is currently authenticated or not. If user is authenticated then it will display a link like "Logout" and if not then "Login". LoginView: This control is used to display the user's authentication status and roles. PasswordRecovery: This control provides the functionality to recover the forgotten password. We can also add function to send the email containing password to user when user request for password.

Login Control properties FailureText: used to control the content and appearance of the text that is displayed when a login attempt fails. CreateUserUrl: used to create links to registration page to create user PasswordRecoveryUrl: used to create links to password recovery page VisibleWhenLoggedIn: This property enables you to automatically hide the Login control when the user is already authenticated DestinationPageUrl: This property sets the name of the page that the user will be redirected to after logging in. If you do not specify a value for the DestinationPageUrl property, the user will be redirected to the originally requested URL after being authenticated.

Design Of Login Control:

.CS CODE protected void Login1_Authenticate(object sender, AuthenticateEventArgs e) { OleDbConnection cn = new OleDbConnection("provider=microsoft.jet.oledb.4.0;data source=D://invent.mdb"); cn.Open(); OleDbCommand cmd = new OleDbCommand("select * from logtbl where user ='" + Login1.UserName + "' and pass= '"+ Login1.Password + "' ", cn); OleDbDataReader dr = cmd.ExecuteReader(); if (dr.HasRows) { Response.Redirect("Default.aspx"); } else { Response.Write("Username and Password wrong"); } cn.Close(); }

Web User control in Asp.net


ASP.NET allows you to create new controls according to your requirements. The controls that you create are called ASP.NET User Controls. ASP.NET User Controls have .ascx extension. The biggest advantage of ASP.NET User Controls is that it allows you to save a part of the web form and reuse it many other web forms. This drastically reduces the developers time. ASP.NET User Controls are self-contained entities that are saved in an independent file. You can relate a user control with a black box. ASP.NET User Controls are very helpful when you want to use functionality on multiple pages of a web-application. As ASP.NET User Controls are self-contained the developers working on the same project need not worry about transgressing on others code. ASP.NET User Controls offer a great deal of functionality than Server-side Includes (SSIs) . Using SSIs in encapsulating the site functionality is a quite tedious task when compared to ASP.NET User Controls. You can create a user control by using the Register directive. This process is called registering the user control. For instance, you can use this code

to register a user control: <%@ Register TagPrefix="sampNamespace" TagName="Myname" Src="mypage.ascx" %> The TagPrefix is the exclusive namespace provided to the user control so that multiple ASP.NET User Controls with similar name can be discriminated from each other. The TagName is the name of the user control and the Src is the virtual path to the user control. After registering the user control you can place the tag of the user control in an appropriate location on the web form. You have to include the runat=server attribute with the tag.

User controls have the following similarities with normal ASPX pages: They have a markup section where you can add standard markup and server controls. They can be created and designed with Visual Web Developer in Markup, Design, and Split View. They can contain programming logic, either inline or with a Code Behind file. You have access to page-based information like Request.QueryString. They raise some (but not all) of the events that the Page class raises, including Init, Load, and PreRender.

Creating User Controls: User controls are added to the site like any other content type: through the Add New Item dialog box. Similar to pages, you get the option to choose the programming language and whether you want to place the code in a separate Code Behind file

Now Add following code to file .ascx <%@ Page Language="C#" AutoEventWireup="true" Codevirtual="windows level authntication.aspx.cs" Inherits="windows_level_authntication" %> <%@ Register src="WebUserControl.ascx" tagname="WebUserControl" tagprefix="uc1" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title>Untitled Page</title> <style type="text/css"> .style1 { width: 100%; border: 4px solid #00FFFF; background-color: #FFCC99; }

.style2 { height: 242px; } .style3 { height: 231px; } .style8 { width: 213px; } .style9 { height: 664px; width: 213px; } </style> </head> <body> <form id="form1" runat="server"> <div> <table class="style1"> <tr> <td class="style8"> <uc1:WebUserControl ID="WebUserControl1" runat="server" /> </td> <td class="style3"> <asp:Login ID="Login1" runat="server" BackColor="#FFFBD6" BorderColor="#FFDFAD" BorderPadding="4" BorderStyle="Solid" BorderWidth="1px" FontNames="Verdana" Font-Size="0.8em" ForeColor="#333333" onauthenticate="Login1_Authenticate" TextLayout="TextOnTop"> <TextBoxStyle Font-Size="0.8em" /> <LoginButtonStyle BackColor="White" BorderColor="#CC9966" BorderStyle="Solid" BorderWidth="1px" Font-Names="Verdana" Font-Size="0.8em" ForeColor="#990000" /> <InstructionTextStyle Font-Italic="True" ForeColor="Black" /> <TitleTextStyle BackColor="#990000" Font-Bold="True" FontSize="0.9em" ForeColor="White" /> </asp:Login> </td> <td class="style3"> </td> </tr> <tr> <td class="style9"> &nbsp;</td

<td class="style2"> </td> </tr> </table> </div> </form> </body> </html> Design Of User Control

.CS CODE OF WEB USER CONTROL

protected void Calendar1_SelectionChanged(object sender, EventArgs e) { TextBox2.Text = Calendar1.SelectedDate.ToLongDateString(); } protected void TextBox3_TextChanged(object sender, EventArgs e) { Literal1.Text = "<h1><marquee>Welcome to Mr..'" + TextBox3.Text + "' </marquee> </h1> "; }

How to Call User Control in .aspx Page:

<%@ Register src="WebUserControl.ascx" tagname="WebUserControl" tagprefix="uc1" %>

Output of User Control:

How to Encrypt Password With SHA1 Algorithm


SHA-1 is a two way algorithm meaning that you can take the encrypted value, and decrypt the value to get the original plain text value back. This algorithm provides a good level of security for data, and is a standard algorithm which is used to protect credit card data when it is stored within a database. SHA-1 stands for Secure Hash Algorithm. It consists of five hash functions designed by the National Security Agency (NSA) and published by the National Institute of Standards and Technology (NIST). The five algorithms are SHA-1, SHA-224, SHA-256, SHA-384, and SHA512. SHA-1 is the most commonly used of the SHA series. Hash algorithms are called secure when 1. It is impossible to find a message that corresponds to a given message digest.

2. It is impossible to find two different messages that produce the same message digest. 3. If a message is changed even by a single character, the result will be a completely different message digest. Applications of SHA-1: SHA-1 can be used in a variety of applications: 1. 2. 3. 4. 5. Security applications that require authentication E-mail Electronic funds transfer Software distribution Data storage

Encryption Of Data With Sha-1 Algorithm: .CS Code:

private string EnryptString (string strEncrypted) { byte[] b = System.Text.ASCIIEncoding.ASCII.GetBytes(strEncrypted); string encryptedPassword = Convert.ToBase64String(b); return encryptedPassword; }

Calling of EncryptString Function:

protected void Button2_Click(object sender, EventArgs e) { //Label2.Text=FormsAuthentication.HashPasswordForStoringInConfigFile(TextBox3.Text," Sha1"); string s1 = EnryptString(TextBox3.Text.ToString()).ToString(); Label2.Text = s1; }

Decryption Of Data With Sha-1 Algorithm:

private string DecryptString(string encrString) { byte[] b = Convert.FromBase64String(encrString); string decryptedPassword = System.Text.ASCIIEncoding.ASCII.GetString(b); return decryptedPassword;

Calling of DecryptString Function:

protected void Button3_Click(object sender, EventArgs e) { string s2 = DecryptString(Label2.Text.ToString()).ToString(); Label3.Text = s2; }

Design:

Create connection to Excel data source using C#


Firstly make Database in Excel Sheet Like as:

Connection String For Excel Sheet: Provider=Microsoft.Jet.OLEDB.4.0; Data Source=D:\Book1.xls; Extended Properties=""Excel 8.0;HDR=Yes"";"; .CS Code:

protected void Page_Load(object sender, EventArgs e) { string ConnectionString = @"Provider=Microsoft.Jet.OLEDB.4.0; Data Source=D:\Book1.xls;

Extended Properties=""Excel 8.0;HDR=Yes"";"; string CommandText = "select * from [Sheet1$]"; OleDbConnection myConnection = new OleDbConnection(ConnectionString); OleDbCommand myCommand = new OleDbCommand(CommandText, myConnection); myConnection.Open(); GridView1.DataSource = myCommand.ExecuteReader(); GridView1.DataBind(); myConnection.Close();

Output:

How to add Flash file in Website in ASP.NET


Add flash image in the website, makes attractive. In ASP.NET it can be add easily. For this add any Flash (.swf) file extension file to solution explorer of the website. Add write the code inside Form tag in source page as given below-

<asp:Panel ID="Panel1" runat="server"> <param name="movie" value="head.swf" /> <param name="scale" value="exactfit" /> <param name="AllowScriptAccess" value="always" /> <embed src="head.swf" width="750" height="96" scale="exactfit" allowscriptaccess="always" type="application/x-

shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" /> </asp:Panel>

Highlighted show the flash file name you can add your flash file name here. Rest thing is ok or you can customize according to your requirement.

How to Rotate Image in ASP.NET


Design:

When You Click On Button Image Will Rotate: Like this

.ASPX CODE:

<asp:Image ID="Image1" runat="server" Height="297px" ImageUrl="~/images/image.bmp" Width="343px" /> <asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Rotate Image" />

.CS CODE:

protected void Button1_Click(object sender, EventArgs e) { // get the full path of image url string path = Server.MapPath(Image1.ImageUrl); // creating image from the image url System.Drawing.Image i = System.Drawing.Image.FromFile(path); // rotate Image 90' Degree i.RotateFlip(RotateFlipType.Rotate90FlipXY);

// save it to its actual path i.Save(path); // release Image File i.Dispose(); path) } // Set Image Control Attribute property to new image(but its old Image1.Attributes.Add("ImageUrl", path);

How to Download Any File in ASP.NET


Design:

Write Code in .CS File: public void Download() { string filename = "Socha Na Tha "; if (filename != "") { string path = Server.MapPath(filename); System.IO.FileInfo file = new System.IO.FileInfo("D://Socha Na Tha.avi"); if (file.Exists) { Response.Clear(); Response.AddHeader("Content-disposition", "attachment; filename=" + filename); Response.AddHeader("content-Length", file.Length.ToString()); Response.ContentType = "application/octet-stream";// Response.WriteFile(file.FullName); Response.End(); } else { Response.Write("this file does not exist"); }

} { }

} protected void Button1_Click(object sender, EventArgs e) Download();

Output:

When You Click Soch Na Tha Movie Button This Dialog Box Will Appear When You Click On Save This File Any where in Computer

After This Download process Start:

How to get the Values of Selected Row from a Gridview in TextBox using ASP.NET
In this Example you can learn how to get the values of selected row from a Gridview and display the values in textboxes using C# code.

Design:

Add Gridview in .aspx page and bind a Data using SqlDataSource or msaccess.and Add Four Textboxes to display a data in Textboxes when the GridviewRow is Selected. Set the Gridview AutoGenerateColumns property to 'False'. You will need to set the Bound column in order to see the text in the cells of the grid view control. .ASPX Code:

<%@ Page Language="C#" AutoEventWireup="true" Codevirtual="Default.aspx.cs" Inherits="_Default" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml">

<head runat="server"> <title>Untitled Page</title> <style type="text/css"> .style1 { width: 112%; } .style2 { width: 169px; } </style> </head> <body> <form id="form1" runat="server"> <div style="background-color: #FF9900; width: 356px;"> <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="user_id" Height="264px" onrowediting="GridView1_RowEditing" onrowupdating="GridView1_RowUpdating" onselectedindexchanged="GridView1_SelectedIndexChanged" Width="379px" BackColor="#66CCFF" BorderColor="#FF0066"> <Columns> <asp:BoundField DataField="user_id" HeaderText="id" /> <asp:BoundField DataField="name" HeaderText="name" /> <asp:BoundField DataField="fathername" HeaderText="fathername" /> <asp:BoundField DataField="salery" HeaderText="salery" /> <asp:CommandField ShowEditButton="True" /> <asp:CommandField ShowSelectButton="True" /> <asp:CommandField ShowDeleteButton="True" /> </Columns> <SelectedRowStyle BackColor="#FF66FF" /> </asp:GridView> &nbsp;&nbsp;&nbsp;&nbsp; <table class="style1" style="background-color: #CCFF99; height: 268px;"> <tr> <td class="style2"> ID</td> <td> <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox> </td> </tr> <tr> <td class="style2"> Name</td> <td> <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>

</td> </tr> <tr> <td class="style2"> Fathername</td> <td> <asp:TextBox ID="TextBox3" runat="server"></asp:TextBox> </td> </tr> <tr> <td class="style2"> Salery</td> <td> <asp:TextBox ID="TextBox4" runat="server"></asp:TextBox> </td> </tr> <tr> <td class="style2"> Select Name</td> <td> <asp:DropDownList ID="DropDownList1" runat="server" Height="17px" Width="127px"> </asp:DropDownList> </td> </tr> </table> <br /> <br /> </div> </form> </body> </html>

.CS Code:

using using using using using using using using using

System; System.Configuration; System.Data; System.Linq; System.Web; System.Web.Security; System.Web.UI; System.Web.UI.HtmlControls; System.Web.UI.WebControls;

using System.Web.UI.WebControls.WebParts; using System.Xml.Linq; using System.Data.SqlClient; public partial class _Default : System.Web.UI.Page { public void binddata() { SqlConnection con = new SqlConnection(@"data source=R4R01\SQLEXPRESS; initial catalog= banneth; integrated security=true;"); con.Open(); SqlDataAdapter cmd = new SqlDataAdapter("select * from a1", con); DataSet ds = new DataSet(); cmd.Fill(ds); GridView1.DataSource = ds; GridView1.DataBind(); } public void binddata1() { SqlConnection con = new SqlConnection(@"data source=R4R01\SQLEXPRESS; initial catalog= banneth; integrated security=true;"); con.Open(); SqlDataAdapter cmd = new SqlDataAdapter("select name from a1", con); DataSet ds = new DataSet(); cmd.Fill(ds); DropDownList1.DataSource = ds; DropDownList1.DataTextField = "name"; DropDownList1.DataBind(); } protected void Page_Load(object sender, EventArgs e) { if (!Page.IsPostBack) { binddata(); binddata1(); } } // get the values of selected row from a Gridview and display the values in textboxes using C# code. protected void GridView1_SelectedIndexChanged(object sender, EventArgs e) { TextBox1.Text = GridView1.SelectedRow.Cells[0].Text;

} //Update Row protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e) {

TextBox2.Text = GridView1.SelectedRow.Cells[1].Text; TextBox3.Text = GridView1.SelectedRow.Cells[2].Text; TextBox4.Text = GridView1.SelectedRow.Cells[3].Text;

string s = GridView1.DataKeys[e.RowIndex].Value.ToString(); string user = ((TextBox)GridView1.Rows[e.RowIndex].Cells[2].Controls[0]).Text; string l = ((TextBox)GridView1.Rows[e.RowIndex].Cells[2].Controls[0]).Text; string m = ((TextBox)GridView1.Rows[e.RowIndex].Cells[3].Controls[0]).Text; SqlConnection con = new SqlConnection(@"data source=R4R01\SQLEXPRESS; initial catalog= banneth; integrated security=true;"); con.Open(); SqlCommand cmd = new SqlCommand("Update a1 set fathername='" + user + "' where user_id='" + s + "'", con); cmd.ExecuteNonQuery(); con.Close(); GridView1.EditIndex = -1; binddata(); } //Edit Row code protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e) { GridView1.EditIndex = e.NewEditIndex; binddata(); } }

Output:

How to Insert picture in Excel File


Design:

Right Click On Solution Explorer And ADD Reference

.CS CODE:

private void button1_Click(object sender, EventArgs e)

Excel.Application xlApp; Excel.Workbook xlWorkBook; Excel.Worksheet xlWorkSheet; object misValue = System.Reflection.Missing.Value; xlApp = new Excel.ApplicationClass(); xlWorkBook = xlApp.Workbooks.Add(misValue); xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1); //add some text xlWorkSheet.Cells[1, xlWorkSheet.Cells[2, xlWorkSheet.Cells[1, xlWorkSheet.Cells[2, 1] 1] 2] 2] = = = = textBox1.Text; textBox2.Text; textBox3.Text; textBox4.Text;

xlWorkSheet.Shapes.AddPicture("D:\\images1.JPEG", Microsoft.Office.Core.MsoTriState.msoFalse, Microsoft.Office.Core.MsoTriState.msoCTrue, 50, 50, 300, 45); xlWorkBook.SaveAs("ExcelFile.xls", Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue); xlWorkBook.Close(true, misValue, misValue); xlApp.Quit(); releaseObject(xlApp); releaseObject(xlWorkBook); releaseObject(xlWorkSheet); MessageBox.Show("File created !"); } private void releaseObject(object obj) { try { System.Runtime.InteropServices.Marshal.ReleaseComObject(obj); obj = null; } catch (Exception ex) { obj = null; MessageBox.Show("Unable to release the Object " + ex.ToString()); } finally { GC.Collect(); }

Output:

How to Make Setup Of WebApplication


Step I: Create a Simple web application or web project using Microsoft Visual Studio .NET

Step II: After This You Create a Simple WebForm in the web project. You can also add some more Webform or other control in this project by creating separate directory or in same directory.

Step III: Select Setup and Deployment Projects and than select Web Setup Project also specify the Location and name of your project. Click>>> File>>>ADD>>>NewProject>>>OtherProjectTypes>>>Setup and Deployment>>>WebSetup

After creating setup project right click on project(solution Explorer) and than select view, it will show different possible operations, which you can perform with this setup project.

These options are File System Registry File Types User interfaces Custom Actions Launch conditions Step IV: Select File system, it is use to create file system on the target machine. Through this you can specify what details you want to provide at the target machine. For providing right click on web application project than select add it will display certain option out of that select project output. After that select all details you want to supply for target machine.

Step V: Select User Interface from the view in this selection you can specify what are the screens you want to display during installation process. You can change it, remove it or you can define new screen by right clicking on the screen header.

After That Step VI: Select Launch Conditions through this condition you can specify your criteria, which are prerequisite for your application installation

Step VII: Now final step is compile the setup project. After compilation you will notice that it has generated SampleProjectSetup.msi at applications bin/debug folder.

How to Save Image in Database


Create a table in a SQL Server 2005 database which has at least one field of type IMAGE.

Design :

Namespaces used in this application: using using using using using System.Data.SqlClient; System.Drawing; System.Data; System.IO; System.Drawing.Imaging;

Source Code for Save the image file into the database protected void Button1_Click(object sender, EventArgs e) { int length = FileUpload1.PostedFile.ContentLength; byte[] pic = new byte[length]; FileUpload1.PostedFile.InputStream.Read(pic, 0, length); // Insert the image and comment into the database SqlConnection con = new SqlConnection(@"data source=R4R01\SQLEXPRESS;initial catalog=saveimage;integrated security=true"); try { con.Open(); SqlCommand cmd = new SqlCommand("insert into saveimage1 " + "(Picture, Comment) values (@a, @b)", con); cmd.Parameters.Add("@a", pic); cmd.Parameters.Add("@b", TextBox1.Text); cmd.ExecuteNonQuery(); } finally { con.Close(); } }

Read image from a database using ADO.NET and display it in a Web Page protected void Button2_Click(object sender, EventArgs e) { // Put user code to initialize the page here MemoryStream stream = new MemoryStream(); SqlConnection con = new SqlConnection(@"data source=R4R01\SQLEXPRESS;initial catalog=saveimage;integrated security=true"); con.Open(); SqlCommand command = new SqlCommand("select picture from saveimage1",con); byte[] image = (byte[])command.ExecuteScalar(); stream.Write(image, 0, image.Length); Bitmap bitmap = new Bitmap(stream); Response.ContentType = "image/gif"; bitmap.Save(Response.OutputStream, ImageFormat.Gif); }

Output:

Machine Confiq in ASP.NET


The Machine.Config file, which specifies the settings that are global to a particular machine. Machine Confiq is automatically installed when you install Visual Studio. Net on computer. This is also called machine level configuration file. Only one Machine.config file exists on a server. This file is at the highest level in the configuration hierarchy. There are a number of ASP.NET settings that reside in the machine.config file provided with the .NET* Framework that can be tweaked to improve system performance. This file is located at the following path: \WINNT\Microsoft. NET\Framework\[Framework Version]\CONFIG\machine.config As web.config file is used to configure one asp .net web application, same way Machine.config file is used to configure the application according to a particular machine. That is, configuration done in machine.config file is affected on any application that runs on a particular machine. Usually, this file is not altered and only web.config is used which configuring applications. You can override settings in the Machine.Config file for all the applications in a particular Web site by placing a Web.Config file in the root directory of the Web site as follows: \InetPub\wwwroot\Web.Config Difference between Web.Config and Machine.Config File: Two types of configuration files supported in ASP.NET. Configuration files are used to control and manage the behavior of a web application. Machine.config: 1. 2. 3. 4. This is automatically installed when you install Visual Studio. Net. This is also called machine level configuration file. Only one machine.config file exists on a server. This file is at the highest level in the configuration hierarchy.

Web.config: 1. This is automatically created when you create an ASP.Net web application project. 2. This is also called application level configuration file. 3. This file inherits setting from the machine.config

Reflection in ASP.NET
Reflection provides objects (of type Type) that encapsulate assemblies, modules and types. Reflection is the ability to read metadata at runtime. Using reflection, it is possible to uncover the methods, properties, and events of a type, and to invoke them dynamically. Reflection also allows us to create new types at runtime. Reflection generally begins with a call to a method present on every object in the .NET framework: GetType. The GetType method is a member of the System. Object class, and the method returns an instance of System.Type. System.Type is the primary gateway to metadata. System.Type is actually derived from another important class for reflection: the MemeberInfo class from the System.Reflection namespace. MemberInfo is a base class for many other classes who

describe the properties and methods of an object, including FieldInfo, MethodInfo, ConstructorInfo, ParameterInfo, and EventInfo among others. As you might suspect from their names, you can use these classes to inspect different aspects of an object at runtime. How to use Reflection in our applications? The System.Reflection namespace contains classes and interfaces that provide a managed view of loaded types, methods, and fields, with the ability to dynamically create and invoke types.. OR we can say System.Reflection namespace hold all the Reflection related classes. These classes are used and provide information from any of the class under .NET framework. The Type class is the main class of all reflection operations. Type is an abstract base class that acts as means to access metadata though the reflection classes. Using Type object, any information related to methods, implementation details and manipulating information can be obtained. The types include the constructors, methods, fields, properties, and events of a class, along with this the module and the assembly in which these information are present can be accessed and manipulated easily. As mentioned earlier, we can use reflection to dynamically create an instance of any type, bind the type to an existing object, or get the type from an existing object. Once this is done appropriate method can be invoked, access the fields and properties. This can be done by specifying the Type of object or by specifying both assembly and Type of the object that needs to be created. By this the new object created acts like any other object and associated methods, fields and properties can be easily accessed. With reflection we can also find out about various methods associated with newly created object and how to use these object. To find out the attributes and methods associated with an object we can use the abstract class MemberInfo, this class is available under the namespace System.Reflection. Example Of Reflection: In this example, Reflection is used to obtain the full name of a loaded assembly: // Using Reflection to get information from an Assembly:

protected void Button1_Click(object sender, EventArgs e) { System.Reflection.Assembly o = System.Reflection.Assembly.Load("mscorlib.dll"); Response.Write(o.GetName()); }

Output: mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 Benefits Of Reflection:

1. The advantage of Reflection is that we don't require any modification on the Copy Constructor code as long as we define a Property for newly added fields. Similarly, no code modification is required if we drop a field. 2. Reflection can also be used to create customizable application architectures through the use of plug-in modules. Many Object Relation Modeling (ORM) solutions also take advantage of reflection to implement dynamic mapping functionality.

How to Save Resume in Resume folder which is use in project


Design Output:

Step 1: Firstly Make resume Folder in Solution Explorer in Visual studio 2008 Step 2: Right Code On Button Click

protected void Button1_Click(object sender, EventArgs e) { if (FileUpload1.HasFile) { try { string path = Server.MapPath("~/resume/") + FileUpload1.FileName; FileUpload1.SaveAs(path); Label1.Text = "Mr."+" " + TextBox1.Text + " Your Resume Successfully saved"; } catch (Exception ex) {

} } }

Output:

Click Submit Button it save in resume Folder of Project:

Searching document from website in ASP.NET


In this application i am going to show how to make searching enabled website. Through this you can search topics, resumes, news and contents also. For this design page as given below-

Here browse button is used for submitting document to the server and then with the help of textbox we can search that document. Code for submitting document to the server or in website.

protected void Button1_Click(object sender, EventArgs e) { FileUpload1.SaveAs(Server.MapPath("~/NewFolder1/") + FileUpload1.FileName); SqlConnection con = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory| \newdata.mdf;Integrated Security=True;User Instance=True"); SqlCommand com = new SqlCommand("insert into new values('"+FileUpload1.PostedFile.FileName.ToString() +"')",con); con.Open(); com.ExecuteNonQuery(); con.Close(); } Code for making search-

protected void Button2_Click(object sender, EventArgs e) { SqlConnection con = new SqlConnection(@"Data Source=. \SQLEXPRESS;AttachDbFilename=|DataDirectory| \newdata.mdf;Integrated Security=True;User Instance=True"); SqlCommand com = new SqlCommand("select filename from new where filename like '"+TextBox1.Text+"%'", con); con.Open(); SqlDataReader dr = com.ExecuteReader(); if (dr.Read()) { LinkButton1.Text = dr["filename"].ToString(); } else { LinkButton1.Text = "No match found!!!"; } con.Close(); }

Here search result will show on link button Code for this is given below-

protected void LinkButton1_Click(object sender, EventArgs e) { Response.TransmitFile(Server.MapPath("~/NewFolder1/me.doc")); Response.End(); }

Making Google Search from website Code for this is given below-

protected void Button3_Click(object sender, EventArgs e) { Response.Redirect("http://www.google.co.in/search?hl =en&source=hp&biw=&bih=&q=" + TextBox2.Text); }

Page will redirect to the Google and your search result will show as follows-

Bind Countries to a DropDownList in ASP.NET


In this Example we Learn How to get list of all countries and bind to a dropdown list in ASP.NET . Create an ASP.NET application and add a DropDownList to the page something like this. .ASPX Code:

<asp:DropDownList ID="DropDownList1" runat="server" Height="27px" Width="141px">

</asp:DropDownList>

.CS CODE: using using using using using using using using using using using using using using System; System.Configuration; System.Data; System.Linq; System.Web; System.Web.Security; System.Web.UI; System.Web.UI.HtmlControls; System.Web.UI.WebControls; System.Web.UI.WebControls.WebParts; System.Xml.Linq; System.IO; System.Collections.Generic; System.Globalization;

public partial class _Default : System.Web.UI.Page { public List<string> GetCountryList() { List<string> list = new List<string>(); CultureInfo[] cultures = CultureInfo.GetCultures(CultureTypes.InstalledWin32 Cultures | CultureTypes.SpecificCultures); foreach (CultureInfo info in cultures) { RegionInfo info2 = new RegionInfo(info.LCID); if (!list.Contains(info2.EnglishName)) { list.Add(info2.EnglishName); } } return list; } protected void Page_Load(object sender, EventArgs e) { DropDownList1.DataSource = GetCountryList(); DropDownList1.DataBind(); DropDownList1.Items.Insert(0, "Select"); } }

Output:

Skin Style And Theme in ASP.NET


Themes are the great way to customize user-experience in the web application .The main purpose of Themes are used to define the look and feel of the web application, similar to the use of Cascading Style Sheets (CSS) .OR we can say Themes are used to define visual styles for web pages. Themes are made up of a set of elements: skins, Cascading Style Sheets (CSS), images, and other resources. Themes can be applied at the application, page, or server control level. Step1..Once you've created your site, the next step is to create a theme. Right click in Solution Explorer and select Add ASP.NET Folder -> Theme.

In order to add a skin file to an existing theme, you just right click on the theme's folder in Solution Explorer and select Add New Item....

In the resulting dialog box, select "Skin File" as the type of file and choose a name for the file. For this example, I'll just use the default value of "SkinFile.skin".

Right Code And Set Color Size and Border of Control in .Skin File asp:button runat="server" BackColor="lightblue" BorderColor="AliceBlue" Font-Bold ="true" ForeColor="black"/> <asp:Calendar runat="server" BackColor="White" BorderColor="#3366CC" BorderWidth="1px" CellPadding="1" DayNameFormat="Shortest" Font-Names="Verdana" Font-Size="8pt" ForeColor="#003399" Height="200px" Width="220px"> <SelectedDayStyle BackColor="#009999" Font-Bold="True" ForeColor="#CCFF99" /> <SelectorStyle BackColor="#99CCCC" ForeColor="#336666" /> <WeekendDayStyle BackColor="#CCCCFF" /> <OtherMonthDayStyle ForeColor="#999999" /> <TodayDayStyle BackColor="#99CCCC" ForeColor="White" /> <NextPrevStyle Font-Size="8pt" ForeColor="#CCCCFF" />

<DayHeaderStyle BackColor="#99CCCC" ForeColor="#336666" Height="1px" /> <TitleStyle BackColor="#003399" BorderColor="#3366CC" BorderWidth="1px" Font-Bold="True" Font-Size="10pt" ForeColor="#CCCCFF" Height="25px" /> </asp:Calendar> <asp:Image runat="server" ImageUrl = "~/App_Themes/p_0010.jpg" BorderWidth = "4" BorderStyle = "Dashed" BorderColor = "Navy" /> <asp:TextBox runat="server" BorderColor="#3366CC" BorderWidth="1px" ForeColor="#003399" Font-Names="Verdana" Font-Size="8pt"></asp:TextBox Write This line In .ASPX Page: <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Theme="Theme1" Inherits="_Default" %> When you view the page without skin in a browser, you should see:

When you set your theme to the ".aspx" page see:

and view the page in a browser, you should

Differences between Themes and CSS: o CSS deals with HTML code. You cannot apply CSS to certain ASP.NET specific server controls which are not present in HTML. o You can apply Themes and skins to all type of ASP.NET controls with less effort. Themes and skins can be uniformly applied on both windows and asp.net applications. o You can apply single theme to each page where as multiple style sheets can be applied to each page. o Themes don't override or cascade style definitions by default the way CSS generally do. But you can selectively override local property settings for a control using StyleSheetTime attribute in Themes. o You can include CSS files in Themes which is applied as part of Theme structure but not vice-versa. You can apply theming for only those properties that have ThemeableAttribute attribute set to true in their control class. Skins

Socket Programming in ASP.NET


A Computer Network implies two or more computers linked together through some software or hardware for the purpose of exchanging data and information from one computer to other computer. Microsoft .NET provides great support for writing programs that can make

use of sockets for communication between two or more programs over a network. Sockets are similar to telephone communications between people working for different companies. If Im going to contact you from my phone, I need to know you company phone number and your extension. In socket communication, the Phone number is the IP address of the machine you want to talk to. You may know you want to talk to. You may know this as a dotted IP address of the form 127.0.0.1 or as a more humanly friendly representation of www.domainname.domaintype. Sockets and Ports A socket is the end point of a two way communication between two computer running over a network. When two or more processes communicate over a network, they communicate using Sockets. A port implies an unsigned integer that uniquely identifies a process running over a network. The following are some of the well known port numbers distinguished by the type of services that they provide: 1. 2. 3. 4. 5. 6. 7. HTTP Telnet SMTP SNPP DNS FTP (Data) FTP (Control) 80 23 25 444 53 20 21

Tracing in ASP.NET
Tracing is the concept or process of checking errors in code/codes. Or we can say : Tracing is a way to check the execution of your ASP.NET application. You can record exception details and program flow in a way that doesn't affect the program's output. ASP.NET Provide Two Types of Tracing Page Level Tracing ASP.NET tracing can be enabled on a page-by-page basis by adding "Trace=true" to the Page directive in any ASP.NET page: <%@ Page Language="C#" Trace="true" TraceMode = "SortByCategory" Inherits = "System.Web.UI.Page" Codevirtual="Default.aspx.cs" %> The Page Level Tracing include some information 1. 2. 3. 4. 5. 6. 7. 8. 9. Request details (time, type, status code) Size (in bytes) required to render the page, and each control. Timing information for critical points of the pages lifecycle Cookie information sent to the server Client HTTP headers Form data Session and application state associated with the request Query strings sent with the request All server variables (REMOTE_HOST, SERVER_NAME, etc)

Example:

Application-Level Tracing : Application level tracing by default turns on page-level tracing for all pages in the application .However ,for an individual page it is possible to explicitly turn off page tracing .Application level tracing additionally provides information about the application state, contents of the session .These static's can b collected for a specified number of request as determined by the application configuration file .Enabling application level tracing is also very simple. To enable application level tracing the following line of code needs to be added to the "System.Web" session of the "web.config" file. trace enabled ="true" pageOutput="true" The pageOutput parameter is required to set to be true .If the pageOutput statistics are supposed to be sent to the client (displaying as page level tracing) .By default,this value is false.

Code for Application Level tracing in web.config file <configuration> <system.web> <trace enabled="true" requestLimit="40" pageOutput="true" localOnly="false" /> </system.web> </configuration>

Multiple Image Upload in ASP.NET


Design:

.ASPX CODE: <%@ Page Language="C#" AutoEventWireup="true" Codevirtual="add multiple images.aspx.cs" Inherits="add_multiple_images" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title>Untitled Page</title> <style type="text/css"> .style1 {

width: 100%; } .style2 { font-size: x-large; } .style3 { width: 173px; } </style> </head> <body> <form id="form1" runat="server" enctype="multipart/form-data"> <div> <table class="style1" style="background-color: #FFCCFF"> <tr> <td colspan="2"> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <span class="style2">&nbsp;&nbsp; Upload Multiple Images&nbsp;</span></td> </tr> <tr> <td class="style3" rowspan="10" style="background-image: url('Images/where r u.jpg')"> &nbsp;</td> <td> &nbsp;<asp:FileUpload ID="FileUpload1" runat="server" /> </td> </tr> <tr> <td> <asp:FileUpload ID="FileUpload2" runat="server" /> </td> </tr> <tr> <td> <asp:FileUpload ID="FileUpload3" runat="server" /> </td> </tr> <tr> <td> <asp:FileUpload ID="FileUpload4" runat="server" /> </td> </tr> <tr> <td> <asp:FileUpload ID="FileUpload5" runat="server" />

</td> </tr> <tr> <td> <asp:FileUpload ID="FileUpload6" runat="server" /> </td> </tr> <tr> <td> <asp:FileUpload ID="FileUpload7" runat="server" /> </td> </tr> <tr> <td> <asp:FileUpload ID="FileUpload8" runat="server" /> </td> </tr> <tr> <td> <asp:FileUpload ID="FileUpload9" runat="server" /> </td> </tr> <tr> <td> <asp:FileUpload ID="FileUpload10" runat="server" /> </td> </tr> <tr> <td class="style3"> <asp:Button ID="Button1" runat="server" onclick="Button1_Click1" Text="Upload Images" /> </td> <td> &nbsp;</td> </tr> <tr> <asp:Image ID="Image1" runat="server" Height="100" Width="100" ImageUrl="~/Image.gif" /> <asp:Image ID="Image2" runat="server" Height="100" Width="100" ImageUrl="~/Image.gif" /> <asp:Image ID="Image3" runat="server" Height="100" Width="100" ImageUrl="~/Image.gif" /> <asp:Image ID="Image4" runat="server" Height="100" Width="100" ImageUrl="~/Image.gif" /> <asp:Image ID="Image5" runat="server" Height="100" Width="100" ImageUrl="~/Image.gif" /> </div> <br /> <div id="div4" runat="server" visible="false"> <asp:Image ID="Image6" runat="server" Height="100" Width="100" ImageUrl="~/Image.gif" /> <asp:Image ID="Image7" runat="server" Height="100" Width="100" ImageUrl="~/Image.gif" />

<asp:Image ID="Image8" runat="server" Height="100" Width="100" ImageUrl="~/Image.gif" /> <asp:Image ID="Image9" runat="server" Height="100" Width="100" ImageUrl="~/Image.gif" /> <asp:Image ID="Image10" runat="server" Height="100" Width="100" ImageUrl="~/Image.gif" /> </div> </tr> </table> </div> </form> </body> </html> .CS CODE:

protected void Button1_Click1(object sender, EventArgs e) { HttpFileCollection uploadFilCol = Request.Files; for (int i = 0; i < uploadFilCol.Count; i++) { HttpPostedFile file = uploadFilCol[i]; string fileExt = Path.GetExtension(file.FileName).ToLower(); string fileName = Path.GetFileName(file.FileName); if (fileName != string.Empty) { try { if (fileExt == ".jpg" || fileExt == ".gif" || fileExt == ".bmp" || fileExt == ".jpeg" || fileExt == ".png") { file.SaveAs(Server.MapPath("~/Images/") + fileName); if (i == 0) { Image1.ImageUrl = "~/Images/" + fileName; } if (i == 1) { Image2.ImageUrl = "~/Images/" + fileName; } if (i == 2) { Image3.ImageUrl = "~/Images/" + fileName; } if (i == 3) {

Image4.ImageUrl = "~/Images/" + fileName; } if (i == 4) { Image5.ImageUrl = "~/Images/" + fileName; } if (i == 5) { Image6.ImageUrl = "~/Images/" + fileName; } if (i == 6) { Image7.ImageUrl = "~/Images/" + fileName; } if (i == 7) { Image8.ImageUrl = "~/Images/" + fileName; } if (i == 8) { Image9.ImageUrl = "~/Images/" + fileName; } if (i == 9) { Image10.ImageUrl = "~/Images/" + fileName; } } } catch (Exception ex) { throw ex; } } }

Output: Now click on Browse button and select Images which you want to upload.

Now click on the uploadImages button.

What is Virtual Directory


1. In ASP.NET virtual directory represents a web application or WebProject and it points to a physical folder in your own computer. 2. A web application is accessed using a virtual directory name instead of a physical folder name. For example, if you have a web application called "Inventory" in your machine, and if you Create a virtual directory for this web application. You will access your web application using the URL httP://localhost/Inventory. If your virtaul directory name is "TestData", then your web application url will be "http://localhost/TestData". 3. Assume you have a web application called "Inventory", created under the physical folder "C:\MyProjects\Inventory". 4. You can go to IIS (internet Information Server) and see this virtual directory listed. Right click on this virtual directory name in IIS and see the properties. You can see that this virtual directory is pointing to the physical location "C:\MyProjects\Inventory". 5. If you have a file called "File1.aspx" under the folder "C:\MyProjects\Inventory\", then you can access this file using Internet Explorer with the URL "http://localhost/Inventory/File1.aspx"

How to Make Virtual Directory in ASP.NET:

1. When you create a new web project using, a new virtual directory will be created
automatically for you. This virtual directory will point to a new folder created under C:\Inetpub\wwwroot. 2. If you like to better organize your projects and files in your favorites folder, you must manually create a new folder for each project in your preferred location and convert it into a virtual folder manually. 3. There are couple of ways you can do this. Method 1: Open the IIS. Right click on the node "Default Web Site" and select "new Virtual Directory". When it prompt you to enter the "alias", enter the virtual directory name you want(Eg: Inventory). In the prompt for "directory", select the folder which you want to make a virtual directory (Eg: C:\MyProjects\Inventory). Select other default values and press "Finish". Now you should be able to see your new virtual directory in IIS. Method 2: In the explorer, go to the folder(Eg: C:\MyProjects\Inventory) which you want to make a "virtual directory". Right click on the folder name and select "Properties". Select the tab "Web sharing" and select teh option "Share this folder". It will prompt you with a default Alias name same as the folder name (Eg: Inventory). Simply select the default values and press "OK".

4. How to Add Manually CheckBox in C# using Asp.net


5. You can add a CheckBox to a form at run time in the following manner. 6. Code for Add mannualy CheckBox in C#:

public void AddCheckBox() { CheckBox chkBox = new CheckBox(); chkBox.Location = new Point(50, 50); chkBox.AutoCheck = true; chkBox.Text = "Checked"; chkBox.Checked = true; chkBox.CheckState = CheckState.Checked; chkBox.CheckedChanged += new EventHandler(chkBox_CheckedChanged); } Controls.Add(chkBox);

private void chkBox_CheckedChanged(object sender, System.EventArgs e) { if (sender is CheckBox) { CheckBox checkbox = sender as CheckBox; if (checkbox.Checked) { checkbox.Text = "Checked"; } else

{ } } }

checkbox.Text = "UnChecked";

How to Add StyleSheet in TextBox using ASP.NET


Add Stylesheet in Project: Rightclick on Solutionexplorer >> AddNewitem>>stylesheet.css and Right Code in .Css File .textbox { font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 25px; font-style:normal; height:30px; } .aspx Code:

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

Output:

How to Create Multi Language Web-Site in ASP.NET


Step 1: Start a new web site with C# and give it the Name Multilanguage website. It will give you a Default.aspx and Default.aspx.cs two files. Step 2:

Now Design the form by putting three labels and three buttons on the form; set the id for the label as well as the button. Step 3: Now go to Solution Explorer window and add a "App_GlobalResources" folder to your project by right clicking and selecting "Add Asp.Net Folder" option. It will add "App_GlobalResources" folder to your project. Now here right click and add Resource File and give it the name "Strings.resx"; it will add a resource file. Step 4: Open that "String.resx" file and add a name to it and a value that you want on the first page load. We will give some English values here for the first time page load. Here we will add some fields like AboutMe, Desc, Header, Eng, Hindi, Marathi and also give some default values like About Me, Hi, Localization In Asp.Net and the two values for Hindi and Marathi taken from gmail option. Step 5: Like in Step 4, create three more files for English, Hindi and Marathi and give the name with culture code like Strings.en-US.resx, Strings.hi-IN.resx, Strings.mr-IN.resx respectively and add same name and the different values with respect to language. Step 6: Now open the code file of Default page and import the namespaces given bellow. using using using using System.Globalization; System.Resources; System.Threading; System.Reflection;

Step 7: Now in global decleration section of .cs file create an instance of ResourceManager and CultureInfo Class. .CS code:

using using using using using using using using using using using using using using using

System; System.Configuration; System.Data; System.Linq; System.Web; System.Web.Security; System.Web.UI; System.Web.UI.HtmlControls; System.Web.UI.WebControls; System.Web.UI.WebControls.WebParts; System.Xml.Linq; System.Globalization; System.Resources; System.Threading; System.Reflection;

public partial class _Default : System.Web.UI.Page { ResourceManager rm; CultureInfo ci; private void LoadString(CultureInfo ci) { Label1.Text = rm.GetString("AboutMe", ci); Label2.Text = rm.GetString("Desc", ci); Button1.Text = rm.GetString("Hindi", ci); Label3.Text = rm.GetString("Header", ci); Button2.Text = rm.GetString("Marathi", ci); Button3.Text = rm.GetString("Eng", ci); } protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { Thread.CurrentThread.CurrentCulture = new CultureInfo("enUS"); rm = new ResourceManager("Resources.Strings", System.Reflection.Assembly.Load("App_GlobalResources")); ci = Thread.CurrentThread.CurrentCulture; LoadString(ci); } else { rm = new ResourceManager("Resources.Strings", System.Reflection.Assembly.Load("App_GlobalResources")); ci = Thread.CurrentThread.CurrentCulture; LoadString(ci); } } protected void Button1_Click(object sender, EventArgs e) { Thread.CurrentThread.CurrentCulture = new CultureInfo("hi-IN"); LoadString(Thread.CurrentThread.CurrentCulture); } protected void Button3_Click(object sender, EventArgs e) { Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US"); LoadString(Thread.CurrentThread.CurrentCulture); } protected void Button2_Click(object sender, EventArgs e) { Thread.CurrentThread.CurrentCulture = new CultureInfo("mr-IN"); LoadString(Thread.CurrentThread.CurrentCulture); }

Output:

When You Click on Hindi Buttton:

When You Click on Marathi Buttton:

How to show Alert and Confirmation Message box in ASP.NET


1. Alert Message Box using Javascript:

<head runat="server"> <script type="text/Javascript" language ="javascript" > function alert_meth() { alert("Client Side MessageBox"); } </script> </head> <body> <form id="form1" runat="server"> <div> <asp:Button ID="Button1" runat="server" Text="Show Message" OnClientClick ="alert_meth()" onclick="Button1_Click" /> </div> </form> </body>

Output:

2. Confirmation Message Box: This MessageBox is used to give a warning to the user. Suppose user want to delete records; at that time this type of message box is used to give confirmation about the action to be taken or not by showing two Buttons as "YES'" and "NO". If the user clicks on the "YES" Button it returns Boolean "True" and for "NO" button it returns Boolean "False". function confirm_meth() { if( confirm("Do you want to continue!Click 'YES'")==true) { document.writeln ("<b>You had click on 'YES' Button</b>"); } else { document.writeln ("<b>You had clic on 'NO' Button</b>"); } } </script> </head> <body> <form id="form1" runat="server"> <div>

<asp:Button ID="Button2" runat="server" Text="Confirmation Message" OnClientClick ="confirm_meth()" onclick="Button1_Click" /> </div> </form> </body> Output:

How to Write Gridview data to XML file in .NET


In this Example you have to write the file name with the extension .xml and the code will create the xml file with that name and populate it. .CS Code:

using using using using using using using using using using using using using

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

public partial class Default6 : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { DataSet ds = new DataSet(); ds.ReadXml(MapPath("Regis.xml")); GridView1.DataSource = ds; //DataGrid1.DataSource = ds; GridView1.DataBind(); } protected void Button3_Click(object sender, EventArgs e) { DataSet ds = new DataSet("TestDataset");

DataTable dt = new DataTable("TestDataTable"); dt.Columns.Add("Id", System.Type.GetType("System.String")); dt.Columns.Add("Loc", System.Type.GetType("System.String")); dt.Columns.Add("email", System.Type.GetType("System.String")); dt.Columns.Add("Disc", System.Type.GetType("System.String")); dt.Columns.Add("Date", System.Type.GetType("System.String")); ds.Tables.Add(dt); // ds.Tables.Add(dt); //Add any number columns here for (int count = 0; count < GridView1.Rows.Count; count++) { DataRow dr = dt.NewRow(); dr[0] = GridView1.Rows[count].Cells[0].Text; dr[1] = GridView1.Rows[count].Cells[1].Text; dr[2] = GridView1.Rows[count].Cells[2].Text; dr[3] = GridView1.Rows[count].Cells[3].Text; dr[4] = GridView1.Rows[count].Cells[4].Text; //you can add values to all columns in datatable dt.Rows.Add(dr); } ds.Tables[0].WriteXml("E:\\test2.xml"); }

<?xml version="1.0" encoding="utf-8"?> <Information> <Comments> <Name>Ashish Kumar Gupta</Name> <location>Ghaziabad</location> <Email>Ashish07akg@gmail.com</Email> <Description>very Nice Article</Description> <Date>1/12/2011 11:22:13 AM</Date> </Comments> <Comments> <Name>Anil</Name> <location>Delhi</location> <Email>anil.rkgit@gmailcom</Email> <Description>Very nice Article Thanks</Description> <Date>1/12/2011 11:29:56 AM</Date> </Comments> <Comments> <Name>Anil</Name> <location>Delhi</location>

<Email>anil.rkgit@gmailcom</Email> <Description>Very nice Article Thanks</Description> <Date>1/12/2011 11:30:09 AM</Date> </Comments> <Comments> <Name>aditya</Name> <location>anil</location> <Email>ash</Email> <Description>sferterte</Description> <Date>4/1/2011 8:46:51 AM</Date> </Comments> </Information>

Output:

When You Click Generate xml file Button XML file is generated in E Drive with Name test2.xml:

test2.xml

How to get Line Count of a File using StreamReader in C#


In this Example We count the Record is without adding the file line by line into a List Collection which can be very inefficient. Just read through the text file line by line till the Stream Reader reaches the end of file and use a counter variable to count the number of lines as shown in the following example.

.CS Code:

using using using using using using using using using

System; System.Collections.Generic; System.ComponentModel; System.Data; System.Drawing; System.Linq; System.Text; System.Windows.Forms; System.IO;

namespace WindowsFormsApplication53 { public partial class Form2 : Form { public Form2() { InitializeComponent(); } int totalRecordCount; private void button1_Click(object sender, EventArgs e) { using (StreamReader r = new StreamReader("TextFile1.txt")) { string record; while ((record = r.ReadLine()) != null) { totalRecordCount++; } } textBox1.Text = totalRecordCount.ToString(); label1.Text = "Hiiiiiii This File Contain " + textBox1.Text+ " "+"Line"; } } }

Output:

How to Calculate Textbox value Using JavaScript in ASP.NET:


.ASpx Code:

<%@ Page Language="C#" AutoEventWireup="true" Codevirtual="calculate textbox.aspx.cs" Inherits="calculate_textbox" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional// EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <script language="javascript" type="text/javascript"> function KeyUpEvent() { if (document.getElementById("TextBox1").value=="") { alert("textbox can not be blank"); document.getElementById("TextBox1").focus(); return false; } if (document.getElementById("TextBox2").value=="") { alert("textBox can not be blank"); document.getElementById("TextBox2").focus(); return false; } var txt1 = document.getElementById("TextBox1"); var txt2 = document.getElementById("TextBox2"); var txt3 = document.getElementById("TextBox3"); if ((txt1.value != "") && (txt2.value != "")) { txt3.value = parseInt(txt1.value) + parseInt(txt2.value); } } </script> </head> <body> <form id="form1" runat="server"> <div style="width: 332px"> Enter First Number :&nbsp;&nbsp;&nbsp; <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox> <br /> <br /> Enter Second Number:<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox> <br /> <br /> Result&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&n bsp;&nbsp;&nbsp; :<asp:TextBox ID="TextBox3" runat="server"></asp:TextBox> <br /> <asp:Button ID="Button1" runat="server" onclick="Button1_Click"

Text="Show Result:" OnClientClick=" return KeyUpEvent()" /> <br /> </div> </form> </body> </html>

Output:

How to create Dynamic textbox in asp.net


.CS Code:

using using using using using using using using using using

System.Configuration; System.Data; System.Linq; System.Web; System.Web.Security; System.Web.UI; System.Web.UI.HtmlControls; System.Web.UI.WebControls; System.Web.UI.WebControls.WebParts; System.Xml.Linq;

public partial class Default7 : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { int n = 5; for (int i = 0; i < n; i++) { TextBox txt = new TextBox(); txt.ID = "txt_" + i.ToString(); Console.WriteLine(); Panel1.Controls.Add(txt); Panel1.Controls.Add(new Literal("<br />"));

} } }

Output:

How to convert text in TextBox to image with C# Language


.aspx Code:

<%@ Page Language="C#" AutoEventWireup="true" Codevirtual="Excelsheet header.aspx.cs" Inherits="Excelsheet_header" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title>Untitled Page</title> </head> <body> <form id="form1" runat="server"> <div> <asp:TextBox ID="TextBox1" runat="server" Width="321px"></asp:TextBox> <br /> <br /> <asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" /> </div> </form> </body> </html> .CS Code:

using using using using using using using using using using using using using

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

using System.Drawing; using System.Drawing.Imaging; public partial class Excelsheet_header : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } protected void Button1_Click(object sender, EventArgs e) { Bitmap b = new Bitmap(250, 30, System.Drawing.Imaging.PixelFormat.Format32bppArgb); Graphics g = Graphics.FromImage(b); string message; g.Clear(Color.Yellow); message = TextBox1.Text; g.DrawString(message, new Font("Arial", 12, FontStyle.Regular), new SolidBrush(Color.Black), new PointF(0.5F, 2.5F)); Response.ContentType = "image/gif"; b.Save(Response.OutputStream, ImageFormat.Gif); b.Dispose(); } }

Design:

Output:

When You Click On Button Its convert in Image:

How to populate combobox from xml file using c#


This is Your xml file Filename is==>> Regis.xml

<?xml version="1.0" encoding="utf-8"?> <Information> <Comments> <Name>Ashish Kumar Gupta</Name> <location>Ghaziabad</location> <Email>Ashish07akg@gmail.com</Email> <Description>very Nice Article</Description> <Date>1/12/2011 11:22:13 AM</Date> </Comments> <Comments> <Name>Anil</Name> <location>Delhi</location> <Email>anil.rkgit@gmailcom</Email> <Description>Very nice Article Thanks</Description> <Date>1/12/2011 11:29:56 AM</Date> </Comments> <Comments> <Name>Anil</Name> <location>Delhi</location> <Email>anil.rkgit@gmailcom</Email> <Description>Very nice Article Thanks</Description> <Date>1/12/2011 11:30:09 AM</Date> </Comments> <Comments> <Name>aditya</Name> <location>anil</location> <Email>ash</Email> <Description>sferterte</Description> <Date>4/1/2011 8:46:51 AM</Date> </Comments> </Information> .CS Code:

using System; using System.Collections; using System.Configuration;

using System.Data; using System.Linq; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.HtmlControls; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Xml.Linq; using System.Xml; public partial class xmlfill_dropdown : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { XmlDocument doc = new XmlDocument(); doc.Load(Server.MapPath("regis.xml")); XmlNodeList colorList = doc.SelectNodes("Information/Comments/Name"); foreach (XmlNode Name in colorList) { DropDownList1.Items.Add(Name.InnerText); } } } Output:

How to Get Particular Value From XML file in ASP.NET using C#


Create XML file Like This:

<?xml version="1.0" encoding="utf-8"?> <Information> <Comments> <Name>Ashish Kumar Gupta</Name> <location>Ghaziabad</location> <Email>Ashish07akg@gmail.com</Email> <Description>very Nice Article</Description> <Date>1/12/2011 11:22:13 AM</Date>

</Comments> <Comments> <Name>Anil</Name> <location>Delhi</location> <Email>anil.rkgit@gmailcom</Email> <Description>Very nice Article Thanks</Description> <Date>1/12/2011 11:29:56 AM</Date> </Comments> <Comments> <Name>Anil</Name> <location>Delhi</location> <Email>anil.rkgit@gmailcom</Email> <Description>Very nice Article Thanks</Description> <Date>1/12/2011 11:30:09 AM</Date> </Comments> <Comments> <Name>aditya</Name> <location>anil</location> <Email>ash</Email> <Description>sferterte</Description> <Date>4/1/2011 8:46:51 AM</Date> </Comments> </Information>

.CS Code:

protected void Button2_Click(object sender, EventArgs e) { System.Xml.XmlDocument doc = new System.Xml.XmlDocument(); doc.Load(Server.MapPath("regis.xml")); // Root element System.Xml.XmlElement root = doc.DocumentElement; System.Xml.XmlElement conditie = (System.Xml.XmlElement)root.ChildNodes[0].ChildNodes[0]; string semnal = conditie.ChildNodes[0].InnerText; string bl = conditie.ChildNodes[1].InnerText; Response.Write(semnal ); }

Output:

Ashish Kumar Gupta

How to upload Image in ASP .NET using C#


Step 1: Drag a image control and a button control. Click on Add Extender a small window open, select a popupControlExtender and click ok. The extender control be added.

Design Code (Default.aspx) <%@ Page Language="C#" AutoEventWireup="true" Codevirtual="Default.aspx.cs" Inherits="_Default" %> <%@ Register assembly="AjaxControlToolkit" namespace="AjaxControlToolkit" tagprefix="cc1" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title>Untitled Page</title> </head> <body> <form id="form1" runat="server"> <asp:ScriptManager ID="ScriptManager1" runat="server"> </asp:ScriptManager> <div> <asp:Image ID="profile_image" runat="server" Width="142px" Height="193px"/>

<br /> <asp:Button ID="Button2" runat="server" Text="Edit Image" /> <br /> <table align="center"><tr><td><cc1:PopupControlExtender ID="Button2_PopupControlExtender" runat="server" DynamicServicePath="" Enabled="True" ExtenderControlID="" PopupControlID="Panel1" TargetControlID="Button2"> </cc1:PopupControlExtender> <asp:Panel ID="Panel1" runat="server" BorderStyle="Solid" BorderWidth="1px" BackColor="Gray" Height="120px" Width="227px"><br /> <asp:FileUpload ID="FileUpload1" runat="server" /> <br /> <asp:Button ID="Button1" runat="server" Text="Upload" onclick="Button1_Click" /> <br /> </asp:Panel></td></tr></table></div> </form></body></html> Default.aspx.cs using System.Data; using System.Linq; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.HtmlControls; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Xml.Linq; public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { profile_image.ImageUrl="~/Image/blank_img.jpeg"; } protected void Button1_Click(object sender, EventArgs e) { string filename = ""; string path; if (FileUpload1.HasFile) { filename = FileUpload1.PostedFile.FileName; path=Server.MapPath("~/Image/") +FileUpload1.FileName; string onlyname = path.Substring(path.LastIndexOf("\\") + 1); profile_image.ImageUrl = "~/Image/" + onlyname; } }

Step 2: Run the Application and click on edit Button then click on Brower Button and select an image.

Then click on Upload Button. The profile image being uploaded

Creating Directory or Folder using ASP.NET in C#


.aspx code:

<%@ Page Language="C#" AutoEventWireup="true" Codevirtual="creating directory.aspx.cs" Inherits="creating_directory" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title>Untitled Page</title> </head> <body> <form id="form1" runat="server"> <div> <asp:Button ID="Button1" runat="server" Text="Create New Directory" onclick="Button1_Click" /> <br /><br /> <asp:Label ID="Label1" runat="server" Text=""></asp:Label> </div> </form>

</body> </html>

.CS Code:

using using using using using using using using using using using using using

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

public partial class creating_directory : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } private void CreateDirectoryIfNotExists(string NewDirectory) { try { // Checking the existance of directory if (!Directory.Exists(NewDirectory)) { //If No any such directory then creates the new one Directory.CreateDirectory(NewDirectory); Label1.Text = "Directory Created"; } else { Label1.Text = "Directory Exist"; } } catch (IOException _err) { Response.Write(_err.Message); } } protected void Button1_Click(object sender, EventArgs e) {

string NewDirectory = Server.MapPath("Ashish Kumar"); //New Directory Name in string variable CreateDirectoryIfNotExists(NewDirectory); //Calling the function to create new directory } }

Output:

When You Click on Create Directory Button then Directory Will be Create in Solution Explorer

Set style for label in ASP.NET Using C#


.aspx Code:

<%@ Page Language="C#" AutoEventWireup="true" Codevirtual="setstyleforlabel.aspx.cs" Inherits="setstyleforlabel" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/ xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title>Untitled Page</title>

<style type="text/css"> .style1 { color: #0066FF; } </style> </head> <body> <form id="form1" runat="server"> <div> <h1 class="style1">Choose multiple colors (use ctrl or shift): </h1> <asp:ListBox ID="myList" runat="server" SelectionMode="Multiple" Rows="6" AutoPostBack="True" onselectedindexchanged="myList_SelectedIndexChanged"> <asp:ListItem Value="#FF0000">Red</asp:ListItem> <asp:ListItem Value="#FF00FF">Magenta</asp:ListItem> <asp:ListItem Value="#FFFF00">Yellow</asp:ListItem> <asp:ListItem Value="#00FF00">Green</asp:ListItem> <asp:ListItem Value="#00FFFF">Cyan</asp:ListItem> <asp:ListItem Value="#0066FF">Blue</asp:ListItem> </asp:ListBox> <asp:Label ID="labResult" runat="server" Width="222px" Height="100px" /> </div> </form> </body> </html>

.CS Code:

using using using using using using using using using using using using

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

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

protected void myList_SelectedIndexChanged(object sender, EventArgs e) { labResult.Text = "Colors chosen: <br/>"; foreach (ListItem li in myList.Items) { if (li.Selected) { labResult.Text += "<span style='color:"; labResult.Text += li.Value + "'>" + li.Text; labResult.Text += "</span><br/>"; } } } }

Change style for ListItem in ASP.NET


.aspx code:

<%@ Page Language="C#" AutoEventWireup="true"

Codevirtual="listboxstyle.aspx.cs" Inherits="listboxstyle" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/ xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title>Untitled Page</title> </head> <body> <form id="form1" runat="server"> <div> <asp:Label ID="myLab" runat="server" /><br /> <asp:DropDownList ID="myDrop" runat="server" AutoPostBack="True"> <asp:ListItem>Red</asp:ListItem> <asp:ListItem>Blue</asp:ListItem> <asp:ListItem>Green</asp:ListItem> </asp:DropDownList> </div> </form> </body> </html>

.Cs Code:

using using using using using using using using using using using using

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

public partial class listboxstyle : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { myLab.Text = "Red text here"; myLab.Attributes["style"] = "background-color:red;"; myDrop.Items[0].Attributes["style"] = "background-

color:red;"; myDrop.Items[1].Attributes["style"] = "backgroundcolor:green;"; myDrop.Items[2].Attributes["style"] = "backgroundcolor:blue;"; myDrop.Attributes["style"] = "background-color:yellow;"; myDrop.Items[1].Enabled = false; } }

Output:

How to change page theme dynamically at runtime in asp.net


.aspx Code:

<%@ Page Language="C#" AutoEventWireup="true" Codevirtual="stylesheetdynamically.aspx.cs" Inherits="stylesheetdynamically" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title>Untitled Page</title> </head> <body> <form id="form1" runat="server"> <div>

<asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="True" onselectedindexchanged="DropDownList1_SelectedIndexChanged1"> <asp:ListItem>Blue</asp:ListItem> <asp:ListItem>Green</asp:ListItem> </asp:DropDownList> </div> </form> </body> </html>

.CS Code:

using using using using using using using using using using using using

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

public partial class stylesheetdynamically : System.Web.UI.Page { protected void Page_PreInit(object sender, EventArgs e) { string thm; thm = (string)Session["theme"]; if (thm != null) { Page.Theme = thm; DropDownList1.Text = thm; } else { Session["theme"] = DropDownList1.Text; Page.Theme = "Blue";// Blue is The theme Name } } protected void Page_Load(object sender, EventArgs e) {

} protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e) { Session["theme"] = DropDownList1.Text; Server.Transfer(Request.FilePath); } protected void DropDownList1_SelectedIndexChanged1(object sender, EventArgs e) { Session["theme"] = DropDownList1.Text; Server.Transfer(Request.FilePath); } }

Output:

When You Select Green The Background Will be Green

Important properties of ValidationSummary control


DisplayMode: How the error messages are formatted. Possible values are BulletList, List, and SingleParagraph. HeaderText: Display header text above the validation summary. ShowMessageBox: Display a popup alert box. ShowSummary: Hide the validation summary in the page.

<%@ Page Language="C#" AutoEventWireup="true" Codevirtual="validation summary.aspx.cs" Inherits="validation_summary" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server">

<title>Untitled Page</title> </head> <body> <form id="form1" runat="server"> <div> <asp:ValidationSummary id="ValidationSummary1" ShowMessageBox="true" ShowSummary="false" Runat="server" /> <asp:Label id="lblFirstName" Text="First Name:" AssociatedControlID="txtFirstName" Runat="server" /> <br /> <asp:TextBox id="txtFirstName" Runat="server" /> <asp:RequiredFieldValidator id="reqFirstName" ErrorMessage="First Name is required" ControlToValidate="txtFirstName" Display="None" Runat="server" /> <br /><br /> <asp:Label id="lblLastName" Text="Last Name:" AssociatedControlID="txtLastName" Runat="server" /> <br /> <asp:TextBox id="txtLastName" Runat="server" /> <asp:RequiredFieldValidator id="reqLastName" ErrorMessage="Last Name is required" ControlToValidate="txtLastName" Display="None" Runat="server" /> <br /><br /> <asp:Button id="btnSubmit" Text="Submit" Runat="server" onclick="btnSubmit_Click" /> </div>

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

Output:

Use Validation Summary to display message Box (C#)

<%@ Page Language="C#" AutoEventWireup="true" Codevirtual="validation with msg.aspx.cs" Inherits="validation_with_msg" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title>Untitled Page</title> </head> <body> <form id="form1" runat="server"> <div> A number (1 to 10):

<asp:textbox id="txtValidated" runat="server"></asp:textbox>&nbsp; <asp:rangevalidator id="RangeValidator" runat="server" Type="Integer" MinimumValue="1" MaximumValue="10" ControlToValidate="txtValidated" Text="<img src='ErrorIcon.jpg' alt='Error' />" ErrorMessage="The First Number Is Not In The Range"> </asp:rangevalidator> <br/> <br /> <asp:button id="cmdOK" runat="server" Text="OK" OnClick="cmdOK_Click" Width="44px"></asp:button><br /> <br /> <asp:label id="lblMessage" runat="server" EnableViewState="False"></asp:label><br /> <br /> <asp:ValidationSummary id="ValidationSummary1" runat="server" ShowMessageBox="True"></asp:ValidationSummary> </div> </form> </body> </html>

Output:

ValidationSummary DisplayMode=BulletList

<%@ Page Language="C#" AutoEventWireup="true" Codevirtual="validation summartmode.aspx.cs" Inherits="validation_summartmode" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title>Untitled Page</title> </head> <body> <form id="form1" runat="server"> <div> Select Course <asp:DropDownList ID="lstBooks" runat="server"> <asp:ListItem Value="0" Selected="True">Please pick a book</asp:ListItem> <asp:ListItem Value="1">C#</asp:ListItem> <asp:ListItem Value="2">Asp.net</asp:ListItem> <asp:ListItem Value="3">Ajax</asp:ListItem> </asp:DropDownList> <br /> <asp:RequiredFieldValidator ID="reqBook"

runat="server" ControlToValidate="lstBooks" SetFocusOnError="true" Text="*" InitialValue="0" Display="static" ErrorMessage="Please choose a book from list"/> User Name:<asp:TextBox ID="txtUserName" runat="server"></asp:TextBox> <br /> <asp:RequiredFieldValidator ID="reqUserName" runat="server" ControlToValidate="txtUserName" SetFocusOnError="true" Text="*" Display="static" ErrorMessage="Please enter a User Name"/> Password:&nbsp; <asp:TextBox ID="txtPassword" runat="server"></asp:TextBox> <br /> <asp:RequiredFieldValidator ID="reqPassword" runat="server" ControlToValidate="txtPassword" SetFocusOnError="true" Text="*" Display="static" ErrorMessage="Please enter a password"/> <asp:ValidationSummary id="valSum" runat="server" DisplayMode="BulletList" HeaderText="The following errors were found:" ShowMessageBox="false" ShowSummary="true" /> <asp:Button ID="btnSubmit" Text="Click this to test validation" runat="server"

/>

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

Output:

RequiredFieldValidatorSummary DisplayMode
.aspx Code: <%@ Page Language="C#" AutoEventWireup="true" Codevirtual="displayvalidation.aspx.cs" Inherits="displayvalidation" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title>Untitled Page</title> </head> <body> <form id="form1" runat="server"> <div> <asp:Label ID="lblMsg" Text="Please report your bug here" ForeColor="red" Font-Name="Verdana" Font-Size="10" runat=server /> <ASP:DropDownList id=ddlBooks runat=server> <asp:ListItem>-- Please Pick A Book --</asp:ListItem> <asp:ListItem>Programming ASP.NET</asp:ListItem> <asp:ListItem>Programming .NET Windows Applications</asp:ListItem> <asp:ListItem>Programming C#</asp:ListItem> <asp:ListItem>Programming Visual Basic 2005</asp:ListItem>

<asp:ListItem> Teach Yourself C++ In 21 Days </asp:ListItem> <asp:ListItem> Teach Yourself C++ In 64 Hours </asp:ListItem> <asp:ListItem>TY C++ In 10 Minutes</asp:ListItem> <asp:ListItem>C++ Unleashed</asp:ListItem> </ASP:DropDownList> </td> <!-- Validator for the drop down --> <td align=center rowspan=1> <asp:RequiredFieldValidator id="reqFieldBooks" ControlToValidate="ddlBooks" Display="Static" InitialValue="-- Please Pick A Book --" ErrorMessage = "You did not choose a book from the drop-down" Width="100%" runat=server> * </asp:RequiredFieldValidator> <td> <ASP:RadioButtonList id=rblEdition RepeatLayout="Flow" runat=server onselectedindexchanged="rblEdition_SelectedIndexChanged"> <asp:ListItem>1st</asp:ListItem> <asp:ListItem>2nd</asp:ListItem> <asp:ListItem>3rd</asp:ListItem> <asp:ListItem>4th</asp:ListItem> </ASP:RadioButtonList> </td> <td align=center rowspan=1> <asp:RequiredFieldValidator id="reqFieldEdition" ControlToValidate="rblEdition" ErrorMessage = "You did not pick an edition" Display="Static" InitialValue="" Width="100%" runat=server>*</asp:RequiredFieldValidator> <ASP:TextBox id=txtBug runat=server width="183px" textmode="MultiLine" height="68px"/> <asp:RequiredFieldValidator id="reqFieldBug" ControlToValidate="txtBug" ErrorMessage = "You must provide bug details" Display="Static" Width="100%" runat=server>*</asp:RequiredFieldValidator> <asp:DropDownList id="lstDisplay" AutoPostBack=true OnSelectedIndexChanged="lstDisplay_SelectedIndexChanged"

runat=server> <asp:ListItem Selected ="true">Summary</asp:ListItem> <asp:ListItem>Msg. Box</asp:ListItem> </asp:DropDownList> <asp:DropDownList id="lstFormat" AutoPostBack=true OnSelectedIndexChanged="lstFormat_SelectedIndexChanged" runat=server> <asp:ListItem>List</asp:ListItem> <asp:ListItem Selected="true">Bulleted List</asp:ListItem> <asp:ListItem>Single Paragraph</asp:ListItem> </asp:DropDownList> <ASP:Button id=btnSubmit text="Submit Bug" runat=server OnClick="btnSubmit_Click" /> <asp:ValidationSummary ID="ValSum" runat="server" DisplayMode="BulletList" HeaderText="The following errors were found: " ShowSummary="True" /> </div> </form> </body> </html>

.CS Code:

using using using using using using using using using using using using

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

public partial class displayvalidation : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } protected void lstFormat_SelectedIndexChanged(object sender, EventArgs e) { ValSum.DisplayMode = (ValidationSummaryDisplayMode)

lstFormat.SelectedIndex; } protected void lstDisplay_SelectedIndexChanged(object sender, EventArgs e) { ValSum.ShowSummary = lstDisplay.SelectedIndex == 0; ValSum.ShowMessageBox = lstDisplay.SelectedIndex == 1; } protected void btnSubmit_Click(object sender, EventArgs e) { if (Page.IsValid) { lblMsg.Text = "Page is Valid!"; } else { lblMsg.Text = "Some of the required fields are empty"; } } }

Output:

If You select Summary Then messagebox will be display

CompareValidator performs a comparison against a fixed value


.aspx Code:

<%@ Page Language="C#" AutoEventWireup="true" Codevirtual="comparevalidatior.aspx.cs" Inherits="comparevalidatior" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title>Untitled Page</title> </head> <body> <form id="form1" runat="server"> <div> <asp:Label id="lblDate"

Text="Date:" AssociatedControlID="txtDate" Runat="server" /> <asp:TextBox id="txtDate" Runat="server" /> <asp:CompareValidator id="cmpDate" Text="(Date must be greater than now)" ControlToValidate="txtDate" Type="Date" Operator="GreaterThan" Runat="server" /> <br /><br /> <asp:Button id="btnSubmit" Text="Submit" Runat="server" onclick="btnSubmit_Click" /> </div> </form> </body> </html>

.CS Code:

using using using using using using using using using using using using

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

public partial class comparevalidatior : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { cmpDate.ValueToCompare = DateTime.Now.ToString("d");

} }

Output:

CompareValidator compares the value of one form field against another form field

<%@ Page Language="C#" AutoEventWireup="true" Codevirtual="comparedate.aspx.cs" Inherits="comparedate" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head id="Head1" runat="server"> <title>Untitled Page</title> </head> <body> <form id="form1" runat="server"> <div> <asp:Label id="lblStartDate" Text="Start Date:" Runat="server" /> <asp:TextBox id="txtStartDate" Runat="server" /> &nbsp;&nbsp;&nbsp;&nbsp; <asp:Label id="lblEndDate" Text="End Date:" Runat="server" /> <asp:TextBox id="txtEndDate" Runat="server" /> <asp:CompareValidator id="cmpDate" Text="(End date must be greater than start date)" ControlToValidate="txtEndDate" ControlToCompare="txtStartDate" Type="Date" Operator="GreaterThan" Runat="server" /> <br /> <br /> <asp:Button id="btnSubmit" Text="Submit" Runat="server" /> </div> </form> </body> </html>

Output:

Using the CompareValidator to test values against other control values


<%@ Page Language="C#" AutoEventWireup="true" Codevirtual="comaprepassword.aspx.cs" Inherits="comaprepassword" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title>Untitled Page</title> </head> <body> <form id="form1" runat="server"> <div style="background-color: #99CCFF"> Password <asp:TextBox ID="TextBox1" Runat="server" TextMode="Password"></asp:TextBox> &nbsp;<br /> <br> &nbsp;Confirm Password <asp:TextBox ID="TextBox2" Runat="server" TextMode="Password"></asp:TextBox> &nbsp; <asp:CompareValidator ID="CompareValidator1" Runat="server" ErrorMessage="Passwords do not match!" ControlToValidate="TextBox2" ControlToCompare="TextBox1"></asp:CompareValidator> <br />

<asp:Button ID="Button1" OnClick="Button1_Click" Runat="server" Text="Login"></asp:Button> &nbsp;&nbsp;&nbsp;&nbsp; <asp:Label ID="Label1" Runat="server"></asp:Label> </div> </form> </body> </html>

Output:

CompareValidator for number, text and password

<%@ Page Language="C#" AutoEventWireup="true" Codevirtual="comparebirthday.aspx.cs" Inherits="comparebirthday" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title>Untitled Page</title> </head> <body> <form id="form1" runat="server"> <div> Sales Date: <asp:TextBox ID="txtDate" runat="server"></asp:TextBox> <asp:CompareValidator ID="compDate" runat="server" ControlToValidate="txtDate"

Operator="DataTypeCheck" Type="Date" Text="Enter a valid date" />

<br />

Quantity <asp:TextBox ID="txtQuantity" runat="server"></asp:TextBox> <asp:CompareValidator ID="compQuantity" runat="server" ControlToValidate="txtQuantity" Operator="DataTypeCheck" Type="Integer" Text="Enter a valid whole number" />

<br />

Enter Password:&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <asp:TextBox ID="txtPass1" runat="server" TextMode="password"></asp:TextBox> <br /> Reenter Password:&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <asp:TextBox ID="txtPass2" runat="server" TextMode="password"></asp:TextBox> <asp:CompareValidator ID="compPass" runat="server" ControlToValidate="txtPass2" Operator="Equal" ControlToCompare="txtPass1" Text="Passwords must match" /> <br /> &nbsp;<asp:Button ID="btnSubmit" Text="Click this to test validation" runat="server" /> </div> </form> </body> </html>

Output:

CompareValidator with age field

<%@ Page Language="C#" AutoEventWireup="true" Codevirtual="comparewithage.aspx.cs" Inherits="comparewithage" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title>Untitled Page</title> </head> <body> <form id="form1" runat="server"> <div style="width: 657px; background-color: #99CCFF;"> Username:&nbsp;&nbsp;&nbsp;&nbsp; <asp:TextBox id="usernameTextBox" runat="server" /> <asp:RequiredFieldValidator id="usernameReq" runat="server" ControlToValidate="usernameTextBox" ErrorMessage="Username is required!" SetFocusOnError="True" /> <br /> Password&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <asp:TextBox id="passwordTextBox" runat="server" TextMode="Password"

ontextchanged="passwordTextBox_TextChanged" /> &nbsp;&nbsp; <asp:RequiredFieldValidator id="passwordReq" runat="server" ControlToValidate="passwordTextBox" ErrorMessage="Password is required!" SetFocusOnError="True" Display="Dynamic" /> <br /> Confirmation :<asp:TextBox id="confirmPasswordTextBox" runat="server" TextMode="Password" /> <asp:RequiredFieldValidator id="confirmPasswordReq" runat="server" ControlToValidate="confirmPasswordTextBox" ErrorMessage="Password confirmation is required!" SetFocusOnError="True" Display="Dynamic" /> <asp:CompareValidator id="comparePasswords" runat="server" ControlToCompare="passwordTextBox" ControlToValidate="confirmPasswordTextBox" ErrorMessage="Your passwords do not match up!" Display="Dynamic" /> <br /> <!-- Age --> Age:&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <asp:TextBox id="ageTextBox" runat="server" /> <asp:RequiredFieldValidator id="ageReq" runat="server" ControlToValidate="ageTextBox" ErrorMessage="Age is required!" SetFocusOnError="True" Display="Dynamic" /> <asp:CompareValidator id="ageCheck" runat="server" Operator="GreaterThan" Type="Integer" ControlToValidate="ageTextBox" ValueToCompare="15" ErrorMessage="You must be 16 years or older to log in" /> <br /> &nbsp;&nbsp;&nbsp;&n <asp:Button id="submitButton" runat="server" Text="Submit" OnClick="submitButton_Click" /> </div> </form> </body> </html>

Output:

How to validate name Using Regular Expression

<%@ Page Language="C#" AutoEventWireup="true" Codevirtual="validation.aspx.cs" Inherits="validation" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title>Untitled Page</title> </head> <body> <form id="form1" runat="server"> <div> Name:<br /> <asp:TextBox ID="txtName" runat="server"></asp:TextBox> <asp:RegularExpressionValidator ID="regName" runat="server" ControlToValidate="txtName" ValidationExpression="^[a-zA-Z'.\s]{1,50}" Text="Enter a valid name" /> <br /> <br /> <asp:Button ID="btnSubmit" Text="Check Name" runat="server" onclick="btnSubmit_Click" /> </div> </form> </body> </html>

Output:

How to use Validation Group in ASP.NET

<%@ Page Language="C#" AutoEventWireup="true" Codevirtual="demovali.aspx.cs" Inherits="demovali" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title>Untitled Page</title> </head> <body> <form id="form1" runat="server"> <div> Username:<br /> <asp:TextBox id="usernameTextBox" runat="server" /> <asp:RequiredFieldValidator id="usernameReq" runat="server" ControlToValidate="usernameTextBox" ErrorMessage="Username is required!" SetFocusOnError="True" ValidationGroup="Login" /> Password:<br /> <asp:TextBox id="passwordTextBox" runat="server" TextMode="Password" /> <asp:RequiredFieldValidator id="passwordReq" runat="server" ControlToValidate="passwordTextBox"

ErrorMessage="Password is required!" SetFocusOnError="True" ValidationGroup="Login" /> <asp:Button ID="loginButton" runat="server" Text="Log In" ValidationGroup="Login" /> <h1>Register</h1> Username:<br /> <asp:TextBox id="newUserNameTextBox" runat="server" /> <asp:RequiredFieldValidator id="newUserNameReq" runat="server" ControlToValidate="newUserNameTextBox" ErrorMessage="Username is required!" SetFocusOnError="True" ValidationGroup="Register" /> Password:<br /> <asp:TextBox id="newPasswordTextBox" runat="server" TextMode="Password" /> <asp:RequiredFieldValidator id="newPasswordReq" runat="server" ControlToValidate="newPasswordTextBox" ErrorMessage="Password is required!" SetFocusOnError="True" ValidationGroup="Register" /> <asp:Button ID="registerButton" runat="server" Text="Register" ValidationGroup="Register" /> </div> </form> </body> </html>

Output:

Group based validation (C#)

<%@ Page Language="C#" AutoEventWireup="true" Codevirtual="validationgroup.aspx.cs" Inherits="validationgroup" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title>Untitled Page</title> </head> <body> <form id="form1" runat="server"> <div> <asp:Panel Height="112px" ID="Panel1" runat="server" Width="392px"> <asp:TextBox ID="TextBox1" runat="server" ValidationGroup="Group1"></asp:TextBox> <asp:RequiredFieldValidator ErrorMessage="*Required" ID="RequiredFieldValidator1"

iredFieldValidator> <asp:Button ID="Button1" runat="server" Text="Validate Group1" ValidationGroup="Group1" OnClick="Button_Click"/></asp:Panel>&nbsp;<br /> <asp:Panel Height="94px" ID="Panel2" runat="server" Width="392px" BorderWidth="2px"> <asp:TextBox ID="TextBox2" runat="server" ValidationGroup="Group2"></asp:TextBox> <asp:RequiredFieldValidator ErrorMessage="*Required" ID="RequiredFieldValidator2" runat="server" ValidationGroup="Group2" ControlToValidate="TextBox2"> </asp:RequiredFieldValidator><br /> <br /> <asp:Button ID="Button2" runat="server" Text="Validate Group2" ValidationGroup="Group2" OnClick="Button_Click"/></asp:Panel> <br /> </div> </form> </body> </html>

runat="server" ValidationGroup="Group1" ControlToValidate="TextBox1"></asp:Requ

How to Validate Form using Server Side Validation in ASp.NET


.CS Code: using using using using using using using using using using using using System; System.Collections; System.Configuration; System.Data; System.Linq; System.Web; System.Web.Security; System.Web.UI; System.Web.UI.HtmlControls; System.Web.UI.WebControls; System.Web.UI.WebControls.WebParts; System.Xml.Linq;

public partial class formvalidate : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } protected void OptionsChanged(object sender, EventArgs e) { foreach (BaseValidator valCtl in Page.Validators) { valCtl.Enabled = EnableValidators.Checked; valCtl.EnableClientScript = EnableClientSide.Checked; } ValidationSum.ShowMessageBox = ShowMsgBox.Checked;

ValidationSum.ShowSummary = ShowSummary.Checked; } protected void Submit_Click(object sender, EventArgs e) { if (Page.IsValid) Result.Text = "Thanks for sending your data"; else Result.Text = "There are some errors, please correct them and re-send the form."; } protected void CustomValidator1_ServerValidate(object source, ServerValidateEventArgs args) { try { args.IsValid = (int.Parse(args.Value) % 5 == 0); } catch { args.IsValid = false; } } protected void ValidateEmpID2_ServerValidate(object source, ServerValidateEventArgs args) { try { args.IsValid = (int.Parse(args.Value) % 5 == 0); } catch { args.IsValid = false; } } }

.aspx Code:

<%@ Page Language="C#" AutoEventWireup="true" Codevirtual="formvalidate.aspx.cs" Inherits="formvalidate" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server">

<title>Untitled Page</title> <script type="text/javascript" language="JavaScript"> function EmpIDClientValidate(ctl, args) { args.IsValid=(args.Value%5 == 0); } </script> <style type="text/css"> .style1 { font-family: "Arial Black"; } </style> </head> <body> <form id="form1" runat="server"> <div> <br /> <b> <br class="style1" /> <span class="style1">How to Form Validate in ASP.NET</span></b><br /> <br /> <br /> <br /> Name: <asp:TextBox runat="server" Width="200px" ID="Name" /> <asp:RequiredFieldValidator runat="server" ID="ValidateName" ControlToValidate="Name" ErrorMessage="Name is required" Display="dynamic">* </asp:RequiredFieldValidator> <asp:RegularExpressionValidator runat="server" ID="ValidateName2" ControlToValidate="Name" validationExpression="[a-z A-Z]*" ErrorMessage="Name cannot contain digits" Display="dynamic">* </asp:RegularExpressionValidator> <br /> ID (multiple of 5):&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &nbsp; <asp:TextBox runat="server" Width="200px" ID="EmpID" /> <asp:RequiredFieldValidator runat="server" ID="ValidateEmpID" ControlToValidate="EmpID" ErrorMessage="ID is required" Display="dynamic">* </asp:RequiredFieldValidator>

<asp:CustomValidator runat="server" ID="ValidateEmpID2" ControlToValidate="EmpID" ClientValidationFunction="EmpIDClientValidate" ErrorMessage="ID must be a multiple of 5" Display="dynamic" OnServerValidate="ValidateEmpID2_ServerValidat e">* </asp:CustomValidator> <br /> Day off:<small>08/08/08-08/20/08 </small> &nbsp;<asp:TextBox runat="server" Width="200px" ID="DayOff" /> <asp:RequiredFieldValidator runat="server" ID="ValidateDayOff" ControlToValidate="DayOff" ErrorMessage="Day Off is required" Display="dynamic">* </asp:RequiredFieldValidator> <asp:RangeValidator runat="server" ID="ValidateDayOff2" ControlToValidate="DayOff" MinimumValue="08/08/2008" MaximumValue="08/20/2008" Type="Date" ErrorMessage="Day Off is not within the valid interval" Display="dynamic" SetFocusOnError="True">* </asp:RangeValidator> <br /> Age&nbsp<small>( >= 18 )</small>:</td> <asp:TextBox runat="server" Width="200px" ID="Age" /> <asp:RequiredFieldValidator runat="server" ControlToValidate="Age" ErrorMessage="Age is required" Display="dynamic" ID="Requiredfieldvalidator1" Name="Requiredfieldvalidator1">* </asp:RequiredFieldValidator> <asp:CompareValidator runat="server" ID="ValidateAge" ControlToValidate="Age" ValueToCompare="18" Type="Integer" Operator="GreaterThanEqual" ErrorMessage="You must be at least 18-year-old" Display="dynamic">* </asp:CompareValidator> <br /> E-mail: <asp:TextBox runat="server" Width="200px" ID="Email" /> <asp:RequiredFieldValidator runat="server"

ControlToValidate="Email" ErrorMessage="E-mail is required" Display="dynamic" ID="Requiredfieldvalidator2" Name="Requiredfieldvalidator2">* </asp:RequiredFieldValidator> <asp:RegularExpressionValidator runat="server" ID="ValidateEmail" ControlToValidate="Email" validationExpression=".*@.{2,}\..{2,}" ErrorMessage="E-mail is not in a valid format" Display="dynamic">* </asp:RegularExpressionValidator> <br /> Password: <asp:TextBox TextMode="Password" runat="server" Width="200px" ID="Password" /> <asp:RequiredFieldValidator runat="server" ControlToValidate="Password" ErrorMessage="Password is required" Display="dynamic" ID="Requiredfieldvalidator3" Name="Requiredfieldvalidator3"> <img src="" border="0"> </asp:RequiredFieldValidator> <br /> Re-enter Password: <asp:TextBox runat="server" TextMode="Password" Width="200px" ID="Password2" /> <asp:RequiredFieldValidator runat="server" ControlToValidate="Password2" ErrorMessage="Password2 is required" Display="dynamic" ID="Requiredfieldvalidator4" Name="Requiredfieldvalidator4"> <img src="" border="0"> </asp:RequiredFieldValidator> &nbsp;<br /> <asp:Button runat="server" Text="Submit" ID="Submit" OnClick="Submit_Click" /><BR> <asp:CheckBox runat="server" ID="EnableValidators" Checked="True" AutoPostBack="True" Text="Validators enabled" OnCheckedChanged="OptionsChanged" /> <asp:CheckBox runat="server" ID="EnableClientSide" Checked="True" AutoPostBack="True" Text="Client-side validation enabled" OnCheckedChanged="OptionsChanged" /> <asp:CheckBox runat="server" ID="ShowSummary" Checked="True" AutoPostBack="True" Text="Show summary" OnCheckedChanged="OptionsChanged" /> <asp:CheckBox runat="server" ID="ShowMsgBox"

Checked="False" AutoPostBack="True" Text="Show message box" OnCheckedChanged="OptionsChanged" /> <asp:ValidationSummary runat="server" ID="ValidationSum" DisplayMode="BulletList" HeaderText="<b>Please review the following errors:</b>" ShowSummary="true" ShowMessageBox="false" /> <asp:Label runat="server" ID="Result" ForeColor="magenta" FontBold="true" EnableViewState="False" /> </div> </form> </body> </html>

Output:

How to Enter only Ten Character in Textbox Using Custom validation


.aspx Code

<%@ Page Language="C#" AutoEventWireup="true" Codevirtual="customvalidation.aspx.cs" Inherits="customvalidation" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title>Untitled Page</title> </head> <body> <form id="form1" runat="server"> <div> <asp:Label id="lblComments" Text="Comments:" AssociatedControlID="txtComments" Runat="server" /> <asp:TextBox id="txtComments" TextMode="MultiLine" Columns="30" Rows="5" Runat="server" /> <asp:CustomValidator id="valComments" ControlToValidate="txtComments" Text="(Comments must be less than 10 characters)" OnServerValidate="valComments_ServerValidate" Runat="server" /> <br /> <br /> <asp:Button id="btnSubmit" Text="Submit" Runat="server" onclick="btnSubmit_Click" style="width: 61px" /> </div> </form> </body> </html>

.CS Code:

using System; using System.Collections;

using using using using using using using using using using

System.Configuration; System.Data; System.Linq; System.Web; System.Web.Security; System.Web.UI; System.Web.UI.HtmlControls; System.Web.UI.WebControls; System.Web.UI.WebControls.WebParts; System.Xml.Linq;

public partial class customvalidation : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } protected void btnSubmit_Click(object sender, EventArgs e) { } protected void valComments_ServerValidate(object source, ServerValidateEventArgs args) { if (args.Value.Length > 10) args.IsValid = false; else args.IsValid = true; } }

Output:

How to Create a Login Page Using Form Authentication


.aspx Code <%@ Page Language="C#" AutoEventWireup="true" Codevirtual="authntication.aspx.cs" Inherits="authntication" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title>Untitled Page</title> </head> <body> <form id="form1" runat="server"> <div> <asp:Label id="lblError" EnableViewState="false" ForeColor="Red" Runat="server" /> <br /><br /> <asp:Label id="lblUserName" Text="User Name:" AssociatedControlID="txtUserName" Runat="server" /> <asp:TextBox id="txtUserName" Runat="server" />

<br /><br /> <asp:Label id="lblPassword" Text="Password:" AssociatedControlID="txtPassword" Runat="server" /> &nbsp; <asp:TextBox id="txtPassword" TextMode="Password" Runat="server" /> <br /><br /> <asp:CheckBox id="chkRememberMe" Text="Remember Me" Runat="server" /> <br /><br /> <asp:Button id="btnLogin" Text="Login" OnClick="btnLogin_Click" Runat="server" /> </div> </form> </body> </html>

.CS Code: using using using using using using using using using using using using System; System.Collections; System.Configuration; System.Data; System.Linq; System.Web; System.Web.Security; System.Web.UI; System.Web.UI.HtmlControls; System.Web.UI.WebControls; System.Web.UI.WebControls.WebParts; System.Xml.Linq;

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

if (FormsAuthentication.Authenticate(txtUserName.Text, txtPassword.Text)) { FormsAuthentication.RedirectFromLoginPage(txtUserName.Text, chkRememberMe.Checked); Response.Redirect("Home.aspx");// set Your redirect page } else lblError.Text = "Invalid user name/password"; } }

Output:

How to Use Logout Method Using Authentication


.aspx.code <%@ Page Language="C#" AutoEventWireup="true" Codevirtual="logout.aspx.cs" Inherits="logout" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title>Untitled Page</title> </head> <body> <form id="form1" runat="server"> <div>

<asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Logout" /> </div> </form> </body> </html>

.CS Code:

using using using using using using using using using using using using

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

public partial class logout : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } protected void Button1_Click(object sender, EventArgs e) { FormsAuthentication.SignOut(); Response.Redirect("Home.aspx"); } }

Count Number of Visitors in WebSite using ASP.Net and C#


RightClick in Solution Explorer>> Addnewitem>> Like this

Write Code in Global.asax file

<%@ Application Language="C#" %> <script runat="server"> public static int count = 0; void Application_Start(object sender, EventArgs e) { Application["myCount"] = count; // 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) { count = Convert.ToInt32(Application["myCount"]); Application["myCount"] = count + 1; // 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. } </script>

.CS Code:

using using using using using using using using using using using using

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

public partial class Hitcounter : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { int a; a = Convert.ToInt32((Application["myCount"])); Label1.Text = Convert.ToString(a); if (a < 10)

} }

Label1.Text = "000" + Label1.Text; else if (a < 100) Label1.Text = "00" + Label1.Text; else if (a < 1000) Label1.Text = "0" + Label1.Text;

Output:

When Anyone Visit your Website then Total Visitor will be increased.

Writing XML File using XmlWriter in ASP.NET


Add Namespace: Using System.XML; .CS Code:

protected void Button1_Click(object sender, EventArgs e) { XmlDocument XDoc = new XmlDocument(); // Create root node. XmlElement XElemRoot = XDoc.CreateElement("Test"); XElemRoot.SetAttribute("hiiiiiiiiiiiii","ashish"); //Add the node to the document. XDoc.AppendChild(XElemRoot); XmlElement Xsource = XDoc.CreateElement("source");

XElemRoot.AppendChild(Xsource); XmlElement XTemp = XDoc.CreateElement("ID"); XTemp.InnerText = "Test"; Xsource.AppendChild(XTemp); XTemp = XDoc.CreateElement("UserName"); XTemp.InnerText = "username"; Xsource.AppendChild(XTemp); XTemp = XDoc.CreateElement("Password"); XTemp.InnerText = "password"; Xsource.AppendChild(XTemp); XDoc.Save(@"C:\test1.xml"); }

Output:

A Simple DropDownList of links in ASP.NET Using C#


In this Example I add a DropDownList to an aspx page using c# that contains links that go on selection to either other pages on the site or other web site urls? With or without the Go button is fine.

using using using using using

System; System.Configuration; System.Data; System.Linq; System.Web;

using using using using using using

System.Web.Security; System.Web.UI; System.Web.UI.HtmlControls; System.Web.UI.WebControls; System.Web.UI.WebControls.WebParts; System.Xml.Linq;

public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { DropdownList1.Items.Add(new ListItem("Yahoo", "http://www.yahoo.com")); DropdownList1.Items.Add(new ListItem("Google", "http://www.google.com")); DropdownList1.Items.Add(new ListItem("CodingForums", "http://www.codingforums.com")); } protected void Button1_Click(object sender, EventArgs e) { Response.Redirect(DropDownList1.SelectedValue); } }

When You Click on Browser It open dropdown selected value: Bind all column names in one Dropdownlist in ASP.NET using c#

using using using using using using using using using using using using

System; System.Configuration; System.Data; System.Linq; System.Web; System.Web.Security; System.Web.UI; System.Web.UI.HtmlControls; System.Web.UI.WebControls; System.Web.UI.WebControls.WebParts; System.Xml.Linq; System.Data.OleDb;

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

OleDbConnection cn = new OleDbConnection ("provider=microsoft.jet.oledb.4.0;data source=E:\\Invent.mdb"); protected void Page_Load(object sender, EventArgs e) { cn.Open(); string strQuery = "Select * from purchasing"; OleDbDataAdapter da = new OleDbDataAdapter(strQuery, cn); DataSet ds = new DataSet(); da.Fill(ds); foreach (DataRow r in ds.Tables[0].Rows) { DropDownList1.Items.Add(r[0].ToString() + " " + r[2].ToString() +" "+" "+r[3].ToString()); //Add 7 columns } } }

Output:

Bind an ASP.NET DropDownList to a Dictionary using System.Collections.Generic you can customize your dropdownlist items.

using using using using using using

System; System.Collections; System.Configuration; System.Data; System.Linq; System.Web;

using using using using using using using

System.Web.Security; System.Web.UI; System.Web.UI.HtmlControls; System.Web.UI.WebControls; System.Web.UI.WebControls.WebParts; System.Xml.Linq; System.Collections.Generic;

public partial class dropdatain_dictonary : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { Dictionary<int, string> dicRel = new Dictionary<int, string>(); dicRel.Add(1, "Father"); dicRel.Add(2, "Mother"); dicRel.Add(3, "Brother"); dicRel.Add(4, "Sister"); dicRel.Add(5, "Others"); ddlRelatives.DataSource = dicRel; ddlRelatives.DataTextField = "Value"; ddlRelatives.DataValueField = "Key"; } } ddlRelatives.DataBind();

.aspx code:

<%@ Page Language="C#" AutoEventWireup="true" Codevirtual="dropdatain dictonary.aspx.cs" Inherits="dropdatain_dictonary" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title>Untitled Page</title> </head> <body>

<form id="form1" runat="server"> <div> <asp:DropDownList ID="ddlRelatives" runat="server"> </asp:DropDownList> </div> </form> </body> </html>

Output:

Convert Time in Different TimeZones in ASP.NET using C#


.CS CODE:

using using using using using using using using using using using using using using

System; System.Collections; System.Configuration; System.Data; System.Linq; System.Web; System.Web.Security; System.Web.UI; System.Web.UI.HtmlControls; System.Web.UI.WebControls; System.Web.UI.WebControls.WebParts; System.Xml.Linq; System.Collections; System.Collections.ObjectModel;

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

lblLocalTime.Text = DateTime.Now.ToString(); ReadOnlyCollection<TimeZoneInfo> tzi; tzi = TimeZoneInfo.GetSystemTimeZones(); foreach (TimeZoneInfo timeZone in tzi) { ddlTimeZone.Items.Add(new ListItem(timeZone.DisplayName, timeZone.Id)); } } } protected void ddlTimeZone_SelectedIndexChanged(object sender, EventArgs e) { if (ddlTimeZone.SelectedIndex > 0) { DateTime dt = DateTime.Now; lblTimeZone.Text = TimeZoneInfo.ConvertTimeBySystemTimeZoneId(dt, TimeZoneInfo.Local.Id, ddlTimeZone.SelectedValue).ToString(); } } }

.aspx Code:

<%@ Page Language="C#" AutoEventWireup="true" Codevirtual="converdatareadertodatatable.aspx.cs" Inherits="converdatareadertodatatable" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title>Untitled Page</title> </head> <body> <form id="form1" runat="server"> <div> <asp:DropDownList ID="ddlTimeZone" runat="server" AutoPostBack="True" AppendDataBoundItems="true" onselectedindexchanged="ddlTimeZone_SelectedIndexChanged" style="height: 22px" > <asp:ListItem Text="Select a TimeZone" Value="Default value" /> </asp:DropDownList> <br /><br />

Local Time: <asp:Label ID="lblLocalTime" runat="server" Text=""></asp:Label> <br /><br /> Converted Time: <asp:Label ID="lblTimeZone" runat="server" Text=""></asp:Label> </div> </form> </body> </html>

Output:

Export gridview to pdf in asp.net using c#

Download itextsharp.dll
.CS Code:

using using using using using using using using using using using using using

System; System.Collections; System.Configuration; System.Data; System.Linq; System.Web; System.Web.Security; System.Web.UI; System.Web.UI.HtmlControls; System.Web.UI.WebControls; System.Web.UI.WebControls.WebParts; System.Xml.Linq; iTextSharp.text.pdf;

using iTextSharp.text.html; using iTextSharp.text.html.simpleparser; using System.IO;

using iTextSharp.text; public partial class pdf_genration : System.Web.UI.Page { DataSet ds=new DataSet(); protected void Page_Load(object sender, EventArgs e) { ds.ReadXml(MapPath("Regis.xml")); GridView1.DataSource = ds; //DataGrid1.DataSource = ds; GridView1.DataBind(); } public override void VerifyRenderingInServerForm(Control control)// this Event is must for Rendring { } protected void Button1_Click(object sender, EventArgs e) { Response.Clear(); //this clears the Response of any headers or previous output Response.Buffer = true; //ma Response.ContentType = "application/pdf"; Response.AddHeader("content-disposition", "attachment;filename=DataTable.pdf"); che); Response.Cache.SetCacheability(HttpCacheability.NoCa StringWriter sw = new StringWriter(); HtmlTextWriter hw = new HtmlTextWriter(sw); GridView1.RenderControl(hw); StringReader sr = new StringReader(sw.ToString()); Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 10f, 0f); HTMLWorker htmlparser = new HTMLWorker(pdfDoc); PdfWriter.GetInstance(pdfDoc, Response.OutputStream); pdfDoc.Open();

htmlparser.Parse(sr); pdfDoc.Close(); Response.Write(pdfDoc); Response.End(); } }

.aspx Code:

<%@ Page Language="C#" AutoEventWireup="true" Codevirtual="pdf genration.aspx.cs" Inherits="pdf_genration" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title>Untitled Page</title> </head> <body> <form id="form1" runat="server"> <div> <asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Export Gridview" /> <asp:GridView ID="GridView1" runat="server" Width="591px"> </asp:GridView> </div> </form> </body> </html>

Output:

When You Click On ExportGridview Button All gridview Data is bind In pdffile Like this:

How to Add Image in PDf ASP.NET using C#

Download itextsharp.dll
.CS CODE: using using using using using System; System.Collections; System.Configuration; System.Data; System.Linq;

using using using using using using using using using using

System.Web; System.Web.Security; System.Web.UI; System.Web.UI.HtmlControls; System.Web.UI.WebControls; System.Web.UI.WebControls.WebParts; System.Xml.Linq; System.Data.OleDb; System.IO; iTextSharp.text;

using iTextSharp.text.pdf; using iTextSharp.text.html; using iTextSharp.text.html.simpleparser;

public partial class excel_data_to_gridview : System.Web.UI.Page { DataSet ds = new DataSet(); protected void Page_Load(object sender, EventArgs e) { Response.Clear(); //this clears the Response of any headers or previous output Response.Buffer = true; //make sure that the entire output is rendered simultaneously ds.ReadXml(MapPath("Regis.xml")); GridView1.DataSource = ds; GridView1.DataBind(); } protected void Button1_Click(object sender, EventArgs e) {

Response.ContentType = "application/pdf"; Response.AddHeader("content-disposition", "attachment;filename=DataTable.pdf");

Response.Cache.SetCacheability(HttpCacheability.NoCache);

StringWriter sw = new StringWriter(); HtmlTextWriter hw = new HtmlTextWriter(sw); GridView1.RenderControl(hw); StringReader sr = new StringReader(sw.ToString()); Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 10f, 0f); HTMLWorker htmlparser = new HTMLWorker(pdfDoc); PdfWriter.GetInstance(pdfDoc, Response.OutputStream);

// Now image in the pdf file string imageFilePath = Server.MapPath(".") + "/image/aa.jpg"; iTextSharp.text.Image jpg = iTextSharp.text.Image.GetInstance(imageFilePath); //Resize image depend upon your need jpg.ScaleToFit(280f, 260f); //Give space before image jpg.SpacingBefore = 30f; //Give some space after the image jpg.SpacingAfter = 1f; jpg.Alignment = Element.ALIGN_CENTER; // doc.Add(paragraph); // add paragraph to the document pdfDoc.Open(); pdfDoc.Add(jpg); htmlparser.Parse(sr); pdfDoc.Close(); Response.Write(pdfDoc); Response.End();

public override void VerifyRenderingInServerForm(Control control) {

} }

.ASPX CODE:

<%@ Page Language="C#" AutoEventWireup="true" Trace="true" TraceMode = "SortByTime" Codevirtual="excel data to gridview.aspx.cs" Inherits="excel_data_to_gridview" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title>Untitled Page</title> </head> <body> <form id="form1" runat="server"> <div> <asp:GridView ID="GridView1" runat="server"> </asp:GridView> <asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Export PDF File" />

</div>

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

Output:

How to Find String in RichtextBox


.CS Code:

using using using using

System; System.Collections.Generic; System.ComponentModel; System.Data;

using using using using

System.Drawing; System.Linq; System.Text; System.Windows.Forms;

namespace WindowsFormsApplication53 { public partial class Form4 : Form { public Form4() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { string wordToFind = textBox1.Text; int startIndex = 0; while (startIndex > -1) { startIndex = richTextBox1.Find(wordToFind, startIndex + 1, richTextBox1.Text.Length, RichTextBoxFinds.WholeWord); if (startIndex > -1) { richTextBox1.Select(startIndex, wordToFind.Length); richTextBox1.SelectionFont = new Font("Verdana", 12, FontStyle.Bold | FontStyle.Italic); richTextBox1.SelectionColor = Color.Red; } else { MessageBox.Show("String not Found"); } } } } }

Output:

How to Fill Ellipse with Brush in ASP.NET Using C#


.CS Code:

using using using using using using using using using using using using using using

System; System.Collections; System.Configuration; System.Data; System.Linq; System.Web; System.Web.Security; System.Web.UI; System.Web.UI.HtmlControls; System.Web.UI.WebControls; System.Web.UI.WebControls.WebParts; System.Xml.Linq; System.Drawing; System.Drawing.Imaging;

public partial class drawellipse : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { Bitmap b = new Bitmap(150, 150, PixelFormat.Format32bppArgb); Graphics g = Graphics.FromImage(b); Brush br = Brushes.Green; g.FillEllipse(br, 5, 5, 140, 140); Response.ContentType = "image/gif"; b.Save(Response.OutputStream, ImageFormat.Gif);

} }

b.Dispose();

Output:

How to create custom error reporting pages in ASP.NET by using Visual C# .NET
The <customErrors> tag in ASP.NET Web configuration files affects how error pages are managed in an ASP.NET application and whether developers can redirect users or Visitor to their custom error pages when an exception is thrown. The syntax for this tag is:

<customErrors mode="On|Off|RemoteOnly" defaultRedirect="url"> <error statusCode="statuscode" redirect="url"/> </customErrors>

Mode parameter can have three possible values: RemoteOnly - this is default value, detailed messages are shown if you access through a localhost, and more general (default) error message to remote visitors.

On - default error message is shown to everyone. This could be a security problem since part of source code where error occurred is shown too. Off - detailed error message is shown to everyone. Default ASP.NET error message hides details about error, but still is not user friendly. Instead of this page, ASP.NET allows you to create your own error page. After custom error page is created, you need to add a reference to it in customErrors section by using a defaultRedirect parameter, like in code snippet bellow:

<customErrors mode="RemoteOnly" defaultRedirect="~/DefaultErrorPage.aspx" />

When error occured, ASP.NET runtime will redirect visitor to DefaultErrorPage.aspx. On custom error page you can gently inform your visitors what happened and what they can do about it. DefaultErrorPage.aspx will display when any error occurs. Also, there is a possibility to show different custom error pages for different types of exceptions. We can do that by using <error > sub tag. In code sample bellow, specialized pages are shown for errors 404 (File Not Found) and error 403 (Forbidden).

<customErrors mode="On" defaultRedirect="~/DefaultErrorPage.aspx" > <error statusCode="404" redirect="~/FileNotFound.htm"/> <error statusCode="403" redirect="~/Forbidden.htm"/> </customErrors>

How Dynamically Add Rows into ASP.NET Table using C#


.CS Code:

protected void Page_Load(object sender, EventArgs e) { TableRow tr = new TableRow(); TableCell tc = new TableCell(); tc.Text = "r4r.co.in"; tr.Cells.Add(tc); TableCell tc2 = new TableCell(); tc2.Text = "Hello";

tr.Cells.Add(tc2); Table1.Rows.Add(tr); }

Output:

How to make CountDown Timer in ASP.NET Using C#


.CS CODE:

int totalSeconds = 0; int seconds = 0; int minutes = 0; string time = "";

protected void Page_Load(object sender, EventArgs e) { if (!Page.IsPostBack) { Session["time"] = 1800 ; } } protected void Timer1_Tick(object sender, EventArgs e) { Session["time"] = Convert.ToInt16(Session["time"]) 1; if (Convert.ToInt16(Session["time"]) <= 0) { label_time.Text = "TimeOut!";

insert_result(); Response.Redirect("Show_result.aspx"); } else { totalSeconds = Convert.ToInt16(Session["time"]); seconds = totalSeconds % 60; minutes = totalSeconds / 60; time = minutes + ":" + seconds; label_time.Text = time; } }

How to Refresh an ASP.NET GridView automatically at regular Intervals


In this Tutorial Discribe how to refresh the GridView after regular intervals. Add the GridView and the Timer control inside an ASP.NET AJAX UpdatePanel as shown below :

<%@ Page Language="C#" AutoEventWireup="true" Codevirtual="how to refresh gridview at regularinterval.aspx.cs" Inherits="how_to_refresh_gridview_at_regularinterval" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title>Untitled Page</title> </head> <body> <form id="form1" runat="server"> <div> <asp:UpdatePanel ID="UpdatePanel1" runat="server"> <ContentTemplate> <asp:Timer ID="Timer1" runat="server" Interval="3600" ontick="Timer1_Tick"></asp:Timer> <asp:GridView ID="GridView2" runat="server" AutoGenerateColumns="False" DataKeyNames="CustomerID" DataSourceID="SqlDataSource1" AllowPaging="True" AllowSorting="True">

<Columns> <asp:BoundField DataField="CustomerID" HeaderText="CustomerID" ReadOnly="True" SortExpression="CustomerID" /> <asp:BoundField DataField="CompanyName" HeaderText="CompanyName" SortExpression="CompanyName" /> <asp:BoundField DataField="ContactName" HeaderText="ContactName" SortExpression="ContactName" /> <asp:BoundField DataField="Address" HeaderText="Address" SortExpression="Address" /> <asp:BoundField DataField="City" HeaderText="City" SortExpression="City" /> </Columns> </asp:GridView> </ContentTemplate> </asp:UpdatePanel> </div> </form> </body> </html>

Then in the code behind, add the following code which refreshes the GridView after every minute .CS Code:

protected void Timer1_Tick(object sender, EventArgs e) { Databind();// method in binding data in gridview (write code) }

Calculate Firstdate And Lastdate of Month in ASP.NET Using C#


.CS COde

using using using using using using using using using using using using

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

public partial class calculate_date : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } protected void Button1_Click(object sender, EventArgs e) { DateTime today = DateTime.Now; //current date DateTime firstDay = today.AddDays(-(today.Day - 1)); //first day today = today.AddMonths(1); DateTime lastDay = today.AddDays(-(today.Day)); //last day Label1.Text = firstDay.ToString(); ; Label2.Text = lastDay.ToString(); } }

Click On Button And Display Output Like This: Output:

How to get the list of ADO.NET data providers registered in the machine and application configuration file
using System; using System.Configuration; using System.Data;

using System.Linq; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.HtmlControls; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Xml.Linq; using System.Data.SqlClient; using System.Data.Common; ///Import New NameSpace public partial class _Default : System.Web.UI.Page { SqlConnection newConnection = new SqlConnection(@"Data Source=R4R-3EFD13BB468; initial catalog=newDatabase;integrated security=true;"); protected void Page_Load(object sender, EventArgs e) { DataTable provider = new DataTable(); provider = DbProviderFactories.GetFactoryClasses(); foreach (DataRow row in provider.Rows) { Response.Write(" <b>Name:</b> "+row["Name"].ToString()); Response.Write(" <b>Description:</b> " + row["InvariantName"].ToString()); Response.Write(" <b>Invarient Name:</b> " + row["Description"].ToString()); } } }

Out Put:

How To Create a Directory using C# in ASP .NET


Design Code: <%@ Page Language="C#" AutoEventWireup="true" Codevirtual="Default.aspx.cs" Inherits="_Default" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title>Untitled Page</title> </head> <body> <form id="form1" runat="server"> <div> <asp:Button ID="Button1" runat="server" Text="Create Directory" onclick="Button1_Click" /> <br /><br /> <asp:Label ID="Label1" runat="server" Text=""></asp:Label>

</div> </form> </body> </html> Default.aspx.cs: using System; using System.Configuration; using System.Data; using System.Linq; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.HtmlControls; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Xml.Linq; using System.IO; public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } public void createDirectory(string newDirectory) { if (!Directory.Exists(newDirectory)) { Directory.CreateDirectory(newDirectory); Label1.Text = "Directory Created"; } else { Label1.Text = "Directory Exist"; } } protected void Button1_Click(object sender, EventArgs e) { string NewDirectory = Server.MapPath("Aditya"); createDirectory(NewDirectory); } } Out Put:

See your Solution Explorer

How to Use Validation Summary in ASP .NET using C#


Design Code <%@ Page Language="C#" AutoEventWireup="true" Codevirtual="Default.aspx.cs" Inherits="_Default" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head id="Head1" runat="server"> <title>Untitled Page</title> </head> <body>

<form id="form1" runat="server"> <div> Select Course <asp:DropDownList ID="ListBooks" runat="server"> <asp:ListItem Value="0" Selected="True">--select book-</asp:ListItem> <asp:ListItem Value="1">C#(Black Book)</asp:ListItem> <asp:ListItem Value="2">Asp.net(Black Book)</asp:ListItem> <asp:ListItem Value="3">Ajax</asp:ListItem> </asp:DropDownList> <asp:RequiredFieldValidator ID="reqBook" runat="server" ControlToValidate="ListBooks" SetFocusOnError="true" Text="*" InitialValue="0" Display="static" ErrorMessage="Please choose a book from list"/> <br /> User Name:<asp:TextBox ID="txtUserName" runat="server"></asp:TextBox> <asp:RequiredFieldValidator ID="reqUserName" runat="server" ControlToValidate="txtUserName" SetFocusOnError="true" Text="*" Display="static" ErrorMessage="Please enter a User Name"/><br /> Password: <asp:TextBox ID="txtPassword" runat="server"></asp:TextBox> <asp:RequiredFieldValidator ID="reqPassword" runat="server" ControlToValidate="txtPassword" SetFocusOnError="true" Text="*" Display="static" ErrorMessage="Please enter a password"/><br /><br /> <asp:ValidationSummary id="valSum" runat="server" DisplayMode="BulletList" HeaderText="The following errors were found:" ShowMessageBox="false" ShowSummary="true" /><br /><br /><br /> <asp:Button ID="btnSubmit" Text="Check Validations" runat="server" /> </div> </form> </body> </html> Out Put:

How to Load XML to DataSet in ASP.Net using C#


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

public partial class _Default : System.Web.UI.Page { SqlConnection newConnection = new SqlConnection(@"Data Source=R4R-3EFD13BB468; initial catalog=newDatabase;integrated security=true;");

protected void Page_Load(object sender, EventArgs e) { SqlDataAdapter MyAdapter = new SqlDataAdapter("select * from emp_tbl", newConnection); DataSet MyDataSet = new DataSet(); MyAdapter.Fill(MyDataSet); MyDataSet.WriteXml(@"c:\Sample.xml"); } } Out Put:

How to DataSet Merge in ASP.NET using C#


using System; using System.Configuration; using System.Data;

using using using using using using using using using

System.Linq; System.Web; System.Web.Security; System.Web.UI; System.Web.UI.HtmlControls; System.Web.UI.WebControls; System.Web.UI.WebControls.WebParts; System.Xml.Linq; System.Data.SqlClient;

public partial class _Default : System.Web.UI.Page { SqlConnection newConnection = new SqlConnection(@"Data Source=R4R-3EFD13BB468; initial catalog=newDatabase;integrated security=true;"); protected void Page_Load(object sender, EventArgs e) { SqlDataAdapter MyAdapter = new SqlDataAdapter("select * from emp_tbl", newConnection); DataSet MyDataSet = new DataSet(); MyAdapter.Fill(MyDataSet); MyAdapter = new SqlDataAdapter("select * from emp_tbl", newConnection); DataSet ds = new DataSet(); MyAdapter.Fill(ds); MyDataSet.Merge(ds); GridView1.DataSource = MyDataSet; GridView1.DataBind(); } }

Out Put:

How to create an application domain in ASP .NET using C#


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

public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { AppDomain d = AppDomain.CreateDomain("AdityaDomain"); Response.Write(AppDomain.CurrentDomain.FriendlyNam e); Response.Write(d.FriendlyName); } } Out Put:

Updating Data Using Transactions in ASP .Net using C#


using System; using System.Configuration; using System.Data; using System.Linq; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.HtmlControls; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Xml.Linq; using System.Data.SqlClient; public partial class _Default : System.Web.UI.Page { SqlConnection newConnection = new SqlConnection(@"Data Source=R4R-3EFD13BB468; initial catalog=newDatabase;integrated security=true;"); protected void Page_Load(object sender, EventArgs e) { newConnection.Open(); SqlTransaction newTransaction=newConnection.BeginTransaction(); SqlCommand cmd=new SqlCommand("insert into emp_tbl(emp_id,emp_name,emp_age) values(234,'prem',23)",newConnection,newTransaction); cmd.ExecuteScalar(); newTransaction.Commit();

newConnection.Close(); } }

Out Put:

How to Read Bitmap from database in ASP .NET


using System; using System.Configuration; using System.Data; using System.Linq; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.HtmlControls; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Xml.Linq; using System.Data.SqlClient; public partial class _Default : System.Web.UI.Page { SqlConnection newConnection = new SqlConnection(@"Data Source=R4R-3EFD13BB468; initial catalog=newDatabase;integrated security=true;"); protected void Page_Load(object sender, EventArgs e) { newConnection.Open(); SqlCommand cmd = new SqlCommand(@"select imagefile,imagedata from imagetable ", newConnection); SqlDataReader dr = cmd.ExecuteReader(); string imageFilename = (string)dr.GetValue(0); byte[] imageBytes = (byte[])dr.GetValue(1); MemoryStream ms = new MemoryStream(imageBytes);

Bitmap bmap = new Bitmap(ms); newConnection.Close(); } }

The image will be selected and you will be used it. How to Create DataViews from DataTable in ASP .NET using C#
using System; using System.Configuration; using System.Data; using System.Linq; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.HtmlControls; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Xml.Linq; using System.Data.SqlClient; public partial class _Default : System.Web.UI.Page { SqlConnection newConnection = new SqlConnection(@"Data Source=R4R-3EFD13BB468; initial catalog=newDatabase;integrated security=true;"); protected void Page_Load(object sender, EventArgs e) { newConnection.Open(); SqlDataAdapter da = new SqlDataAdapter ("select emp_id,emp_name,emp_age from emp_tbl",newConnection); DataSet ds = new DataSet(); da.Fill(ds, "emp_tbl"); DataTable dt = ds.Tables["emp_tbl"]; DataView dv = new DataView(dt, "emp_name = 'Anjali'", "emp_name", DataViewRowState.CurrentRows); GridView1.DataSource = dv; GridView1.DataBind(); newConnection.Close(); } } Out Put:

Show in a Message Box using Validation Summary


<%@ Page Language="C#" AutoEventWireup="true" Codevirtual="Default.aspx.cs" Inherits="_Default" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head id="Head1" runat="server"> <title>Untitled Page</title> </head> <body> <form id="form1" runat="server"> <div> Select Course <asp:DropDownList ID="ListBooks" runat="server"> <asp:ListItem Value="0" Selected="True">--select book-</asp:ListItem> <asp:ListItem Value="1">C#(Black Book)</asp:ListItem> <asp:ListItem Value="2">Asp.net(Black Book)</asp:ListItem> <asp:ListItem Value="3">Ajax</asp:ListItem> </asp:DropDownList> <asp:RequiredFieldValidator ID="reqBook" runat="server" ControlToValidate="ListBooks" SetFocusOnError="true" Text="*" InitialValue="0" Display="static" ErrorMessage="Please choose a book from list"/> <br /> User Name:<asp:TextBox ID="txtUserName" runat="server"></asp:TextBox> <asp:RequiredFieldValidator ID="reqUserName" runat="server" ControlToValidate="txtUserName" SetFocusOnError="true" Text="*" Display="static" ErrorMessage="Please enter a User Name"/><br />

Password: <asp:TextBox ID="txtPassword" runat="server"></asp:TextBox> <asp:RequiredFieldValidator ID="reqPassword" runat="server" ControlToValidate="txtPassword" SetFocusOnError="true" Text="*" Display="static" ErrorMessage="Please enter a password"/><br /><br /> <asp:ValidationSummary id="valSum" runat="server" HeaderText="The following errors were found:" ShowMessageBox="true" ShowSummary="true" /><br /><br /><br /> <asp:Button ID="btnSubmit" Text="Check Validations" runat="server" /> </div> </form> </body> </html> Out Put:

Use HtmlHead control to set the page title and meta tags
<%@ Page Language="C#" AutoEventWireup="true" Codevirtual="Default.aspx.cs" Inherits="_Default" %> <%@ Register assembly="AjaxControlToolkit" namespace="AjaxControlToolkit" tagprefix="cc1" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <script runat="server"> void buttonSet_Click(object sender, EventArgs e) { Header.Title = txt_msg.Text; } </script> <html xmlns="http://www.w3.org/1999/xhtml">

<head id="Head1" runat="server"> <title>Testing HtmlHead</title> </head> <body> <div id="pageContent"> <form runat="server" id="MainForm"> Set the title <asp:textbox runat="server" id="txt_msg" /> <asp:button runat="server" id="buttonSet" text="Set" onclick="buttonSet_Click" /> </form> </div> </body> </html> OutPut:

How to specify the Session timeout in the web configuration file The following web configuration file changes the Session timeout value to 60 (1 hour). File: Web.Config <configuration> <system.web>

<sessionState timeout="60" /> </system.web> </configuration> It can be Done by Programmatically:

Session.Timeout = 60; Using Cookieless Session State File: Web.Config <configuration> <system.web> <sessionState cookieless="AutoDetect" regenerateExpiredSessionId="true" /> </system.web> </configuration>

How to call Page.Validate to validate groups


Default.aspx

<%@ Page Language="C#" AutoEventWireup="true" Codevirtual="Default.aspx.cs" Inherits="_Default" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title>Untitled Page</title> </head> <body> <form id="form1" runat="server"> <div><asp:TextBox ID="TextBox1" runat="server" ValidationGroup="Group1"> </asp:TextBox> <asp:RequiredFieldValidator ErrorMessage="*Required" ID="RequiredFieldValidator1" runat="server" ValidationGroup="Group1" ControlToValidate="TextBox1"> </asp:RequiredFieldValidator> <asp:Button ID="Button1" runat="server" Text="Validate Group1"

ValidationGroup="Group1"/> <br /> <asp:TextBox ID="TextBox2" runat="server" ValidationGroup="Group2"> </asp:TextBox> <asp:RequiredFieldValidator ErrorMessage="*Required" ID="RequiredFieldValidator2" runat="server" ValidationGroup="Group2" ControlToValidate="TextBox2"> </asp:RequiredFieldValidator> <asp:Button ID="Button2" runat="server" Text="Validate Group2" ValidationGroup="Group2"/> <br /> <br /> <asp:Button ID="cmdValidateAll" OnClick="cmdValidateAll_Click" runat="server" Text="Validate Default" /><br /> <br /> <asp:Label EnableViewState="False" ID="Label1" runat="server"> </asp:Label> </div> </form> </body> </html> Default.aspx.cs using using using using using using using using using using using System; System.Configuration; System.Data; System.Linq; System.Web; System.Web.Security; System.Web.UI; System.Web.UI.HtmlControls; System.Web.UI.WebControls; System.Web.UI.WebControls.WebParts; System.Xml.Linq;

public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } protected void cmdValidateAll_Click(object sender, EventArgs e) { Label1.Text = "Valid: " + Page.IsValid.ToString();

Page.Validate("Group1"); Label1.Text += "<br />Group1 Valid: " + Page.IsValid.ToString(); Page.Validate("Group2"); Label1.Text += "<br />Group2 Valid: " + Page.IsValid.ToString(); } }

Out Put:

How to remapping URLs in your application's web configuration file


The tilde character (~) represents the current application root. A forward slash (/) at the start of a URL represents the website root.

<configuration> <system.web> <urlMappings> <add url="~/Home.aspx" mappedUrl="~/Default.aspx"/> </urlMappings> </system.web> </configuration>

How to get the URL of Page (RawUrl)


Design Code (Default.aspx) <%@ Page Language="C#" AutoEventWireup="true" Codevirtual="Default.aspx.cs" Inherits="_Default" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title>Untitled Page</title> </head> <body> <form id="form1" runat="server"> <div> <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label> <br /> <asp:Label ID="Label2" runat="server" Text="Label"></asp:Label> </div> </form> </body> </html> Default.aspx.cs using System; using System.Configuration; using System.Data; using System.Linq; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.HtmlControls; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Xml.Linq; public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { Label1.Text = Request.Url.ToString(); Label2.Text = Request.RawUrl;//get the raw url of current request } } Out Put:

How to Know the Type and Version of Browser

using using using using using using using using using using using

System; System.Configuration; System.Data; System.Linq; System.Web; System.Web.Security; System.Web.UI; System.Web.UI.HtmlControls; System.Web.UI.WebControls; System.Web.UI.WebControls.WebParts; System.Xml.Linq;

public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { Label1.Text = "<b>Browser Type:</b> " +Request.Browser.Type.ToString();//Browser Type Label2.Text = "<b>Browser Vesion:</b> " + Request.Browser.Version.ToString();//Browser Vesion Response.Write("<b>.Net Framework Version:</b> " + Request.Browser.ClrVersion.ToString()); //Installed .net FRamework Version } }

Out Put:

How to Bind a Array List to a RadioButtonList in ASP .Net Using C#

using using using using using using using using using using using

System; System.Configuration; System.Data; System.Linq; System.Web; System.Web.Security; System.Web.UI; System.Web.UI.HtmlControls; System.Web.UI.WebControls; System.Web.UI.WebControls.WebParts; System.Xml.Linq;

public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { System.Collections.ArrayList newArrayList = new System.Collections.ArrayList(); newArrayList.Add("C"); newArrayList.Add("C++"); newArrayList.Add("Java");

newArrayList.Add("C#"); newArrayList.Add("ASp.Net"); RadioButtonList1.DataSource = newArrayList; RadioButtonList1.DataBind(); Response.Write("Successfully added " +newArrayList.Count + " different types of objects to an ArrayList."); } }

Out Put:

How to Bind a ArrayList to DropDownList in ASP.Net


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

public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (!Page.IsPostBack) { System.Collections.ArrayList myList = new System.Collections.ArrayList(); myList.Add("Zero"); myList.Add("One"); myList.Add("Two"); myList.Add("Three"); myList.Add("Four"); myList.Add("Five"); DropDownList1.DataSource = myList; DropDownList1.DataBind(); } } protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e) { Label1.Text = "You Select a "+DropDownList1.SelectedItem.Text; } } Out Put:

HTML Controls in ASP. Net


Open the Tool Box

These all are HTML Control Provided By Visual Studio 2008

Input (Reset) Control in HTML


Reset the all values in the form Events:

Property:

Design Code: <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title>Button(reset)</title> </head> <body> <form id="form1" runat="server"> <div> <input id="Reset1" type="reset" value="reset" /> </div> </form> </body> </html>

Input (Submit) Control in HTML


When a visitor clicks a submit button, the form is sent to the address specified in the action setting of the <form> tag. Events :

Property:

Design Code: <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title>Button(submit)</title> </head> <body> <form id="form1" runat="server"> <div> <input id="Submit1" type="submit" value="submit"/> </div> </form> </body> </html>

Input (Text) Control in HTML


User enter the value in this area Event:

Property:

Design Code: <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title>Input(Text)</title> </head> <body> <form id="form1" runat="server"> <div> <input id="Text1" type="text" /> </div> </form> </body> </html>

Input (File) Control in HTML


A form in an HTML document (Web page) can contain an input element with type="file". This may let the user include one or more files into the form submission.

Event:

Property:

Design Code: <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title>Input(File)</title> </head> <body> <form id="form1" runat="server"> <div> <input id="File1" type="file" /> </div> </form> </body> </html>

Input (Password) Control in HTML


Event:

Property:

Design Code:

<html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title>Input(Password)</title> </head> <body> <form id="form1" runat="server"> <div> <input id="Password1" type="password" /> </div> </form> </body> </html>

Input (Check Box) Control in HTML


Event:

Property:

Design Code: <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title>Input(Check Box)</title> </head> <body> <form id="form1" runat="server"> <div> <input id="Checkbox1" type="checkbox" /> </div> </form> </body> </html>

RadioButton Control in ASP.NET


RadioButton control is used to give single select option to the user from multiple items. When it is rendered on the page, it is implemented through <input type=radio></input> HTML tag. Its properties like BackColor, ForeColor, BorderColor, BorderStyle, BorderWidth, Height etc. are implemented through style properties of <input>.

Importent Properties: AutoPostBack CausesValidation Checked OnCheckedChanged ValidationGroup Form is automatically posted back when Radio button selection is changed. true/false. If true, Form is validated if Validation control has been used in the form. true/false. If true, Radio button is selected by default. Fires when Radio button selection changes. This works only if AutoPostBack property is set to true. Used to put a radio button under a particular validation group. It is used when you have many set of form controls and by clicking a paricular button you want to validate a particular set of controls only. It is used a group a set of radion buttons so only one of them can be selected at a time.

GroupName

Event: CheckedChanged Event: It enables you to handle the PostBack event of radiobutton control when user changes its state from selected state. When user clicks the radio button it raises the CheckedChanged event only if the AutoPostBack property of RadioButton control is set to true Example: Output:

.CS Code:

protected void Button3_Click(object sender, EventArgs e) { if (RadioButton1.Checked == true) { Label2.Text = "Your Answer is Wrong"; } if (RadioButton2.Checked == true) { Label2.Text = "Your Answer is Wrong"; } if (RadioButton3.Checked == true) { Label2.Text = "Your Answer is Right "+"<br>"+"Yow win $100"; } if (RadioButton4.Checked == true) { Label2.Text = "Your Answer is Wrong"; } }

RadioButtonlist Control in ASP.NET


RadioButtonList Control is used for selecting one predefined (available in RadioButtonList) value. That means user can be able to select only one a time. For e.g.., it is useful for selecting the User Sex , Highest Qualification etc., ASP.NET RadioButtonList itself is a class like other controls which are present under System.Web.UI.WebControls namespace. Important Properties AutoPostBack - Accept Boolean Value - If True, then page will submit to the server if the index of the Radiobutton is changed CausesValidation - Accept Boolean Value - Used to Validate the page when RadioButton click event fires. DataTextField - Accept String Value - Used to set the column Name from the DataSource which user Can see (eg., Name). DataValueField - Accept String Value - Used to set the column Name from the DataSource which user Can not see (eg., ID). Enabled - Accept Boolean Value- Used to Get/Set Radio button Enabled Height - Accept IntergerValue - Used to Set/Get height of the RadioButton RepeatColumns - Accept Interger Value - Used to set how Many RadioButtons you want to display in one line. RepeatDirection - Enumerator - "Vertical" or "Horizontal"

Width - Accept IntergerValue - Used to set the width of the RadioButton Events : DataBound - This event will fire when you call the assigned dataSource property and you write this line of code to bind your RadioButtonList myRadioButtonList.DataBind(); SelectedIndexChanged - This event will fire when user has changed his/her selection and RadioButtonList's "AutoPostBack" property is set to true; Example: Output:

.CS Code:

protected void Page_Load(object sender, EventArgs e) { if(!Page.IsPostBack) { RadioButtonList1.Items.Add("Salman Khan"); RadioButtonList1.Items.Add("Sharukh Khan"); RadioButtonList1.Items.Add("Amir Khan");

RadioButtonList1.Items.Add("Hritik"); RadioButtonList1.Items.Add(" Ajay Devgan"); RadioButtonList1.Items.Add(" Ranveer kapoor"); RadioButtonList1.Items.Add("Akshay Kumar"); RadioButtonList1.Items.Add("Sahid kapoor"); RadioButtonList1.Items.Add("Sanjay Dutt"); } } protected void Button1_Click(object sender, EventArgs e) { Label1.Text ="Your Favrouite Actor::> "+ RadioButtonList1.SelectedItem.Text; }

Image Control in ASP.NET


ASP.Net 2.0 Image control provides the functionality to display images on ASP.Net web page. The image server control renders using HTML img tag in the web browser. As a web server control it can be accessed at server side that enables you to set the images dynamically using C# code or by specifying the image URL retrieved from SQL database table. It provides properties similar to HTML img tag that allow you to set the path of image file that you want to display on web page along with its alignment and alternate text properties that render as attributes of HTML img tag in the web browser. You can get or set these properties at design time as well as using C# code programmatically. The ASP.Net image control allows you to display the images only for design purposes or as a part of the page content but does not support any server events to execute the server side code if a user clicks on it or moves the mouse over it. Properties:

1. AlternateText: You can specify the text value for this property that appears as
tooltip for the displayed image in the web browsers. All web browsers do not support this property to display the text as tooltip. The web browsers display this alternate text value if the specified image does not load for any reason like unreachable or unavailable at that time. This property renders as alt attribute of img tag. DescriptionUrl: You can specify the URL of the web page containing the full description regarding the image. GenerateEmptyAlternateText: It is a Boolean type property that allows or disallows to generate the empty alt attribute while rendering the image control. ImageAlign : It enables you to specify the alignment of image as a part of inline content or web page elements. ImageUrl :You can specify the URL of the image that you want to display on the web page. ToolTip: It enables you to specify the tooltip text for the image control. The tooltip property generates the title attribute of img tag that appears as tooltip in some browsers.

2. 3. 4. 5. 6.

Apart from these properties there some other CSS based properties that enable you to set the border, background color, height and width of the image. The CSS based properties

include: BackColor, BorderColor, BorderStyle, BorderWidth, CssClass, Height and Width that allow you to customize the appearance of image. Syntax: <asp:Image ID="Image1" runat="server" Height="215px" ImageUrl="~/Images/Sunset.jpg" /> Example:

Design:

ImageMap Control in ASP.NET


ImageMap control is used to create an image that contains clickable hotspot region. When user click on the region, the user is either sent to a URL or a sub program is called Imagemap. When it is rendered on the page, it is implemented through <img /> HTML tag. Hot spots features: o o o o o There is no limit on number of hotspots each image may contain. Each hotspot is characterized by various attributes like shape, location and size. Overlapping hotspots are perfectly valid. Hot spots are defined using x and y coordinates. Hot spots can be assigned Image URL's and are capable of postback.

Different types of hot spots: There are three different types of hot spots offered by ImageMap control. They are: o o o CircleHotspot RectangleHotspot PolygonHotspot

CircleHotspot: CircleHotspot defines circle shaped hot spot region in an ImageMap control. To define the region for a circle hot spot, we should define X and Y coordinates for circle as well as radius property which usually is the distance from the center of circle to the edge. RectangleHotspot: RectangleHotspot defines rectangle shaped hot spot region in an ImageMap control. To define the region for a Rectangle hot spot, we define Top, Bottom, Left and Right coordinates. Similar is the case for the Polygon hot spot. Rightclick On Imagemap Control :

Example:

if you click the left side of the image you see below image

. if you click the Right side of the image you see below image

Calendar control In ASP.net


This control displays a one-month calendar that allows the user to select dates and move to the next and previous months. Properties: Property DayHeaderStyle Description The style for displaying the names of the days

The format for displaying the names of the days. Can take one of the following values: DayNameFormat FirstLetter FirstTwoLetters Full

Short SelectMonthText The text displayed for the month selection link SelectWeekText The text displayed for the week selection link The format for the title of the calendar. Can take one of the following values: TitleFormat Month

MonthYear TodaysDate Today's date VisibleDate The date that specifies the month that is currently visible in the calendar WeekendDayStyle The style for weekends

Here I show how we can use Calendar control in asp.net. Create a web form name Calendar.aspx, and then add a Calendar control and TextBox control. Here we use OnSelectionChanged event in calendar control. When someone selects a date from Calendar, the TextBox control shows the selected date. .ASPX Code:

<asp:TextBox ID="TextBox1" runat="server" Height="32px" Width="234px"></asp:TextBox> asp:Calendar ID="Calendar1" runat="server" BorderColor="#FFCC99" > "BorderStyle="Dashed "onselectionchanged="Calendar1_SelectionChanged SelectedDate="2010-11-01" ToolTip="Please </ "Select Date"> <TitleStyle BackColor="#FFFFCC <asp:Calendar />

.CS Code:

protected void Calendar1_SelectionChanged(object sender, EventArgs e) { TextBox1.Text = Calendar1.SelectedDate.ToLongDateString();//To display date in TextBox }

Output:

FileUpload Control in ASP.net


Finally ASP.NET 2.0 has a FileUpLoad control, which allows developers to drop the control on a page and let it browse a file and upload it on the server. To create a control, simply drop the FileUpload control from Toolbox to a Web page. .ASPX CODE

<asp:FileUpload ID="FileUpload1" runat="server" /> <asp:Label ID="Label1" runat="server" BackColor="White" Text="Label"></asp:Label> <asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Submit" />

.CS CODE

protected void Button1_Click(object sender, EventArgs e) {

if (FileUpload1.HasFile) { FileUpload1.SaveAs(@"D:\temp\" +FileUpload1.FileName); Label1.Text = "File Uploaded: " + FileUpload1.FileName +" "+System.DateTime.Now.ToLongDateString(); } else { Label1.Text = "No File Uploaded."; }

OUTPUT:

After Click on Submit Button file Saved in Folder Temp

Input (Hidden) Control in HTML


Event:

Property:

Design Code: <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title>Input(Hidden)</title> </head> <body> <form id="form1" runat="server"> <div> <input id="Hidden1" type="hidden" /> </div> </form> </body> </html>

Textarea Control in HTML


Using this control enter the value as user requirement Event:

Property:

Design Code: <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title>Textarea</title> </head> <body> <form id="form1" runat="server"> <div> <textarea id="TextArea1" cols="20" rows="2"></textarea> </div> </form> </body> </html>

Table Control in HTML


Property:

Using Style you can change your table View

Design Code: <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title>Table</title> </head> <body> <form id="form1" runat="server"> <div> <table style="width: 100%;"> <tr><td>&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> </tr> <tr> <td>&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> </tr> <tr><td>&nbsp;</td> <td>&nbsp;</td>

<td>&nbsp;</td> </tr> </table> </div> </form> </body> </html>

Select Control in hTML


Event:

Property:

Design Code: <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title>Select</title> </head> <body> <form id="form1" runat="server"> <div> <select id="Select1"> <option>1</option> <option>2</option> <option>3</option> </select> </div> </form> </body> </html> Out Put:

Image Control in HTML


Event:

Property:

Design Code: <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title>Image</title> </head> <body> <form id="form1" runat="server"> <div> <img alt="" src=""/> </div> </form> </body> </html>

ASP.NET Interview Questions And Answers

Page 1
Ques: 1 How to Configure SMTP in asp .NET?

Ans: This example specifies SMTP parameters to send e-mail using a remote SMTP server and user that are importent. This program shows configuration process<system.net> <mailSettings> <smtp deliveryMethod="Network|PickupDirectoryFromIis|SpecifiedPickupDirec> <network defaultCredentials="true|false" from="r4r@fco.in" host="smtphost" port="26" password="password" userName="user"/> <specifiedPickupDirectory pickupDirectoryLocation="c:\pickupDirectory"/> </smtp> </mailSettings> </system.net> Ques: 2 Print Hello World message using SharePoint in Asp.Net 2.0? Ans: using System; using System.Collections.Generic; using System.Text; using System.Web.UI.HtmlControls; using System.Web.UI.WebControls; using Microsoft.SharePoint.WebPartPages; namespace LoisAndClark.WPLibrary { public class MYWP : WebPart { protected override void CreateChildControls() { Content obj = new Content(); string str1 = obj.MyContent<string>("Hello World!"); this.Controls.Add(new System.Web.UI.LiteralControl(str1)); } } } generic method shows that SharePoint site is running on .NET Framework 2.0, and the code of the generic method seems like this: public string MyContent<MyType>(MyType arg) { return arg.ToString(); } Ques: 3 How to create a SharePoint web part using File upload control.give example? Ans: using System; using System.Collections.Generic; using System.Text; using System.Web.UI.HtmlControls; using System.Web.UI.WebControls;

using Microsoft.SharePoint.WebPartPages; namespace LoisAndClark.WPLibrary { public class MYWP : WebPart { FileUpload objFileUpload = new FileUpload(); protected override void CreateChildControls() { this.Controls.Add(new System.Web.UI.LiteralControl ("Select a file to upload:")); this.Controls.Add(objFileUpload); Button btnUpload = new Button(); btnUpload.Text = "Save File"; this.Load += new System.EventHandler(btnUpload_Click); this.Controls.Add(btnUpload); } private void btnUpload_Click(object sender, EventArgs e) { string strSavePath = @"C:\temp\"; if (objFileUpload.HasFile) { string strFileName = objFileUpload.FileName; strSavePath += strFileName; objFileUpload.SaveAs(strSavePath); } else { //otherwise let the message show file was not uploaded. } } } } Ques: 4 What is BulletedList Control in Share Point. Give an example? Ans: Bullet style allow u choose the style of the element that precedes the item.here u can choose numbers, squares, or circles.here child items can be rendered as plain text, hyperlinks, or buttons. This example uses a custom image that requires to be placed in a virtual directory on the server. using System; using System.Collections.Generic; using System.Text; using System.Web.UI.HtmlControls; using System.Web.UI.WebControls; using Microsoft.SharePoint.WebPartPages; namespace LoisAndClark.WPLibrary { public class MyWP : WebPart { protected override void CreateChildControls { BulletedList objBullist = new BulletedList(); objBullist.BulletStyle = BulletStyle.CustomImage; objBullist.BulletImageUrl = @"/_layouts/images/rajesh.gif";

objBullist.Items.Add("First"); objBullist.Items.Add("Seciond"); objBullist.Items.Add("Third"); objBullist.Items.Add("Fourth"); this.Controls.Add(objBullist); } } } Ques: 5 DescribeWizard server control with example in Share Point? Ans: This control enables you to build a sequence of steps that are displayed to the end users side. It is alos used either display or gather information in small steps in system. using System; using System.Collections.Generic; using System.Text; using System.Web.UI.HtmlControls; using System.Web.UI.WebControls; using Microsoft.SharePoint.WebPartPages; namespace LoisAndClark.WPLibrary { public class MyWP : WebPart { protected override void CreateChildControls() { Wizard objWizard = new Wizard(); objWizard.HeaderText = "Wizard Header"; for (int i = 1; i <= 6; i++) { WizardStepBase objStep = new WizardStep(); objStep.ID = "Step" + i; objStep.Title = "Step " + i; TextBox objText = new TextBox(); objText.ID = "Text" + i; objText.Text = "Value for step " + i; objStep.Controls.Add(objText); objWizard.WizardSteps.Add(objStep); } this.Controls.Add(objWizard); } } } Ques: 6 Define Life Cycle of Page in ASP.NET? Ans: protected void Page_PreLoad(object sender, EventArgs e) { Response.Write("<br>"+"Page Pre Load"); } protected void Page_Load(object sender, EventArgs e) { Response.Write("<br>" + "Page Load");

} protected void Page_LoadComplete(object sender, EventArgs e) { Response.Write("<br>" + "Page Complete"); } protected void Page_PreRender(object sender, EventArgs e) { Response.Write("<br>" + "Page Pre Render"); } protected void Page_Render(object sender, EventArgs e) { Response.Write("<br>" + "Pre Render"); } protected void Page_PreInit(object sender, EventArgs e) { Response.Write("<br>" + "Page Pre Init"); } protected void Page_Init(object sender, EventArgs e) { Response.Write("<br>" + "Page Init"); } protected void Page_InitComplete(object sender, EventArgs e) { Response.Write("<br>" + "Page Pre Init Complete"); } Ques: 7 Write a program in ASP.NET to Show Data With Access? Ans: Page_Load():OleDbConnection x; OleDbCommand y; OleDbDataReader z; protected void Page_Load(object sender, EventArgs e) { x = new OleDbConnection("provider=microsoft.jet.oledb.4.0;data source=c:\\db1.mdb"); x.Open(); y = new OleDbCommand("select * from emp", x); z = y.ExecuteReader(); while (z.Read()) { Response.Write(z["ename"]); Response.Write("<hr>"); } z.Close(); y.Dispose(); x.Close(); } Ques: 8 Write a program to show connection with Oracle in ASP.NET? Ans: OleDbConnection x; OleDbCommand y; OleDbDataReader z; protected void Page_Load(object sender, EventArgs e) {

x = new OleDbConnection("provider=msdaora;user id=scott;password=tiger"); x.Open(); y = new OleDbCommand("select * from emp", x); z = y.ExecuteReader(); while (z.Read()) { Response.Write("<li>"); Response.Write(z["ename"]); } z.Close(); y.Dispose(); x.Close(); } Ques: 9 Write a program to show connection to Excel in ASP.NET? Ans: OleDbConnection x; OleDbCommand y; OleDbDataReader z; protected void Page_Load(object sender, EventArgs e) { x = new OleDbConnection("provider=microsoft.jet.oledb.4.0;data source=c:\\book1.xls;Extended Properties=excel 8.0"); x.Open(); y = new OleDbCommand("select * from [sheet1$]", x); z = y.ExecuteReader(); while (z.Read()) { Response.Write("<li>"); Response.Write(z["ename"]); } z.Close(); y.Dispose(); x.Close(); } Ques: 10 How to add Record in ASP.NET? Ans: OleDbConnection x; OleDbCommand y; protected void Button1_Click(object sender, EventArgs e) { x = new OleDbConnection("provider=microsoft.jet.oledb.4.0;data source=c:\\db1.mdb"); x.Open(); y = new OleDbCommand("Insert into emp(empno,ename,sal) values(@p,@q,@r)", x); y.Parameters.Add("@p", TextBox1.Text); y.Parameters.Add("@q", TextBox2.Text); y.Parameters.Add("@r", TextBox3.Text); y.ExecuteNonQuery(); Label1.Visible = true; Label1.Text="Record Addedd"; y.Dispose(); x.Close(); }

Ans: OleDbConnection x; OleDbCommand y; protected void Button1_Click(object sender, EventArgs e) { x = new OleDbConnection("provider=microsoft.jet.oledb.4.0;data source=c:\\db1.mdb"); x.Open(); y = new OleDbCommand("Insert into emp(empno,ename,sal) values(@p,@q,@r)", x); y.Parameters.Add("@p", TextBox1.Text); y.Parameters.Add("@q", TextBox2.Text); y.Parameters.Add("@r", TextBox3.Text); y.ExecuteNonQuery(); Label1.Visible = true; Label1.Text="Record Addedd"; y.Dispose(); x.Close(); } Ques: 11 Write a program to Delete Record in ASP.NET ? Ans: OleDbConnection x; OleDbCommand y; protected void Button1_Click(object sender, EventArgs e) { x = new OleDbConnection("provider=microsoft.jet.oledb.4.0;data source=c:\\db1.mdb"); x.Open(); y = new OleDbCommand("delete from emp where empno=@p",x); y.Parameters.Add("@p", TextBox1.Text); y.ExecuteNonQuery(); Label1.Visible = true; Label1.Text="Record Deleted"; y.Dispose(); x.Close(); } Ques: 12 Write a program to show data in Gridview in ASP.NET? Ans: OleDbConnection x; OleDbDataAdapter y; DataSet z; protected void Button2_Click(object sender, EventArgs e) { x = new OleDbConnection("provider=msdaora;user id=scott;password=tiger"); x.Open(); y = new OleDbDataAdapter("select * from emp", x); z = new DataSet(); y.Fill(z, "emp"); GridView1.DataSource = z.Tables["emp"]; GridView1.DataBind();

y.Dispose(); x.Close(); } Ques: 13 Write a Program to Connect with dropdownlist in ASP.NET Ans: OleDbConnection x; OleDbDataAdapter y; DataSet z; protected void Button1_Click(object sender, EventArgs e) { x = new OleDbConnection("Provider=msdaora;user id=scott;password=tiger"); x.Open(); y=new OleDbDataAdapter("select * from emp",x); z = new DataSet(); y.Fill(z, "emp"); DropDownList1.DataSource = z; DropDownList1.DataTextField = "ename"; DropDownList1.DataBind(); x.Close(); } Ques: 14 How Repeater is used in ASP.NET? Ans: <asp:Repeater ID="Repeater1" runat="server"> <ItemTemplate> <%#DataBinder.Eval(Container.DataItem, <%#DataBinder.Eval(Container.DataItem, <%#DataBinder.Eval(Container.DataItem, </ItemTemplate> </asp:Repeater> //the whole structure looks like this <asp:Repeater ID="Repeater1" runat="server"> <HeaderTemplate> Employee Detailed </HeaderTemplate> <ItemTemplate> <font color=gray> <%#DataBinder.Eval(Container.DataItem, <%#DataBinder.Eval(Container.DataItem, <%#DataBinder.Eval(Container.DataItem, </font> </ItemTemplate> <AlternatingItemTemplate> <font color=green> <%#DataBinder.Eval(Container.DataItem, <%#DataBinder.Eval(Container.DataItem, <%#DataBinder.Eval(Container.DataItem, </font> </AlternatingItemTemplate> <FooterTemplate> Thanks </FooterTemplate> <SeparatorTemplate> <hr/>

"Empno") %> "Ename") %> "Sal") %>

"Empno") %> "Ename") %> "Sal") %>

"Empno") %> "Ename") %> "Sal") %>

</SeparatorTemplate> </asp:Repeater> Ques: 15 How to show data in HTML table using Repeater? Ans: <asp:Repeater ID="Repeater1" runat="server"> <HeaderTemplate> <table border="10" width="100%" bgcolor=green style="width:100%" > <tr> <th>Empno</th> <th>Ename</th> <th>Sal</th> </tr> </HeaderTemplate> <ItemTemplate> <tr> <td> <%#DataBinder.Eval(Container.DataItem, "Empno") %> </td> <td> <%#DataBinder.Eval(Container.DataItem, "Ename") %> </td> <td> <%#DataBinder.Eval(Container.DataItem, "Sal") %> </td> </tr> </font> </ItemTemplate> <FooterTemplate> </table> </FooterTemplate> </asp:Repeater> </td> <td style="width: 100px; height: 226px"> </td> </tr> </table> Ans: dfd Ques: 16 Write a program to show the Use of dataList in ASP.NET? Ans: <asp:DataList ID="DataList1" runat="server" BackColor="White" BorderColor="#336666" BorderStyle="Double" BorderWidth="3px" CellPadding="4" GridLines="Both"> <HeaderTemplate>Employee Detailed</HeaderTemplate> <ItemTemplate> <%#DataBinder.Eval(Container.DataItem, "Empno") %> <%#DataBinder.Eval(Container.DataItem, "Ename") %> <%#DataBinder.Eval(Container.DataItem, "Sal") %> </ItemTemplate> Ques: 17 How to make User Control in ASP.net? Ans: a)Add User Controll write code:<hr color=red/> <center><H1><SPAN

style="COLOR: #ff9999; TEXT-DECORATION: underline">BigBanyanTree.com</SPAN></H1></center> <hr Color=Green/> b)In .aspx page:<%@ Register TagPrefix=a TagName="MyUserCtl" Src="~/WebUserControl.ascx"%>

c)Now use this :<a:MyUserCtl ID="tata" runat=server/>

Ques: 18 How to create voting poll system in asp.net which allows user to see the results? Ques: 19 What is Benefits of ASP.NET? Ans: >>Simplified development: ASP.NET offers a very rich object model that developers can use to reduce the amount of code they need to write. >>Web services: Create Web services that can be consumed by any client that understands HTTP and XML, the de facto language for inter-device communication. >>Performance: When ASP.NET page is first requested, it is compiled and cached, or saved in memory, by the .NET Common Language Runtime (CLR). This cached copy can then be re-used for each subsequent request for the page. Performance is thereby improved because after the first request, the code can run from a much faster compiled version. >>Language independence >>Simplified deployment >>Cross-client capability Ques: 20 What is ASP.Net? Ans: ASP Stands for Active server Pages.ASP used to create interacting web pages.

ASP.NET Interview Questions And Answers

Page 1
Ques: 1 What does the keyword virtual declare for a method? Ans: The method or property can be overridden.

Ques: 2 Tell me implicit name of the parameter that gets passed into the set property of a class? Ans: The data type of the value parameter is defined by whatever data type the property is declared as. Ques: 3 What is the difference between an interface and abstract class ? Ans: 1. In an interface class, all methods are abstract and there is no implementation. In an abstract class some methods can be concrete. 2. In an interface class, no accessibility modifiers are allowed. An abstract class may have accessibility modifiers. Ques: 4 How to Specify the accessibility modifier for methods inside the interface? Ans: They all must be public, and are therefore public by default. Ques: 5 Define interface class ? Ans: Interfaces, like classes, define a set of properties, methods, and events. But unlike classes, interfaces do not provide implementation. They are implemented by classes, and defined as separate entities from classes. Ques: 6 When you declared a class as abstract? Ans: 1. When at least one of the methods in the class is abstract. 2. When the class itself is inherited from an abstract class, but not all base abstract methods have been overridden. Ques: 7 Define abstract class? Ans: 1. A class that cannot be instantiated. 2. An abstract class is a class that must be inherited and have the methods overridden. 3. An abstract class is essentially a blueprint for a class without any implementation Ques: 8 How to allowed a class to be inherited, but it must be prevent the method from being over-ridden? Ans: Just leave the class public and make the method sealed. Ques: 9 How to prevent your class from being inherited by another class? Ans: We use the sealed keyword to prevent the class from being inherited. Ques: 10 What class is underneath the SortedList class? Ans: A sorted HashTable. Ques: 11 What is the .NET collection class that allows an element to be accessed using a unique key? Ans: HashTable. Ques: 12 Difference between the System.Array.Clone() and System.Array.CopyTo()? Ans: The Clone() method returns a new array (a shallow copy) object containing all the elements in the original array. The CopyTo() method copies the elements into another existing array. Both perform a shallow copy. A shallow copy means the contents (each array element) contains references to the same

object as the elements in the original array. A deep copy (which neither of these methods performs) would create a new instance of each element's object, resulting in a different, yet identacle object. Ques: 13 Difference between System.String and System.Text.StringBuilder classes? Ans: System.String is immutable. System.StringBuilder was designed with the purpose of having a mutable string where a variety of operations can be performed. Ques: 14 What is the top .NET class that everything is derived from? Ans: System.Object. Ques: 15 How can you automatically generate interface for the remotable object in .NET? Ans: Use the Soapsuds tool. Ques: 16 How to configure a .NET Remoting object via XML file? Ans: It can be done via machine.config and application level .config file (or web.config in ASP.NET). Application-level XML settings take precedence over machine.config. Ques: 17 What is Singleton activation mode? Ans: A single object is instantiated regardless of the number of clients accessing it. Lifetime of this object is determined by lifetime lease. Ques: 18 What security measures exist for .NET Remoting? Ans: None. Ques: 19 In .NET Remoting, What are channels? Ans: Channels represent the objects that transfer the other serialized objects from one application domain to another and from one computer to another, as well as one process to another on the same box. A channel must exist before an object can be transferred. Ques: 20 What are remotable objects in .NET Remoting? Ans: 1. They can be marshaled across the application domains. 2. You can marshal by value, where a deep copy of the object is created and then passed to the receiver. You can also marshal by reference, where just a reference to an existing object is passed.

ASP.NET Interview Questions And Answers

Page 1
Questions Tot Show al Post Your Answers Pos Answers ts Show Answers 44 Post Your Answers Last Post

Which of the following are correct controls in ASP.NET Source View?()

Jairaj Singh

1.<asp:textbox runat="server" id="Msg" text="Hello, R4R" /> 2.<asp:button runat="server" id="Send" text="Send" onclick="Send_Click" /> 3. None 4. Both Which is used to add event code(on C# Code) for TextBox control in Source view ( ASP.NET)

1. MsgSent.Text = Msg.Text; 2. MsgSent.Text = Msg.Text 3. Both 4. None Which is used for code-in-line model? 1.< script runat="server"> Show 2.< script javascript="server"> Answers 3.Both 4.None Which is code allows the modification of the head tag at runtime? Show 1 < head runat="server"> Answers 2.< script javascript="server"> 3.Both 4.None How you can change the page title by changing the using C# 1.void buttonSet_Click(Object sender, EventArgs earg) { Header.Title :Msg.Text; } 2.void buttonSet_Click(Object sender, EventArgs earg) Show { Answers Msg.Text= Header.Title; } 3.void buttonSet_Click(Object sender, EventArgs earg) { Msg.Text: Header.Title; } 4.None Which is not used into @Page attributes 1. Async ,CodeFile 2. EnableTheming, MasterPageFile

Show Answers

Post Your Answers

Monu Sharma

Post Your Answers

Monu Sharma

Post Your Answers

13.03.10 Heena

Post Your Answers

19.06.10 azath

Show Answers

Post Your Answers

14.03.10 ravi

3. MaintainScrollPositionOnPostback Theme 4. None 5. All Which is true to bind a method by setting the Master attribute in the <pages>? 1. < configuration> < system.web> < pages masterpagefile="r4r.co.in.MasterPage" /> Show </system.web> Answers </configuration> 2. < pages> < system.web> < pages masterpagefile="r4r.co.in.MasterPage" /> </system.web> </ pages> 3.Both 4.None @Page directive <%@ MasterType VirtualPath="~/MasterPage.master" %> The above syntax is used to make the Answers Master property typed to the class that is stored in the referenced master on ASP page. 1.Yes 2.No ASP.NET Supports Nested Master Page Show 1.Yes Answers 2.No Which is true ? 1. Page Class is a derivative of the Control class. Show 2. Page Class inherits all Answers properties, methods, and events exposed by the Control class. 3.Both 4. None Which of the following properties are not expose by Page Class? 1.Cache, IsPostBack 2 ErrorPage3,IsValid, Trace, and Validators 3.Both 4.None

Post Your Answers

13.03.10 Hima

Show

Post Your Answers

04.07.10 jagadeesh

Post Your Answers

bsundaramoorthy

Post Your Answers

13.03.10 Shuja

Show Answers

Post Your Answers

13.03.10 Vikas

Choose all true options only 1. HtmlImage is HTMLControl for image and it used for html tag <img> 2. HtmlInputHidden Used for hidden Show just like form fields <input Answers type="hidden"> 3. HtmlInputImage is HTMLControl for Image and it used for html input tag <input type="image"> 4.None Correct syntax of ASP.NET directive: 1.<%@ directive [attribute=value] %>.

Post Your Answers

manoj

Show

2.<% directive [attribute=value] %>. Answers 3.<@ directive [attribute=value] %>. 4.<@ directive [attribute=value] >. The namespaces that are automatically imported into all ASP.NET pages 1.System,System.Collections, System.IO 2.System.Web,System. Web.UI Show 3.System.Web.UI.HtmlControls,System. Answers Web.UI.WebControls A . 1 B. 1,2,3 C, 2,3 D. None The ASP.NET pages directives are 1. @ Page,@ Control,@ Import,@ Register 2. @ Assembly, @ OutputCache Show 3. System.Web.UI.HtmlControls,System. Answers Web.UI.WebControls A . 1,2 B. 1,2,3 C, 2,3 D. None Syntax for Code Declaration Blocks 1. < script runat="server" [language="language"]> //code. </script> 2. <asp runat="server" [language="language"]> //code.

Post Your Answers

13.03.10 Neha

Post Your Answers

20.09.10 Ashwini.S.Acharya

Post Your Answers

25.09.10 amit

Show Answers

Post Your Answers

sushilkumar

</asp> 3. 1 and 2 4. None Syntax for Assembly directive specifies 1. < Assembly runat="server" [language="language"]> //code. </ Assembly > 2. <%@ Assembly Name="r4r" %> 3. 1 and 2 4. None Syntax for Register directive specifies 1. < Register runat="server" [language="language"]> //code. </ Register > 2. <%@ Register Tagprefix="r4r" TagName="CustomControl Src="CustomControl.ascx" %> 3. 1 and 2 4. None Syntax for Import directive specifies 1. <%@ Import Namespace="System.Data.OlDb" %> 2. <%@ Import Namespace="System.Data" Answers %>

Show Answers

Post Your Answers

13.03.10 Renu

Show Answers

Post Your Answers

13.03.10 Vivak

Show

Post Your Answers

12.02.11 Shiela

3. 1 and 2 4. None Syntax for Custom-Control to insert a Show custom control into a page

Answers

Post Your Answers

Ravindra M Kanje

1. <tagprefix:tagname id="controlID" runat="server" eventname="eventHandler" /> 2. <%@ Import Namespace="System.Data" %> 3. 1 and 2 4. None

ASP.NET Basic Subjective Question and Answers


Q1:Describe the role of inetinfo.exe, aspnet_isapi.dll andaspnet_wp.exe in the page loading process. Ans: inetinfo.exe is theMicrosoft IIS server running, handling ASP.NET requests among other things.When an ASP.NET request is received (usually a file with .aspx extension), the ISAPI filter aspnet_isapi.dll takes care of it by passing the request tothe actual worker process aspnet_wp.exe. Q2: Whats the difference between Response.Write() andResponse.Output.Write()? Ans: Response.Output.Write() allows you to write formatted output. Q3: What methods are fired during the page load? Ans: Init() - when the page is instantiated Load() - when the page is loaded into server memory PreRender() - the brief moment before the page is displayed to the user as HTML Unload() - when page finishes loading. Q4: When during the page processing cycle is ViewState available? Ans: After the Init() and before the Page_Load(), or OnLoad() for a control. Q5: What namespace does the Web page belong in the .NET Framework class hierarchy? Ans: System.Web.UI.Page Q6: Where do you store the information about the users locale? Ans: System.Web.UI.Page.Culture Q7: Whats the difference between Codebehind="MyCode.aspx.cs" andSrc="MyCode. aspx.cs"? Ans: CodeBehind is relevant to Visual Studio.NET only. Q8: Whats a bubbled event? Ans: When you have a complex control, like DataGrid, writing an event processing routine for each object (cell, button, row, etc.) is quite tedious. The controls can bubble up their eventhandlers, allowing the main DataGrid event handler to take care of its constituents.

Q9: Suppose you want a certain ASP.NET function executed on MouseOver for a certain button. Where do you add an event handler? Ans: Add an OnMouseOver attribute to the button. Example: btnSubmit.Attributes.Add("onmouseover", "someClientCodeHere();"); Q10: What data types do the RangeValidator control support? Ans: Integer, String, and Date. Q11: Explain the differences between Server-side and Client-side code? Ans: Server-side code executes on the server. Client-side code executes in the client's browser. Q13: What type of code (server or client) is found in a Code-Behind class? Ans: The answer is server-side code since code-behind is executed on the server. However, during the code-behind's execution on the server, it can render client-side code such as JavaScript to be processed in the clients browser. But just to be clear, code-behind executes on the server, thus making it server-side code. Q14: Should user input data validation occur server-side or client-side? Why? Ans: All user input data validation should occur on the server at a minimum. Additionally, client-side validation can be performed where deemed appropriate and feasable to provide a richer, more responsive experience for the user. Q16: What is the difference between Server.Transfer and Response.Redirect? Why would I choose one over the other? Ans: Server.Transfer transfers page processing from one page directly to the next page without making a round-trip back to the client's browser. This provides a faster response with a little less overhead on the server. Server.Transfer does not update the clients url history list or current url. Response.Redirect is used to redirect the user's browser to another page or site. This performas a trip back to the client where the client's browser is redirected to the new page. The user's browser history list is updated to reflect the new address. Q18: Can you explain the difference between an ADO.NET Dataset and an ADO Recordset? Ans: Valid answers are: A DataSet can represent an entire relational database in memory, complete with tables, relations, and views. A DataSet is designed to work without any continuing connection to the original data source. Data in a DataSet is bulk-loaded, rather than being loaded on demand. There's no concept of cursor types in a DataSet. DataSets have no current record pointer You can use For Each loops to move through the data. You can store many edits in a DataSet, and write them to the original data source in a single operation. Though the DataSet is universal, other objects in ADO.NET come in different versions for different data sources. Q19: What is the Global.asax used for? Ans: The Global.asax (including the Global.asax.cs file) is used to implement application and session level events.

Q20: What are the Application_Start and Session_Start subroutines used for? Ans: This is where you can set the specific variables for the Application and Session objects. Q21: Can you explain what inheritance is and an example of when you might use it? Ans: When you want to inherit (use the functionality of) another class. Example: With a base class named Employee, a Manager class could be derived from the Employee base class. Q22: Whats an assembly and Explain what a diffgram is, and a good use for one? Ans: Assemblies are the building blocks of the .NET framework. Overview of assemblies from MSDN Describe the difference between inline and code behind. Inline code written along side the html in a page. Code-behind is code written in a separate file and referenced by the .aspx page. The DiffGram is one of the two XML formats that you can use to render DataSet object contents to XML. A good use is reading database data to an XML file to be sent to a Web Service. Q23: Whats MSIL, and why should my developers need an appreciation of it if at all? Ans: MSIL is the Microsoft Intermediate Language. All .NET compatible languages will get converted to MSIL. MSIL also allows the .NET Framework to JIT compile the assembly on the installed computer. Q24: Which method do you invoke on the DataAdapter control to load your generated dataset with data? Ans: The Fill() method. Q25: Which template must you provide, in order to display data in a Repeater control? Ans: ItemTemplate. Q26: How can you provide an alternating color scheme in a Repeater control? Ans: Use the AlternatingItemTemplate. Q27: What property must you set, and what method must you call in your code, in order to bind the data from a data source to the Repeater control? Ans: You must set the DataSource property and call the DataBind method. Q28: What base class do all Web Forms inherit from? Ans: The Page class. Name two properties common in every validation control? ControlToValidate property and Text property. Q29: Which property on a Combo Box do you set with a column name, prior to setting the DataSource, to display data in the combo box? Ans: DataTextField property. Q30: Which control would you use if you needed to make sure the values in two different controls matched? Ans: CompareValidator control. Q31: How many classes can a single .NET DLL contain? Ans: It can contain many classes.

Web Service Questions Q32: What is the transport protocol you use to call a Web service? Ans: SOAP (Simple Object Access Protocol) is the preferred protocol. Q33: A Web service can only be written in .NET True or False? Ans: False Q34: What does WSDL stand for? Ans: Web Services Description Language. Q35:To test a Web service you must create a Windows application or Web application to consume this service. True or False? Ans: False, the web service comes with a test page and it provides HTTP-GET method to test. State Management Questions: Q36: What is ViewState? Ans: ViewState allows the state of objects (serializable) to be stored in a hidden field on the page. ViewState is transported to the client and back to the server, and is not stored on the server or any other external source. ViewState is used the retain the state of server-side objects between postabacks. Q37: What is the lifespan for items stored in ViewState? Ans: Item stored in ViewState exist for the life of the current page. This includes postbacks (to the same page). Q38: What does the "EnableViewState" property do? Why would I want it on or off? Ans: It allows the page to save the users input on a form across postbacks. It saves the server-side values for a given control into ViewState, which is stored as a hidden value on the page before sending the page to the clients browser. When the page is posted back to the server the server control is recreated with the state stored in viewstate. Q39: What are the different types of Session state management options available with ASP.NET? Ans: ASP.NET provides In-Process and Out-of-Process state management. In-Process stores the session in memory on the web server. This requires the a "sticky-server" (or no loadbalancing) so that the user is always reconnected to the same web server. Out-of-Process Session state management stores data in an external data source. The external data source may be either a SQL Server or a State Server service. Out-of-Process state management requires that all objects stored in session are serializable.

You might also like