0% found this document useful (0 votes)
11 views

Final ASP.NET File-06313702022

The document provides a comprehensive guide for creating various console applications and ASP.NET web forms using Visual Studio. It includes step-by-step instructions for tasks such as creating a console application, taking user input, performing mathematical operations, and configuring Visual Studio for ASP.NET development. Additionally, it covers the implementation of validation controls and the ASP.NET page life cycle events.

Uploaded by

Aasif Ali
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views

Final ASP.NET File-06313702022

The document provides a comprehensive guide for creating various console applications and ASP.NET web forms using Visual Studio. It includes step-by-step instructions for tasks such as creating a console application, taking user input, performing mathematical operations, and configuring Visual Studio for ASP.NET development. Additionally, it covers the implementation of validation controls and the ASP.NET page life cycle events.

Uploaded by

Aasif Ali
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 43

ASP.

NET LAB FILE 01113702022

Q1. Write down steps to create a console application?

Solution 1:

Create a .NET console app project named "HelloWorld".

1. Start Visual Studio 2022.

2. On the start page, choose Create a new project.

3. On the Create a new project page, enter console in the search box. Next,
choose C# or Visual Basic from the language list, and then choose All
platforms from the platform list. Choose the Console App template, and then
choose Next.

Page | 1
ASP.NET LAB FILE 01113702022

4. In the Configure your new project dialog, enter HelloWorld in the Project
name box. Then choose Next.

Page | 2
ASP.NET LAB FILE 01113702022

5. In the Additional information dialog:

 Select .NET 8 (Preview).


 Select Do not use top-level statements.
 Select Create.

The template creates a simple application that displays "Hello, World!" in the console
window. The code is in the Program.cs or Program.vb file:

The code defines a class, Program, with a single method, Main, that takes a String array as an
argument. Main is the application entry point, the method that's called automatically by the
runtime when it launches the application. Any command-line arguments supplied when the
application is launched are available in the args array.

Run the app


1. Press Ctrl+F5 to run the program without debugging.

A console window opens with the text "Hello, World!" printed on the screen.
(Or "Hello World!" without a comma in the Visual Basic project template.)

2. Press any key to close the console window.

Taking User Input


prompt the user for their name and display it along with the date and time.

1. In Program.cs or Program.vb, replace the contents of the Main method, which is


the line that calls Console.WriteLine, with the following code:

Page | 3
ASP.NET LAB FILE 01113702022

This code prompts the user to enter their name using “Console.ReadLine()”
function. Then It displays the current date with the help of “DateTime.Now”
function. And then it reads a key means until user presses any key the console
window will not close.

The dollar sign ($) in front of a string lets you put expressions such as variable
names in curly braces in the string. The expression value is inserted into the
string in place of the expression. This syntax is referred to as interpolated
strings.

1. Press Ctrl+F5 to run the program without debugging.

2. Respond to the prompt by entering a name and pressing the Enter key.

3. Press any key to close the console window.

Q2. Write a Program to take User Name as Input and Print “Hello User
Name”?
Solution 2:
using System;

public class HelloWorld


{
public static void Main(string[] args)
{
Console.WriteLine("1. Enter Your User_Name here: ");

Page | 4
ASP.NET LAB FILE 01113702022

string name=Console.ReadLine();
Console.WriteLine("Hello{0} ",name);
}
}
Output 2:

Q3. Write a Program to take Two User Input and Perform Basic
Mathematical Operations (Addition, Subtraction, Multiplication, Division)
Ans:

using System;
public class Operations
{
public static void Main(string[] args)
{
Console.WriteLine("\n Performing the Basic Mathmatical Operations\n");
Console.Write("\n 1. Enter the First Number: ");
int num1 = Convert.ToInt16(Console.ReadLine());
Console.Write("\n 2. Enter the Second Number: ");
int num2 = Convert.ToInt16(Console.ReadLine());
//Performing all Mathmatical Operations.
Console.WriteLine("\n i). Addition: " + (num1 + num2));
Console.WriteLine("\n ii). Substraction: " + (num1 - num2));
Console.WriteLine("\n iii). Multiplication: " + (num1 * num2));
Console.WriteLine("\n iv). Division: " + (num1 / num2));
}}

