Basic Tutorials With Examples
Basic Tutorials With Examples
1. Introduction of ASP.NET
2. Architecture of ASP.NET
3. Life Cycle of Web pages And Types Of Control in Asp.net
4. Various Type of Application in Asp.net and Partial Class
5. State Management in Asp.net And how to Implement Viewstate
6. Cookies in Asp.net
7. How to Implement Query String in Asp.net
8. Server Side State Management
9. Master Page In Asp.net
10. Introduction Of Gridview Control
11. Simple Databind In Gridview Control
12. Simple Code For Edit Update And Delete In Gridview
13. All Gridview Code In Asp.net
14. Validation Control in Asp.net
15. RequiredFieldvalidator in Asp.net
16. RegularExpressionValidator control in Asp.net
17. CustomValidator control in Asp.net
18. Summary Validation Control in Asp.net
19. Label Control
20. TextBox Control
21. Button Control
22. ImageButton Control
23. hyperlink
24. literal
25. LinkButton Control
26. DropDownList Control
27. How to Bind Data in DropDownList Control
28. Listbox Control
29. Checkbox Control
30. CheckBoxList Control
31. RadioButton Control
32. RadioButtonList Control
33. Image Control
34. ImageMap Control
35. Calender Control
36. FileUpload Control
37. Wizard Control
38. DataList Control
39. DetailView Control
40. FormView Control
41. ListView Control
42. Repeater Control
43. Pager Control
44. Navigation Control
45. Login Control
46. How To Make UserControl in ASP.NET
47. How to Encypt Data and Decrypt Data In ASP.NET
48. Create Connection To Excel Data
49. Add Flash file in Website in ASP.NET
50. How to rotate image in asp.net
51. How to download any file in asp.net
52. How To get the values of selected
53. How to insert picture in excel
54. How to make setup of web application
55. How to save image in database
56. How to send email using asp.net
57. Machine confiq in asp.net
58. Reflection in asp.net
59. Save File In project Folder
60. Searching document from website in ASP.NET
61. Selected country from drop down list
62. Skin style and theme in asp.net
63. Socket programming in asp
64. Tracing in asp
65. Upload Multiple Images On WEB Page
66. What is virtual directory
67. How to Add Manually CheckBox in C# using Asp.net
68. How to Add StyleSheet in TextBox using ASP.NET
69. How to Create Multi Language Web-Site in ASP.NET
70. How to show Alert and Confirmation Message Box in ASP.NET
71. How to write Gridview data to XML file in .NET
72. How to get Line Count of a File using StreamReader in C#
73. How to Calculate Textbox value Using JavaScript in ASP.NET
74. How to create Dynamic textbox in asp.net
75. How to convert text in TextBox to image with C# Language
76. How to populate combobox from xml file using c#
77. How to Get Particular Value From XML file in ASP.NET using C#
78. Login Page IN ASP .NET Using C#
79. How to Upload the Image in ASP .NET using C#
80. Creating Directory or Folder using ASP.NET in C#
81. Set style for label in ASPNET Using C#
82. Change style for ListItem in ASP.NET
83. How to change page theme dynamically at runtime in asp.net
84. Important properties of ValidationSummary control
85. Use Validation Summary to display message Box (C#)
86. ValidationSummary DisplayMode=BulletList
87. RequiredFieldValidatorSummary Display Mode
88. CompareValidator performs a comparison against a fixed value:
89. CompareValidator compares the value of one form field against another form
field:
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 File
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.
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-and-
drop 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
3-Tier architecture generally contains UI or Presentation Layer, Business Access Layer (BAL)
or Business Logic Layer and Data Access Layer (DAL).
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;
string connStr =
ConfigurationManager.ConnectionStrings["connectionstring"].ToString();
public PersonDAL()
{
}
conn.Open();
catch
{
throw;
Business Access Layer (BAL) Code
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;
try
{
catch
{
throw;
finally
{
pDAL = null;
}
}
}
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;
if (!Page.IsValid)
return;
int intResult = 0;
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
<%@ Page
Language="C#"AutoEventWireup="true"Codevirtual="Default.aspx.cs"Inherits="_Default"%
>
<table class="style1">
<tr>
<td colspan="2">
ADD RECORDS </td>
</tr>
<tr>
<td class="style2">
Name</td>
<td>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td class="style2">
 
Address </td>
<td>
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td class="style3">
Age </td>
<td class="style4">
<asp:TextBox ID="TextBox3" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td class="style2">
<td>
<asp:Button ID="Button1" runat="server" onclick="Button1_Click"
Text="Save Record" />
</td>
</tr>
<tr>
<td class="style2">
</td>
<td>
</td>
</tr>
</table>
</div>
</form>
</body>
</html>
• 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 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.
<script language="javascript"
type="text/javascript">
function Submit1_onclick() {
alert("click me");
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
.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
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<br />
<asp:TextBox ID="TextBox2"
runat="server" ></asp:TextBox>
<br />
<br />
.CS CODE
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
<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 />
Address
<asp:TextBox ID="TextBox2"
runat="server" ontextchanged="TextBox2_TextChanged"></asp:TextBox>
<br />
<br />
<asp:Button ID="Button1" runat="server" onclick="Button1_Click"
Text="click me" />
<br />
<br />
</div>
</form>
</body>
</html>
.CS CODE
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.
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.
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.
{}
{
public void show()
{}
State management is the process by which you maintain state and page information over
multiple requests for the same or different pages.
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.
.Cs Code
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 don’t 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
.ASPX CODE
<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
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.
• 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
• 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
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:
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.
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
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.
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.
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) .
• 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
OleDbDataAdapter da;
• .ASPX Code
</div>
</form>
</body>
</html>
Design of Gridview
OleDbConnection con;
OleDbDataAdapter da;
con = new
OleDbConnection("provider=microsoft.jet.oledb.4.0;Data
source=D:\\invent.mdb");
if (!Page.IsPostBack)
bindgrid();
bindgrid();
}
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)
Design Of Gridview
.ASPX CODE
<%@ Page Language="C#" AutoEventWireup="true" Codevirtual="Default.aspx.cs"
Inherits="_Default" %>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
</div>
</form>
</body>
</html>
.CS CODE
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.OleDb;
OleDbConnection con;
OleDbDataAdapter da;
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();
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 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 client-
side/server-side detection and validation is done without extra work by the developer!
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 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
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.
As the name suggest, this validation control make sure that control mention in Control
ToValidate cannot be empty.
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
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.
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 Specifies the name of the control which acts like a source control
Type Specifies the data type to be used for validating the input.
Default type is ‘string’.
Operator 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
Output:
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:
Type Specifies the data type to be used for validating the user input
.ASPX Code
Output:
RegularExpressionValidator control
\s Accepts a space
Occurrences:
It is used to specify the occurrence of the meta characters within the expression.
Modes:
It is used to specify the occurrence of the meta characters within the expression.
? 0 1
. or * 0 Any
+ 1 Any
.ASPX CODE
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
Output:
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
Event
.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
ValidateEmptyText is a boolean attribute that if set to true, the input control will be
validated even if it is empty.
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")..
.ASPX CODE
<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">
Regular Expression Validator </td>
<tr>
<td class="style2">
Email ID</td>
<td class="style3">
</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">
</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">
</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">
</td>
<td class="style3">
</td>
<td>
<asp:ValidationSummary ID="ValidationSummary1" runat="server"
ShowMessageBox="True" ShowSummary="False" />
</td>
</tr>
<tr>
<td class="style2">
</td>
<td class="style3">
</td>
<td>
</td>
</tr>
</table>
</div>
</form>
</body>
</html>
Output::
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.
1. Object
2. Control
3. Web Control
4. Label
</asp: Label>
Click On Button
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:
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.
Syntax Of Textbox
Properties
Property Description
AutoCompleteType Specifies the AutoComplete behavior of a TextBox
A Boolean value that specifies whether the control is
AutoPostBack automatically posted back to the server when the contents
change or not. Default is false
CausesValidation Specifies if a page is validated when a Postback occurs
Columns The width of the textbox
MaxLength The maximum number of characters allowed in the textbox
Specifies whether or not the text in the text box can be
ReadOnly changed
Rows The height of the textbox (only used if TextMode="Multiline")
Specifies that the control is a server control. Must be set to
runat
"server"
TagKey
Text The contents of the textbox
Specifies the behavior mode of a TextBox control (SingleLine,
TextMode MultiLine or Password)
ValidationGroup The group of controls that is validated when a Postback occurs
A Boolean value that indicates whether the contents of the
Wrap textbox should wrap or not
OnTextChanged The name of the function to be executed when the text in the
textbox has changed
Example
.CS CODE
Output
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 Description
Specifies if a page is validated when a button
CausesValidation
is clicked
Specifies additional information about the
CommandArgument
command to perform
Specifies the command associated with the
CommandName
Command event
Specifies the name of the function to be
OnClientClick
executed when a button is clicked
Specifies the URL of the page to post to from
PostBackUrl
the current page when a button is clicked
Specifies that the control is a server control.
runat
Must be set to "server"
Text Specifies the text on a button
Specifies whether or not a button uses the
UseSubmitBehavior browser's submit mechanism or the ASP.NET
postback mechanism
Specifies the group of controls a button causes
ValidationGroup
validation, when it posts back to the server
Example
.Cs Code
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
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
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.
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:
Example
Design
• 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
Important Properties of Asp.NET Webserver Literal control are given below. You can
Set /Get these properties at Design time or at Runtime.
Text - Accept String - Commenly Used property to Get/Set the text that you want to
render in your webpage
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 <Hr>
and sent to browser.
Transform : If you set Mode property to Transform then the string render depends upon
the type of the markup.
Click
Init
Load
PreRender
UnLoad
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:
.CS CODE:
;Literal1.Mode = LiteralMode.Encode
;Literal1.Mode = LiteralMode.PassThrough
;Literal1.Mode = LiteralMode.Transform
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.
Important Properties
CommandArgument:
specify a command argument that is passed to the Command event.
CommandName:
specify a command name that is passed to the Command event.
LinKButton Event
Event Description
Click occurs when the LinkButton control is clicked by the user.
occurs when the LinkButton control is clicked and passes its associated
Command
CommandName and CommandArgument to the server side event handler.
Example
.CS Code
}
protected void LinkButton2_Click(object sender, EventArgs e)
{
Label1.Text = "My Company name R4r TechSoft Solution ";
}
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.
Properties Discription
enables to get or set the border color of the web
BorderColor
server control. [Not Applicable]
enables to get or set the border style of the control.
BorderStyle
[Not Applicable]
enables to get or set the border width for the
BorderWidth
control. [Not Applicable]
enables to get or set an Integer value to specify the
SelectedIndex
zero-based index for the currently selected list item.
enables to get or set a Boolean value to indicate
AppendDataBoundItems whether to clear the list items before binding the
data to the control.
enables to get or set a Boolean value that indicates
AutoPostBack 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
DataTextField
field that provides the text for the list items.
enables to get or set the string formatting to control
DataTextFormatString
the text of each list item that is to be displayed.
enables to get or set the name of the data source
DataValueField
field that provides the value for the list items.
enables to manage the list items of the
Items
DropDownList control.
enables to get the currently selected list item in
SelectedItem
DropDownList control.
enables to get the value property of selected list
SelectedValue
item that returns ListItem object
Text enables to get or set the text for the control.
enables to get or set the name of the group of
ValidationGroup 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
DataMember 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
DataSourceID control from which the data-bound control retrieves
its list of data items.
enables to get an object that implements the
DataSourceObject IDataSource interface and provides the access to the
data items.
enables to get or set the object from which the data-
DataSource
bound control retrieves its list of data items.
enables to get or set a Boolean value to indicate
CausesValidation whether to perform the validation when any list item
of the control is clicked.
Events
TextChanged: Occurs when Text and SelectedValue properties change between postbacks
to the server.
Example:
.CS Code:
///////////////////////////////////////////////
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);
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:
Properties:
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
Example:
.aspx Code:
"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%;
background-color: #FFCC99;
height: 112px;
.style2
width: 689px;
.style3
width: 40px;
</style>
</head>
<body>
<div>
<table class="style1">
<tr>
<td colspan="2">
&nbs
p;
Registration Form</td>
</tr>
<tr>
<td class="style3">
Name</td>
<td class="style2">
</td>
</tr>
<tr>
<td class="style3">
Location</td>
<td class="style2">
</asp:DropDownList>
</td>
</tr>
<tr>
<td class="style3">
CollegeList</td>
<td class="style2">
</asp:DropDownList>
</td>
</tr>
<tr>
<td class="style3">
Qualification</td>
<td class="style2">
onselectedindexchanged="ListBox1_SelectedIndexChanged"
SelectionMode="Multiple"
Width="154px"></asp:ListBox>
</td>
</tr>
<tr>
<td class="style3">
</td>
<td class="style2">
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
</td>
</tr>
<tr>
<td class="style3">
</td>
<td class="style2">
</td>
</tr>
</table>
</div>
</form>
</body>
</html>
.CS Code:
{
OleDbConnection con;
OleDbDataAdapter da;
da.Fill(ds);
DropDownList1.DataSource = ds.Tables[0];
DropDownList1.DataTextField = "ship_location";
DropDownList1.DataBind();
Rows[i]["categorycolor"].ToString());
}
}
OleDbConnection con;
OleDbDataAdapter da;
da.Fill(ds);
DropDownList2.DataSource = ds.Tables[0];
DropDownList2.DataTextField = "colname";
DropDownList2.DataBind();
}
protected void Page_Load(object sender, EventArgs e)
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="";
for (int i = 0; i < ListBox1.Items.Count; i++) // Select Multiple items from Listbox
if (ListBox1.Items[i].Selected == true)
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 Description
Specifies whether the form should be posted immediately after the Checked
AutoPostBack
property has changed or not. Default is false
CausesValidation Specifies if a page is validated when a Button control is clicked
Checked Specifies whether the check box is checked or not
Attribute names and values used for the Input element for the CheckBox
InputAttributes
control
Attribute names and values used for the Label element for the CheckBox
LabelAttributes
control
runat Specifies that the control is a server control. Must be set to "server"
Text The text next to the check box
TEXTALIGN 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
ValidationGroup
posts back to the server
The name of the function to be executed when the Checked property has
OnCheckedChanged
changed
Example:
Output:
.aspx Code:
"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
{
height: 133px;
width: 43px;
}
.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: 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">
</td>
</tr>
<tr>
<td class="style5">
Name </td>
<td class="style9">
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
</td>
<td class="style10">
</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">
</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">
</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">
</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">
</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">
</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">
</td>
</tr>
<tr>
<td class="style5">
<asp:Button ID="Button1" runat="server" onclick="Button1_Click"
Text="Calculate Fees" />
</td>
<td class="style9">
</td>
<td class="style10">
</td>
</tr>
<tr>
<td class="style8">
</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();
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:
Example:
Output:
.aspx Code:
%>
.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">
CheckBoxList Control </td>
</tr>
<tr>
<td class="style2">
<br />
<br />
<br />
<br />
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>";
}
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:
Event:
Output:
.CS Code:
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).
RepeatColumns - Accept Interger Value - Used to set how Many RadioButtons you want to
display in one line.
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 Button1_Click(object sender, EventArgs e)
{
Label1.Text ="Your Favrouite Actor::> "+ RadioButtonList1.SelectedItem.Text;
}
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.
2. DescriptionUrl: You can specify the URL of the web page containing the full
description regarding the image.
3. GenerateEmptyAlternateText: It is a Boolean type property that allows or
disallows to generate the empty alt attribute while rendering the image control.
4. ImageAlign : It enables you to specify the alignment of image as a part of inline
content or web page elements.
5. ImageUrl :You can specify the URL of the image that you want to display on the
web page.
6. 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.
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:
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.
There are three different types of hot spots offered by ImageMap control. They are:
o CircleHotspot
o RectangleHotspot
o 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.
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
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:
.CS Code:
protected void Calendar1_SelectionChanged(object sender, EventArgs e)
{
TextBox1.Text = Calendar1.SelectedDate.ToLongDateString();//To display
date in TextBox
Output:
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
.CS CODE
FileUpload1.SaveAs(@"D:\temp\"
+FileUpload1.FileName);
Label1.Text = "File Uploaded: " + FileUpload1.FileName
+"
"+System.DateTime.Now.ToLongDateString();
}
else
{
Label1.Text = "No File Uploaded.";
}
OUTPUT:
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.
Wizard Layout
A Header appears at the top of each WizardStep display. The easiest way to display a
common heading is by coding the Wizard’s 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 Wizard’s DisplaySideBar="False" property. The Side Bar is
centered vertically within the total height of the Wizard.
.ASPX CODE
.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;
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";
}
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.
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:
1. ItemTemplate
2. AlternatingItemTemplate
3. EditItemTemplate
4. FooterTemplate
5. HeaderTemplate
6. SelectedItemTemplate
7. SeparatorTemplate
Here is a sample of how your DataList control's templates are arranged:
Output:
.aspx Code:
.CS CODE:
OleDbConnection con;
OleDbDataAdapter da;
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.
Example:
.aspx Code:
.CS CODE:
OleDbConnection con;
OleDbDataAdapter da;
DetailsView1.DataSource= ds.Tables[0];
DetailsView1.DataBind();
}
protected void Page_Load(object sender, EventArgs e)
{
bindgrid();
}
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>
</td>
</tr>
<tr>
<td align="right">
<b>Supplier Name:</b></td>
<td>
</td>
</tr>
<tr>
<td align="right">
<b>contact Person:</b></td>
<td>
</td>
</tr>
<tr>
<td align="right">
<b>Address:</b></td>
<td>
</td>
</tr>
</table>
</ItemTemplate>
</asp:FormView>
.CS CODE:
OleDbConnection con;
OleDbDataAdapter da;
FormViewStudent.DataBind();
}
protected void Page_Load(object sender, EventArgs e)
{
bindformview();
}
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
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 Controls display when an item is in edit mode.
EmptyDataTemplate Controls display when the ListView's data source returns no data.
EmptyItemTemplate Controls the display for an empty item.
GroupSeparatorTemplate Controls the content to display between groups of items.
GroupTemplate Specifies a container object such as a table row, div, or span
element for the content.
InsertItemTemplate Specifies content to render when users insert an item.
ItemSeparatorTemplate Controls the content to display between individual items.
ItemTemplate Controls content to display for individual items.
LayoutTemplate 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.
SelectedItemTemplate Specifies the content to display for the currently selected item.
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;
ListView1.DataSource= ds.Tables[0];
ListView1.DataBind();
ListView1.SelectedIndex= e.NewSelectedIndex;
string p = ListView1.SelectedDataKey.Value.ToString();
binddata();
}
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.
o ItemTemplate
o AlternatingItemTemplate
o HeaderTemplate
o FooterTemplate
o SeparatorTemplate
ItemTemplate: ItemTemplate defines how the each item is rendered from data source
collection.
HeaderTemplate: HeaderTemplate will emit markup for Header element for DataSource
collection
FooterTemplate: FooterTemplate will emit markup for footer element for DataSource
collection
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:
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();
da.Fill(ds);
Repeater1.DataSource= ds.Tables[0];
Repeater1.DataBind();
}
repeaterbinddata();
}
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.
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.
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>
Example:
Output:
.aspx Code:
<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>
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.
</siteMapNode>
</siteMap>
• 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:
Code Example:
<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.
TreeView:
The menu looks like a tree with branches that can be opened or closed with + or - symbol.
Code Example:
<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.
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.
• 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.
• 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.
• 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 other’s 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.
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
<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" Font-
Names="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" Font-
Size="0.9em"
ForeColor="White" />
</asp:Login>
</td>
<td class="style3">
</td>
</tr>
<tr>
<td class="style9">
</td
<td class="style2">
</td>
</tr>
</table>
</div>
</form>
</body>
</html>
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 SHA-
512. SHA-1 is the most commonly used of the SHA series.
Applications of SHA-1:
.CS Code:
Design:
.CS Code:
myConnection.Open();
GridView1.DataSource = myCommand.ExecuteReader();
GridView1.DataBind();
myConnection.Close();
Output:
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-
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.
Design:
When You Click On Button Image Will Rotate:
Like this
.ASPX CODE:
.CS CODE:
Design:
Output:
When You Click Soch Na Tha Movie Button This Dialog Box Will Appear
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.
You will need to set the Bound column in order to see the text in the cells of the grid view
control.
.ASPX Code:
<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;">
<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>
</td>
</tr>
</table>
<br />
<br />
</div>
</form>
</body>
</html>
.CS Code:
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 void binddata1()
{
SqlConnection con = new SqlConnection(@"data source=R4R-
01\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;
TextBox2.Text = GridView1.SelectedRow.Cells[1].Text;
TextBox3.Text = GridView1.SelectedRow.Cells[2].Text;
TextBox4.Text = GridView1.SelectedRow.Cells[3].Text;
}
//Update Row
protected void GridView1_RowUpdating(object sender,
GridViewUpdateEventArgs e)
{
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=R4R-
01\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:
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);
}
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:
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.
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.
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 System.Data.SqlClient;
using System.Drawing;
using System.Data;
using System.IO;
using System.Drawing.Imaging;
Source Code for Save the image file into the database
FileUpload1.PostedFile.InputStream.Read(pic, 0, length);
// Insert the image and comment into the database
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:
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
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:
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.
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:
Output:
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.
Design Output:
Step 1:
Step 2:
if (FileUpload1.HasFile)
{
try
{
FileUpload1.SaveAs(path);
Label1.Text = "Mr."+" " + TextBox1.Text + " Your Resume
Successfully saved";
}
catch (Exception ex)
{
}
}
}
Output:
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.
Response.End();
}
Making Google Search from website
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:
.CS CODE:
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;
using System.Collections.Generic;
using System.Globalization;
}
}
Output:
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
ForeColor="#CCFF99" />
Font-Bold="True"
</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
When you view the page without skin in a browser, you should see:
When you set your theme to the ".aspx" page and view the page in a browser, you should
see:
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
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
I’m 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.
1. HTTP 80
2. Telnet 23
3. SMTP 25
4. SNPP 444
5. DNS 53
6. FTP (Data) 20
7. FTP (Control) 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.
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>
Design:
.ASPX CODE:
<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>
</tr>
</table>
</div>
</form>
</body>
</html>
.CS CODE:
Output:
Now click on Browse button and select Images which you want to upload.
Now click on the uploadImages button.
What is Virtual Directory
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#:
chkBox.AutoCheck = true;
chkBox.Text = "Checked";
chkBox.Checked = true;
chkBox.CheckState = CheckState.Checked;
chkBox.CheckedChanged += new
EventHandler(chkBox_CheckedChanged);
Controls.Add(chkBox);
}
font-size: 25px;
font-style:normal;
height:30px;
.aspx Code:
Output:
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 System.Globalization;
using System.Resources;
using System.Threading;
using System.Reflection;
Step 7:
Now in global decleration section of .cs file create an instance of ResourceManager
and CultureInfo Class.
.CS code:
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.Globalization;
using System.Resources;
using System.Threading;
using System.Reflection;
public partial class _Default : System.Web.UI.Page
{
ResourceManager rm;
CultureInfo ci;
private void LoadString(CultureInfo 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:
<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>
</div>
</form>
</body>
Output:
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>
</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 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;
Output:
When You Click Generate xml file Button XML file is generated in E Drive with Name
test2.xml:
test2.xml
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 System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
namespace WindowsFormsApplication53
{
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
int totalRecordCount;
private void button1_Click(object sender, EventArgs e)
{
Output:
.ASpx Code:
<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;
}
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div style="width: 332px">
</div>
</form>
</body>
</html>
Output:
.CS Code:
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;
Panel1.Controls.Add(txt);
Panel1.Controls.Add(new Literal("<br />"));
}
}
Output:
.aspx Code:
.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.IO;
using System.Drawing;
using System.Drawing.Imaging;
}
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:
.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:
.CS Code:
// 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
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.
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)
{
}
}
}
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:
<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 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.IO;
Output:
When You Click on Create Directory Button then Directory Will be Create in Solution
Explorer
.aspx Code:
<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 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;
}
protected void myList_SelectedIndexChanged(object sender,
EventArgs e)
{
}
}
.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>
<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 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;
Output:
.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>
<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 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;
}
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:
DisplayMode: How the error messages are formatted. Possible values are BulletList, List,
and SingleParagraph.
<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" />
<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" />
<asp:Button
id="btnSubmit"
Text="Submit"
Runat="server" onclick="btnSubmit_Click" />
</div>
</form>
</body>
</html>
Output:
<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>
<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
<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"/>
Password:
<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" />
Output:
RequiredFieldValidatorSummary DisplayMode
.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>
<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 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;
Output:
If You select Summary Then messagebox will be display
CompareValidator performs a comparison against a fixed value
.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>
<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" />
<asp:Button
id="btnSubmit"
Text="Submit"
Runat="server" onclick="btnSubmit_Click" />
</div>
</form>
</body>
</html>
.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;
Output:
<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:
<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>
<br />
<br>
Confirm Password
<asp:TextBox ID="TextBox2" Runat="server"
TextMode="Password"></asp:TextBox>
<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>
Output:
<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:
<asp:TextBox ID="txtPass1" runat="server"
TextMode="password"></asp:TextBox>
<br />
Reenter
Password:
<asp:TextBox ID="txtPass2" runat="server"
TextMode="password"></asp:TextBox>
<br />
<asp:Button ID="btnSubmit" Text="Click this to test validation"
runat="server" />
</div>
</form>
</body>
</html>
Output:
<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:
<asp:TextBox id="usernameTextBox" runat="server" />
<asp:RequiredFieldValidator id="usernameReq"
runat="server"
ControlToValidate="usernameTextBox"
ErrorMessage="Username is required!"
SetFocusOnError="True" />
<br />
Password
<asp:TextBox id="passwordTextBox" runat="server"
TextMode="Password"
ontextchanged="passwordTextBox_TextChanged" />
<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:
<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 />
&n
<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 />
<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#)
<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"
runat="server"
ValidationGroup="Group1"
ControlToValidate="TextBox1"></asp:Requ
iredFieldValidator>
<asp:Button ID="Button1" runat="server" Text="Validate
Group1"
ValidationGroup="Group1"
OnClick="Button_Click"/></asp:Panel> <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>
How to Validate Form using Server Side Validation in ASp.NET
.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;
}
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:
<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):
<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>
<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 <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>
<br />
Output:
.aspx Code
<%@ Page Language="C#" AutoEventWireup="true"
Codevirtual="customvalidation.aspx.cs"
Inherits="customvalidation" %>
<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 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;
}
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
<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" />
</div>
</form>
</body>
</html>
.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;
}
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:
.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>
<asp:Button ID="Button1" runat="server" onclick="Button1_Click"
Text="Logout" />
</div>
</form>
</body>
</html>
.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;
}
protected void Button1_Click(object sender, EventArgs
e)
{
FormsAuthentication.SignOut();
Response.Redirect("Home.aspx");
}
}
Like this
Write Code in Global.asax file
<script runat="server">
public static int count = 0;
void Application_Start(object sender, EventArgs e)
{
Application["myCount"] = count;
// Code that runs on application startup
</script>
.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;
Output:
When Anyone Visit your Website then Total Visitor will be increased.
Add Namespace:
Using System.XML;
.CS Code:
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:
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 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;
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"));
}
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.OleDb;
cn.Open();
da.Fill(ds);
Output:
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.Collections.Generic;
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:
<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>
</div>
</form>
</body>
</html>
Output:
.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.Collections;
using System.Collections.ObjectModel;
.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>
<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:
Download itextsharp.dll
.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 iTextSharp.text.pdf;
using iTextSharp.text.html;
using iTextSharp.text.html.simpleparser;
using System.IO;
using iTextSharp.text;
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
{
Response.AddHeader("content-disposition",
"attachment;filename=DataTable.pdf");
Response.Cache.SetCacheability(HttpCacheability.NoCa
che);
GridView1.RenderControl(hw);
PdfWriter.GetInstance(pdfDoc,
Response.OutputStream);
pdfDoc.Open();
htmlparser.Parse(sr);
pdfDoc.Close();
Response.Write(pdfDoc);
Response.End();
}
}
.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>
</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 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.Data.OleDb;
using System.IO;
using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.text.html;
using iTextSharp.text.html.simpleparser;
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();
GridView1.RenderControl(hw);
PdfWriter.GetInstance(pdfDoc,
Response.OutputStream);
pdfDoc.Open();
pdfDoc.Add(jpg);
htmlparser.Parse(sr);
pdfDoc.Close();
Response.Write(pdfDoc);
Response.End();
}
.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>
<asp:GridView ID="GridView1" runat="server">
</asp:GridView>
</div>
</form>
</body>
</html>
Output:
.CS Code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace WindowsFormsApplication53
{
public partial class Form4 : Form
{
public Form4()
{
InitializeComponent();
}
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 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.Drawing;
using System.Drawing.Imaging;
Output:
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.
<customErrors mode="On|Off|RemoteOnly"
defaultRedirect="url">
<error statusCode="statuscode" redirect="url"/>
</customErrors>
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.
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:
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" >
</customErrors>
.CS Code:
Output:
.CS CODE:
int totalSeconds = 0;
int seconds = 0;
int minutes = 0;
string time = "";
if (!Page.IsPostBack)
{
Session["time"] = 1800 ;
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;
}
}
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 :
<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>
DataSourceID="SqlDataSource1" AllowPaging="True"
AllowSorting="True">
<Columns>
<asp:BoundField DataField="CompanyName"
HeaderText="CompanyName"
SortExpression="CompanyName" />
</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:
}
Calculate Firstdate And Lastdate of Month in ASP.NET Using C#
.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;
}
protected void Button1_Click(object sender, EventArgs e)
{
DateTime today = DateTime.Now; //current date
today = today.AddMonths(1);
DateTime lastDay = today.AddDays(-(today.Day)); //last day
Label1.Text = firstDay.ToString(); ;
Label2.Text = lastDay.ToString();
}
}
Output:
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:
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
Design Code
Out Put:
How to Load XML to DataSet 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;
Out Put:
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;
MyDataSet.Merge(ds);
GridView1.DataSource = MyDataSet;
GridView1.DataBind();
}
}
Out Put:
How to create an application domain 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;
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:
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();
}
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
Out Put:
Use HtmlHead control to set the page title and meta tags
OutPut:
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>
Session.Timeout = 60;
File: Web.Config
<configuration>
<system.web>
<sessionState
cookieless="AutoDetect"
regenerateExpiredSessionId="true" />
</system.web>
</configuration>
Default.aspx
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;
Out Put:
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)
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 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;
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;
Out Put:
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)
{
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
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>
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>
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>
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>
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>
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 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:
Event:
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";
}
}
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).
RepeatColumns - Accept Interger Value - Used to set how Many RadioButtons you want to
display in one line.
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 Button1_Click(object sender, EventArgs e)
{
Label1.Text ="Your Favrouite Actor::> "+ RadioButtonList1.SelectedItem.Text;
}
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.
2. DescriptionUrl: You can specify the URL of the web page containing the full
description regarding the image.
3. GenerateEmptyAlternateText: It is a Boolean type property that allows or
disallows to generate the empty alt attribute while rendering the image control.
4. ImageAlign : It enables you to specify the alignment of image as a part of inline
content or web page elements.
5. ImageUrl :You can specify the URL of the image that you want to display on the
web page.
6. 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.
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:
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.
There are three different types of hot spots offered by ImageMap control. They are:
o CircleHotspot
o RectangleHotspot
o 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.
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
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
The format for displaying the names of the days. Can take one of the
following values:
• FirstLetter
DayNameFormat
• 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:
.CS Code:
protected void Calendar1_SelectionChanged(object sender, EventArgs e)
{
TextBox1.Text = Calendar1.SelectedDate.ToLongDateString();//To display
date in TextBox
Output:
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
.CS CODE
FileUpload1.SaveAs(@"D:\temp\"
+FileUpload1.FileName);
Label1.Text = "File Uploaded: " + FileUpload1.FileName
+"
"+System.DateTime.Now.ToLongDateString();
}
else
{
Label1.Text = "No File Uploaded.";
}
OUTPUT:
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>
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>
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> </td>
<td> </td>
<td> </td>
</tr>
<tr> <td> </td>
<td> </td>
<td> </td>
</tr>
<tr><td> </td>
<td> </td>
<td> </td>
</tr>
</table>
</div>
</form>
</body>
</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>
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: 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);
}
}
}
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: 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();
}
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();
}
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/>
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.
Page 1
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:
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.
Page 1
Tot
Show al Post Your
Questions Last Post
Answers Pos Answers
ts
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)
Show Post Your
5
1. MsgSent.Text = Msg.Text; Answers Answers Monu Sharma
2. MsgSent.Text = Msg.Text
3. Both
4. None
Which is used for code-in-line model?
1.< script runat="server"> Show Post Your
2.< script javascript="server"> 2
Answers Answers Monu Sharma
3.Both
4.None
Which is code allows the modification
of the head tag at runtime?
Show Post Your 13.03.10
1 < head runat="server"> 1
2.< script javascript="server"> Answers Answers Heena
3.Both
4.None
How you can change the page title by
changing the using C#
4.None
Which is not used into @Page Show 2 Post Your 14.03.10
attributes ravi
Answers Answers
1. Async ,CodeFile
2. EnableTheming, MasterPageFile
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 Post Your 13.03.10
</system.web> 1
</configuration> Answers Answers Hima
2. < pages>
< system.web>
< pages
masterpagefile="r4r.co.in.MasterPage"
/>
</system.web>
</ pages>
3.Both
4.None
@Page directive
<%@ MasterType
VirtualPath="~/MasterPage.master" %>
Show Post Your 04.07.10
The above syntax is used to make the 3
Master property typed to the class Answers Answers jagadeesh
that is stored in the referenced
master on ASP page.
1.Yes
2.No
1.System,System.Collections,
System.IO
2.System.Web,System. Web.UI Show Post Your 20.09.10
3.System.Web.UI.HtmlControls,System. Answers 4
Answers Ashwini.S.Acharya
Web.UI.WebControls
A . 1
B. 1,2,3
C, 2,3
D. None
The ASP.NET pages directives are
A . 1,2
B. 1,2,3
C, 2,3
D. None
Syntax for Code Declaration Blocks Show 2 Post Your
1. < script runat="server" sushilkumar
Answers Answers
[language="language"]>
//code……………….
</script>
2. <asp runat="server"
[language="language"]>
//code……………….
</asp>
3. 1 and 2
4. None
Syntax for Assembly directive
specifies
3. 1 and 2
4. None
Syntax for Register directive
specifies
//code……………….
</ Register > Show Post Your 13.03.10
1
Answers Answers Vivak
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" %>
3. 1 and 2
4. None
Syntax for Custom-Control to insert a Show 3 Post Your
custom control into a page Ravindra M Kanje
Answers Answers
1. <tagprefix:tagname id="controlID"
runat="server"
eventname="eventHandler" />
3. 1 and 2
4. None
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 user’s locale?
Ans: System.Web.UI.Page.Culture
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.
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.
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.
Q32: What is the transport protocol you use to call a Web service?
Ans: SOAP (Simple Object Access Protocol) is the preferred protocol.
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.
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 load-
balancing) 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.