Page | 5
ASP.NET LAB FILE 01113702022

Output 3:

Q4. Write a Program to check whether the user Input Number is Even OR
Odd?
Solution 4:
using System;
public class Operations
{
public static void Main(string[] args)
{
Console.Write("\n Enter the Number to Check: ");
int num1 = Convert.ToInt16(Console.ReadLine());
if (num1 % 2 == 0)
{ Console.WriteLine("\n Number is Even: " + num1); }
else
{ Console.WriteLine("\n Number is Odd: " + num1); }
}
}
Output 4:

Page | 6
ASP.NET LAB FILE 01113702022

Q5. Write a Program to print the prime number which lie in a given range
by the User-input? (Use If-Conditional Statement)?
Solution 5:
static bool IsPrime(int number)
{
if (number <= 1)
return false;
for (int i = 2; i <= Math.Sqrt(number); i++)
{
if (number % i == 0)
return false;
}
return true;
}
static void Main()
{
Console.WriteLine("Enter the range to find prime numbers:");

// Get user input for the range


Console.Write("Enter the start of the range: ");
int start = Convert.ToInt32(Console.ReadLine());

Console.Write("Enter the end of the range: ");


int end = Convert.ToInt32(Console.ReadLine());
Console.WriteLine($"Prime numbers between {start} and {end} are:");
for (int i = start; i <= end; i++)
{
if (IsPrime(i))
{
Console.Write($"{i} ");
}}
Console.ReadLine(); // To keep the console window open
}
Output 5:

Page | 7
ASP.NET LAB FILE 01113702022

Q6. Write a Program to take a Number as Input and Print its table by
using the FOR-LOOP?
Solution 6:
using System;
public class Operations
{
public static void Main(string[] args)
{
Console.Write("\n Enter the Number To Find its table: ");
int num1 = Convert.ToInt16(Console.ReadLine());
for (int i = 1; i <= 10; i++)
{
Console.WriteLine("{0} * {1} = {2}",num1,i,num1*i);
}
}
}
OUTPUT 6.1:

Q7. Create a console application to take a temperature (in Fahrenheit) as


input from the user and print the temperature in Celsius?
Page | 8
ASP.NET LAB FILE 01113702022

Solution 7:
using System;
class FahrenheitToCelsius
{
static void Main(string[] args)
{
Console.WriteLine(“;\n 1. Enter Fahrenheit Temperature: “; );
double Fahrenheit = Convert.ToDouble(Console.ReadLine()); ;
double Celsius = (Fahrenheit - 32) * 5 / 9;
Console.WriteLine(“;\n 2. The converted Celsius temperature is: “; + Celsius);
Console.ReadLine();
}
}
Output 7:

Q8. Explain the steps to configure Visual Studio for ASP.NET Web Forms
development and also describe the process of creating a new ASP.NET
Web Forms project in it.

SOLUTION 8:

1. Open Visual Studio: Start Visual Studio by clicking on its icon on your
desktop or searching for it in the start menu.

2. Create a New Project: Once Visual Studio is open, go to the “File”


menu at the top left corner of the screen. Click on “File”, then hover over
“New”, and then click on “Project”. This will open a new dialog box.

Page | 9
ASP.NET LAB FILE 01113702022

Select Templates: In the new dialog box, you will see a list of templates on the
left side. Click on “Templates”, then click on “Visual C#”, and finally click
on“Web”. This will display all the web-related templates in the center column.

Page | 10
ASP.NET LAB FILE 01113702022

Choose ASP.NET Web Application Template: In the center column, look for
the template named “ASP.NET Web Application”. Click on it to select it.

Name Your Project: At the bottom of the dialog box, you will see two fields:
“Name” and “Location”. In the “Name” field, enter the name of your project
(for example, “WingtipToys”). In the “Location”field, choose where you want
to save your project on your computer. Once you’ve filled out these fields,

 Change Authentication: A new dialog box will appear with a few


options. Look for a button labeled “Change Authentication” and click on
it. This will open another dialog box where you can choose your
authentication method. For now, you can leave it as default and click
“OK”.

 Select Web Forms Template: You will be taken back to the previous
dialog box. Here, look for a section labeled “Select a template”. Under
this section, click on the option labeled “Web Forms”. Finally, click on
the “OK” button to create your new ASP.NET Web Forms project.

Page | 11
ASP.NET LAB FILE 01113702022

 A New window will open here you have to open default.aspx and the
following code will appear.

Page | 12
ASP.NET LAB FILE 01113702022

 When you click on design it will show the preview of the code output in
the inbuilt browser of the visual studio code.

Q9. Create a Web Page in ASP.NET to display “Hello World” using


response.write() method and also explain the Page Life Cycle events in
ASP.NET Web Forms.
SOLUTION 9:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace Wb_form

Page | 13
ASP.NET LAB FILE 01113702022

{
public partial class _Default : Page
{
protected void Page_Load(object sender, EventArgs e)
{
Response.Write("<h1>Hello World</h1>");
}
}
}
Output 9:

Page | 14
ASP.NET LAB FILE 01113702022

Now, let’s talk about the Page Life Cycle events in ASP.NET Web Forms:
1. PreInit: This event occurs after the start stage is complete and before the
initialization stage begins.
2. Init: This event occurs after all controls have been initialized and any skin
settings have been applied.
3. InitComplete: This event occurs at the end of the page’s initialization stage.
4. PreLoad: This event occurs before the Load event.
5. Load: The Page object calls the OnLoad method on the Page object, and then
recursively does the same for each child control until the page and all controls
are loaded. The Load event of individual controls occurs after the Load event of
the page.
6. Control events: These are events like button Click, dropdown
SelectedIndexChanged, etc.
7. LoadComplete: This event occurs at the end of the event-handling stage.
8. PreRender: This event occurs before generating output to be rendered to the
browser.
9. PreRenderComplete: This event occurs after each data bound control whose
DataSourceID property is set calls its DataBind method.
10. SaveStateComplete: This event occurs after the view state and control state
have been saved for the page and for all controls.
11. Render: This is not an event; instead, at this stage of processing, ASP.NET
calls this method on each control.
12. Unload: This event occurs for each control and then for the page.

Output 9:

Page | 15
ASP.NET LAB FILE 01113702022

Q10. Create a web page with basic controls such as label, textbox, and a
button and take input from the user in the textbox and display it on the
web page when a button is clicked?

Solution 10:

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


CodeBehind="WebForm1.aspx.cs" Inherits="WebApplication2.WebForm1"
%>
<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>ASP.NET Web Form Example</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<h1>Enter your name</h1>
<asp:Label ID="lblMessage" runat="server" Text=""></asp:Label>
<br />
<asp:TextBox ID="txtInput" runat="server"></asp:TextBox>
<br />
<asp:Button ID="btnSubmit" runat="server" Text="Submit" />
</div>
</form>
</body>
</html>

Output 10:

Page | 16
ASP.NET LAB FILE 01113702022

Q11. Create a Web page in ASP.NET to show the list of courses being
taught in IITM and show the chosen course on the web page in the textbox
with “thank you for choosing course name”?

Solution 11:

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


CodeBehind="WebForm1.aspx.cs" Inherits="WebApplication2.WebForm1"
%>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Course Selection at IITM</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<h1>Course Selection at IITM</h1>
<asp:DropDownList ID="ddlCourses" runat="server">
<asp:ListItem Text="Computer Science" Value="computer-
science" />
<asp:ListItem Text="Electrical Engineering" Value="electrical-
engineering" />
<asp:ListItem Text="Mechanical Engineering" Value="mechanical-
engineering" />
<asp:ListItem Text="Civil Engineering" Value="civil-engineering" />
</asp:DropDownList>
<br />
<asp:Button ID="BtnSubmit" runat="server" Text="Submit"
OnClick="BtnSubmit_Click" />
</div>
</form>
</body>
</html>

Output 11:

Page | 17
ASP.NET LAB FILE 01113702022

Q12. Create a web page in ASP.NET that demonstrates the use of


RequiredFieldValidator, CompareValidator, RangeValidatorm,
ustomValidator and validationSummary controls?

Output 12:

(i). Randomn Validation Controls.

<%@ Page Title="Home Page" Language="C#"


MasterPageFile="~/Site.Master" AutoEventWireup="true"
CodeBehind="Default.aspx.cs" Inherits="WebApplication27._Default" %>

<asp:Content ID="BodyContent" ContentPlaceHolderID="MainContent"


runat="server">

<table border="0" cellpadding="0" cellspacing="0">


<tbody><tr>
<td>
<b>Enter Your Name: </b>
<asp:textbox runat="server" id="txtTestForRequiredField">
Page | 18
ASP.NET LAB FILE 01113702022

</asp:textbox></td>
</tr>
<tr>
<td>
<asp:requiredfieldvalidator id="RequiredFieldValidator1"
forecolor="Red" errormessage="Please enter your name"
controltovalidate="txtTestForRequiredField" runat="server">
</asp:requiredfieldvalidator></td>
</tr>
<tr>
<td>
<asp:button id="Button1" text="Save" runat="server">
</asp:button></td>
</tr>
</tbody></table>

</asp:Content>

Output(i):

->This validator is used to make an input control required. It will throw an error
if user leaves input control empty.

It is used to mandate form control required and restrict the user to provide data.

Page | 19
ASP.NET LAB FILE 01113702022

Note: It removes extra spaces from the beginning and end of the input value
before validation is performed.

The ControlToValidateproperty should be set with the ID of control to validate.

(ii). Compare Validator.

Solution(ii):

<%@ Page Title="Home Page" Language="C#"


MasterPageFile="~/Site.Master" AutoEventWireup="true"
CodeBehind="Default.aspx.cs" Inherits="WebApplication27._Default" %>

<asp:Content ID="BodyContent" ContentPlaceHolderID="MainContent"


runat="server">
<table border="0" cellpadding="0" cellspacing="0">
<tr>
<td>Password</td>
<td>
<asp:TextBox ID="txtPassword" runat="server"
TextMode="Password" /><br/>
<asp:RequiredFieldValidator runat="server"
ControlToValidate="txtPassword"
ErrorMessage="Password is required." ForeColor="Red"
Display="Dynamic">
</asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td>Confirm Password</td>
<td>
<asp:TextBox ID="txtConfirmPassword" runat="server"
TextMode="Password" /><br/>
<asp:CompareValidator runat="server"
ControlToCompare="txtPassword" ControlToValidate="txtConfirmPassword"
ErrorMessage="Passwords do not match." ForeColor="Red"
Display="Dynamic">
</asp:CompareValidator>
</td>
</tr>
<tr>
<td></td>

Page | 20
ASP.NET LAB FILE 01113702022

<td><asp:Button Text="Submit" runat="server" /></td>


</tr>
</table>
</asp:Content>

Output (ii):

(iii). Range Validator.

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


CodeBehind="WebForm1.aspx.cs" Inherits="WebApplication2.WebForm1" %>

<!DOCTYPE html>

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>RangeValidator Example</title>
</head>
<body>
<form id="form1" runat="server">
<h1>User Information</h1>
<table>
<tr>

Page | 21
ASP.NET LAB FILE 01113702022

<td style="text-align: right">Age :</td>


<td style="text-align: left">
<asp:TextBox ID="txtAge" runat="server"
TextMode="Number"></asp:TextBox>
<asp:RangeValidator ID="RangeValidator1" runat="server"
ControlToValidate="txtAge" ErrorMessage="Invalid Age !!"
MaximumValue="100" MinimumValue="1" Type="Integer"
Display="Dynamic" Text=" (1-100)"
ForeColor="Red"></asp:RangeValidator>
</td>
</tr>
<tr>
<td>&nbsp;</td>
<td style="text-align: left">
<asp:Button ID="btnSubmit" runat="server" Text="Submit"
OnClick="btnSubmit_Click" />
</td>
</tr>
</table>
</form>
</body>
</html>

Output(iii):

(iv) Custom Field Validator.

Page | 22
ASP.NET LAB FILE 01113702022

1) Client Side Example of CustomValidator:

<table>
<tbody><tr>
<td>
<b>Password</b>(Client side)
</td>
<td>
<asp:textbox runat="server" id="txtPassword"><br>
<asp:customvalidator clientvalidationfunction="validateLength"
forecolor="Red" errormessage="Password cannot be less than 5 characters."
controltovalidate="txtPassword" runat="server">
</asp:customvalidator></asp:textbox></td>
</tr>
</tbody></table>
<script type="text/ecmascript">
function validateLength(sender, args) {
debugger;
if (args.Value.length < 5)
return args.IsValid = false;
else
return args.IsValid = true;
}
</script>

2) Server Side Example of CustomValidator:

<table>
<tbody><tr>
<td>
<b>Password</b>(Server side)
</td>
<td>
<asp:textbox runat="server" id="txtPassword2">
<br>
<asp:customvalidator id="CustomValidator1" forecolor="Red"
onservervalidate="CustomValidator1_ServerValidate" errormessage="Password
cannot be less than 5 characters." controltovalidate="txtPassword2"
runat="server">

Page | 23
ASP.NET LAB FILE 01113702022

</asp:customvalidator></asp:textbox></td>
</tr>
<tr>
<td>

</td>
<td>
<asp:button text="Validate" id="Button1" runat="server">
</asp:button></td>
</tr>
</tbody></table>
protected void CustomValidator1_ServerValidate(object source,
ServerValidateEventArgs args)
{
if (args.Value.Length < 5)
{
args.IsValid = false;
}
else
{
args.IsValid = true;
}
}

Output(iv):

(v). Validation Summary Controls.

Page | 24
ASP.NET LAB FILE 01113702022

 ASP.NET ValidationSummary Control

This validator is used to display list of all validation errors in the web form.

It allows us to summarize the error messages at a single location.

We can set DisplayMode property to display error messages as a list, bullet list or single
paragraph.

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


mo.aspx.cs"
Inherits="asp.netexample.ValidationSummeryDemo" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Validation Form Controls!</title>
</head>
<body>
<form id="form1" runat="server">
<div>
</div>
<table class="auto-style1">
<tr>
<td class="auto-style2">User Name</td>
<td>
<asp:TextBox ID="username" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="user" runat="server" ControlToValidate="username"
ErrorMessage="Please enter a user name" ForeColor="Red">*</
asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td class="auto-style2">Password</td>
<td>
<asp:TextBox ID="password" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="pass" runat="server" ControlToValidate="password"
ErrorMessage="Please enter a password" ForeColor="Red">*</asp:RequiredFieldValidator>

</td>

Page | 25
ASP.NET LAB FILE 01113702022

</tr>
<tr>
<td class="auto-style2">
<br/>
<asp:Button ID="Button1" runat="server"Text="login"/>
</td>
<td>
<asp:ValidationSummary ID="ValidationSummary1" runat="server" ForeColor="Red"/>
<br/> </td> </tr> </table> </form> </body>
</html>

Output (iv):

Q13. Write a program to display advertisements using AdRotator control?


Page | 26
ASP.NET LAB FILE 01113702022

Solution13:

<?xml version="1.0" encoding="utf-8" ?>


<Advertisements>
<Ad>
<ImageUrl>img/1.png</ImageUrl>
<NavigateUrl>https://meeraacademy.com</NavigateUrl>
<AlternateText>Meera Academy</AlternateText>
<Impressions>50</Impressions>
<Keyword>Meera</Keyword>
</Ad>

<Ad>
<ImageUrl>img/2.png</ImageUrl>
<NavigateUrl>http://meera.com</NavigateUrl>
<AlternateText>Meerta Aademy</AlternateText>
<Impressions>100</Impressions>
<Keyword>Academy</Keyword>
</Ad>
<Ad>
<ImageUrl>img/3.png</ImageUrl>
<NavigateUrl>https://meeraacademy.com</NavigateUrl>
<AlternateText>Meerta Aademy</AlternateText>
<Impressions>50</Impressions>
<Keyword>Academy</Keyword>
</Ad>
</Advertisements>

<asp:AdRotator id="controlName" runat="server"

AdvertisementFile="ads.xml" Target="_self">
</asp:AdRotator>
// Create an AdRotator control.
AdRotator rotator = new AdRotator();
// Set the control's properties.
rotator.AdvertisementFile = "AdRotatorFiles.xml";
// Add the control to the Controls collection of a
// PlaceHolder control.
PlaceHolder1.Controls.Add(rotator);

Page | 27
ASP.NET LAB FILE 01113702022

Output 13:

Q14. Create a student registration web form. Show the usage of all basic
controls; label, textbox, button, checkbox, radiobutton. On submission of
data display “Your response has been submitted” on a web page using
response.write() method?

Page | 28
ASP.NET LAB FILE 01113702022

Solution 14:

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


CodeBehind="WebControls.aspx.cs"

Inherits="WebFormsControlls.WebControls" %>

<!DOCTYPE html>

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

<head runat="server">

<title></title>

<style type="text/css">

.auto-style1 {

width: 100%;

.auto-style2 {

width: 278px;

.auto-style3 {

width: 278px;

height: 23px;

.auto-style4 {

height: 23px;

</style>

Page | 29
ASP.NET LAB FILE 01113702022

</head>

<body>

<form id="form1" runat="server">

<div>

<table class="auto-style1">

<tr> <td>

<asp:Label ID="Label1" runat="server" Text="User Name"></asp:Label>

</td> <td>

<asp:TextBox ID="username" runat="server"


required="true"></asp:TextBox></td>

</tr>

<tr>

<td>

<asp:Label ID="Label6" runat="server" Text="Email ID"></asp:Label>

</td>

<td>

<asp:TextBox ID="EmailID" runat="server"


TextMode="Email"></asp:TextBox></td>

</tr> <tr> <td>

<asp:Label ID="Label2" runat="server"


Text="Password"></asp:Label></td>

<td>

<asp:TextBox ID="TextBox2" runat="server"


TextMode="Password"></asp:TextBox></td>

</tr> <tr>

Page | 30
ASP.NET LAB FILE 01113702022

<td>

<asp:Label ID="Label3" runat="server" Text="Confirm


Password"></asp:Label></td>

<td>

<asp:TextBox ID="TextBox3" runat="server"


TextMode="Password"></asp:TextBox></td>

</tr> <tr>

<td>

<asp:Label ID="Label4" runat="server" Text="Gender"></asp:Label></td>

<td> <asp:RadioButton ID="RadioButton1" runat="server"


GroupName="gender" Text="Male" />

<asp:RadioButton ID="RadioButton2" runat="server" GroupName="gender"


Text="Female" /></td>

</tr>

<tr>

<td>

<asp:Label ID="Label5" runat="server" Text="Select


Course"></asp:Label>s</td>

<td>

<asp:CheckBox ID="CheckBox1" runat="server" Text="J2SEE" />

<asp:CheckBox ID="CheckBox2" runat="server" Text="J2EE" />

<asp:CheckBox ID="CheckBox3" runat="server" Text="Spring


Framework" />

</td> </tr>

<tr>

<td>

Page | 31
ASP.NET LAB FILE 01113702022

</td>

<td>

<br />

<asp:Button ID="Button1" runat="server" Text="Register" CssClass="btn


btn-primary" OnClick="Button1_Click"/>

</td>

</tr>

</table>

<asp:Label ID="message" runat="server" Font-Size="Medium"


ForeColor="Red"></asp:Label>

</div>

</form>

<table class="auto-style1">

<tr>

<td class="auto-style2"><asp:Label ID="ShowUserNameLabel"


runat="server" ></asp:Label></td>

<td>

<asp:Label ID="ShowUserName" runat="server" ></asp:Label></td>

</tr>

<tr>

<td class="auto-style2"><asp:Label ID="ShowEmailIDLabel" runat="server"


></asp:Label></td>

<td>

<asp:Label ID="ShowEmail" runat="server" ></asp:Label></td>

</tr>

Page | 32
ASP.NET LAB FILE 01113702022

<tr>

<td class="auto-style3"><asp:Label ID="ShowGenderLabel" runat="server"


></asp:Label></td>

<td class="auto-style4">

<asp:Label ID="ShowGender" runat="server" ></asp:Label></td>

</tr>

<tr>

<td class="auto-style2"><asp:Label ID="ShowCourseLabel" runat="server"


></asp:Label></td>

<td>

<asp:Label ID="ShowCourses" runat="server" ></asp:Label></td>

</tr>

</table>

</body>
</html>
1. Handling Submit Request

In code behind file, we are adding a message that trigger only when user
submit the registration form. This file includes the following code.

// WebControls.aspx.cs

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.UI;

using System.Web.UI.WebControls;

Page | 33
ASP.NET LAB FILE 01113702022

namespace WebFormsControlls

public partial class WebControls : System.Web.UI.Page

protected System.Web.UI.HtmlControls.HtmlInputFile File1;

protected System.Web.UI.HtmlControls.HtmlInputButton Submit1;

protected void Page_Load(object sender, EventArgs e)

protected void Button1_Click(object sender, EventArgs e)

message.Text = "Hello " + username.Text + " ! ";

message.Text = message.Text + " <br/> You have successfuly


Registered with the following details.";

ShowUserName.Text = username.Text;

ShowEmail.Text = EmailID.Text;

if (RadioButton1.Checked)

ShowGender.Text = RadioButton1.Text;

else ShowGender.Text = RadioButton2.Text;

var courses = "";

if (CheckBox1.Checked)

{
Page | 34
ASP.NET LAB FILE 01113702022

courses = CheckBox1.Text + " ";

if (CheckBox2.Checked)

courses += CheckBox2.Text + " ";

if (CheckBox3.Checked)

courses += CheckBox3.Text;

ShowCourses.Text = courses;

ShowUserNameLabel.Text = "User Name";

ShowEmailIDLabel.Text = "Email ID";

ShowGenderLabel.Text = "Gender";

ShowCourseLabel.Text = "Courses";

username.Text = "";

EmailID.Text = "";

RadioButton1.Checked = false;

RadioButton2.Checked = false;

CheckBox1.Checked = false;

CheckBox2.Checked = false;

CheckBox3.Checked = false;

Page | 35
ASP.NET LAB FILE 01113702022

}
}

Output 14:

Page | 36
ASP.NET LAB FILE 01113702022

Q15. Explain how to establish a database using in-built sql database and
connect it to ASP.NET web form and show the data of a table created using
Sql in grid view control?

Solution 15:

Introduction

Here, I will explain how to bind the data from the database to Grid View in
ASP.NET.

Step 1:

Create table in the database (SQL Server 2012)

1. Create the database and name it as Login.


2. Add table (here table name: tbllogin)

Page | 37
ASP.NET LAB FILE 01113702022

3. Set primary key to Id column.

Step 2:

-> Insert values into tbllogin table.

Step 3:

Create new project in Visual Studio 2015.


1. Go to File-> New-> Website -> Visual C#-> ASP.NET empty
Website-> Entry Application Name-> OK.
2. Add Web form to the Website.
Project name-> Add-> Add New Item-> Web Form-> write name -
>Add.

Page | 38
ASP.NET LAB FILE 01113702022

 HomePage.aspx (Web form) page is created.

Page | 39
ASP.NET LAB FILE 01113702022

 Click Design Button-> Add Grid View From Toolbox. ToolBox-> Data->
Grid View.

Page | 40
ASP.NET LAB FILE 01113702022

 Right Click on Grid View-> select View Code.

Page | 41
ASP.NET LAB FILE 01113702022

 Add the namespaces, mentioned below, in the code back-end page.

 After the completion of adding the namespaces, you need to write the
code, as shown below.

 Code Explanation:

1. Write Code Inside Page Load Event.(First time Application Run)


2. SqlConnection: is a Part of ADO.NET, used for Physical
Communication between C# Applications and the database.

Parameters in SQLConnection

o Data Source.
Server Name.
o Initial Catalog.
Database Name.
Id and Password: Here, I am using SQL Server
Authentication, so we have to provide the username and
password.

Note:

For Windows Authentication, there is no need to provide


the username and password. Just write: Integrated
Security=SSPI;

Page | 42
ASP.NET LAB FILE 01113702022

3. con.Open()
Open the connection.

4. SqlCommand
This is used to execute SQL statements (insert, delete, and update).
Command object requires Connection Object.

5. cmd.ExecuteReader()
Execute SQL statements.

6. Store Result into SqlDataReader object. rdr object contains the


results.

7. GridView1.DataSource = rdr; //GridView1 is GridView ID.


GridView get Results from rdr object.

8. GridView1.DataBind(); // Bind the Data

9. con.Close(); Close Connection.


Output

Page | 43

You might also like