ASP.NET Web Development
Q1. Write an ASP.NET Program to print a Message on web form.
Problem Explanation
This program demonstrates how to create a simple ASP.NET web form with a button control. When the button is clicked, it displays a message in a label control on the web form.
Step-By-Step Instructions
- Open Visual Studio
- Create a new ASP.NET Web Application project
- Design the web form with Button and Label controls
- Write code inside the Button Click event handler
- Set the Label Text property to display the message
- Build and run the application
Code
using System;
public partial class que1 : System.Web.UI.Page
{
protected void Button1_Click(object sender, EventArgs e)
{
Label2.Text = "Hello World!!!";
Label2.Visible = true;
}
}
Output
Key Concept
This program demonstrates ASP.NET event handling. When a user clicks the button control, the Click event is triggered, executing the Button1_Click event handler method. The Label control is used to display dynamic content on the web form.
Q2. Write an ASP.NET Program to set a link for new Page.
Problem Explanation
This program shows how to navigate between pages in ASP.NET using hyperlinks. A HyperLink control is used to redirect the user to another web page when clicked.
Step-By-Step Instructions
- Create an ASP.NET web application project in Visual Studio
- Add a HyperLink control to the web form
- Set the NavigateUrl property to point to another page
- Set the Text property to display link text
- Build and run the application
Code
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html>
<html>
<head>
<title>Link to New Page</title>
</head>
<body>
<form id="form1" runat="server">
<asp:HyperLink ID="HyperLink1" runat="server" NavigateUrl="NewPage.aspx">
Click here to go to New Page
</asp:HyperLink>
</form>
</body>
</html>
Output
Key Concept
The HyperLink control in ASP.NET provides a simple way to navigate between pages. The NavigateUrl property specifies the target page URL, and clicking the link redirects the user to that page. This is a fundamental navigation mechanism in web applications.
Q3. Write an ASP.NET Program to demonstrate different common Controls.
Problem Explanation
This program demonstrates various common ASP.NET controls like TextBox, Button, Label, CheckBox, RadioButton, and DropDownList. Each control serves a different purpose in web form development.
Step-By-Step Instructions
- Create a new ASP.NET Web Form
- Drag and drop various controls on the form
- Set properties for each control (ID, Text, etc.)
- Add event handlers to respond to user actions
- Run the application and interact with controls
Code
<%@ Page Language="C#" %>
<!DOCTYPE html>
<html>
<head>
<title>Common Controls</title>
</head>
<body>
<form id="form1" runat="server">
<h2>ASP.NET Common Controls</h2>
<div>
<label>TextBox:</label>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
</div>
<div>
<label>RadioButton:</label>
<asp:RadioButton ID="RadioButton1" runat="server" Text="Option 1"/>
<asp:RadioButton ID="RadioButton2" runat="server" Text="Option 2"/>
</div>
<div>
<label>CheckBox:</label>
<asp:CheckBox ID="CheckBox1" runat="server" Text="Check me"/>
</div>
<div>
<label>DropDownList:</label>
<asp:DropDownList ID="DropDownList1" runat="server">
<asp:ListItem Text="Select..."></asp:ListItem>
<asp:ListItem Text="Item 1"></asp:ListItem>
<asp:ListItem Text="Item 2"></asp:ListItem>
</asp:DropDownList>
</div>
<div>
<asp:Button ID="Button1" runat="server" Text="Submit"/>
</div>
<div>
<asp:Label ID="Label1" runat="server"></asp:Label>
</div>
</form>
</body>
</html>
Output
Key Concept
ASP.NET provides a variety of server controls for building interactive web forms. Each control has specific properties and events that allow developers to collect user input and provide dynamic responses. Understanding these controls is essential for web development.
Q4. Write an ASP.NET program using while or for loop to print sum of first 100 ODD and Even Numbers.
Problem Explanation
This program calculates and displays the sum of the first 100 odd numbers and the first 100 even numbers. Loops are used to iterate through numbers and accumulate their values.
Step-By-Step Instructions
- Create variables to store sum of odd and even numbers
- Use a for or while loop from 1 to 200
- Check if number is odd or even using modulo operator
- Add to respective sum variables
- Display results in label controls
Code
using System;
public partial class SumCalc : System.Web.UI.Page
{
protected void Button1_Click(object sender, EventArgs e)
{
int oddSum = 0, evenSum = 0;
int oddCount = 0, evenCount = 0;
for (int i = 1; i <= 200; i++)
{
if (i % 2 == 0)
{
evenSum += i;
evenCount++;
if (evenCount == 100) break;
}
else
{
oddSum += i;
oddCount++;
}
}
Label1.Text = "Sum of first 100 odd numbers: " + oddSum;
Label2.Text = "Sum of first 100 even numbers: " + evenSum;
}
}
Output
Key Concept
This program demonstrates loop control structures in ASP.NET. The modulo operator (%) is used to determine if a number is even or odd. Even numbers leave remainder 0 when divided by 2, while odd numbers leave remainder 1.
Q5. Write an ASP.NET Program to add the value of Text Box in to Dropdown List and List box Controls.
Problem Explanation
This program demonstrates how to dynamically add items to DropDownList and ListBox controls. User enters text in a TextBox, clicks a button, and the text is added to both controls.
Step-By-Step Instructions
- Create a TextBox for user input
- Create a Button to add items
- Create DropDownList and ListBox controls
- Write code to add TextBox value to both controls
- Clear TextBox after adding
Code
using System;
public partial class AddItems : System.Web.UI.Page
{
protected void ButtonAdd_Click(object sender, EventArgs e)
{
if (TextBox1.Text != "")
{
ListItem item = new ListItem(TextBox1.Text);
DropDownList1.Items.Add(item);
ListBox1.Items.Add(item);
TextBox1.Text = "";
TextBox1.Focus();
}
}
}
Output
Key Concept
This demonstrates dynamic list manipulation in ASP.NET. Using the Items.Add() method, new ListItem objects can be added to select controls at runtime. This is useful for creating dynamic forms that respond to user input.
Q6. Write an ASP.NET Program to Delete Items from Dropdown list and List box.
Problem Explanation
This program shows how to remove selected items from DropDownList and ListBox controls. The user selects an item and clicks a delete button to remove it from both controls.
Step-By-Step Instructions
- Create DropDownList and ListBox with items
- Add a Delete button
- Get the selected item index
- Remove item using Items.RemoveAt()
- Handle cases where no item is selected
Code
using System;
public partial class DeleteItems : System.Web.UI.Page
{
protected void ButtonDelete_Click(object sender, EventArgs e)
{
if (DropDownList1.SelectedIndex > -1)
{
int index = DropDownList1.SelectedIndex;
DropDownList1.Items.RemoveAt(index);
ListBox1.Items.RemoveAt(index);
}
}
}
Output
Key Concept
The Items.RemoveAt() method removes an item at a specific index from select controls. SelectedIndex property returns the index of the selected item (-1 if no selection), which is used to locate and remove the correct item.
Q7. Write an ASP.NET Program to set Image on Image Control according to selection of image name from dropdown list.
Problem Explanation
This program demonstrates how to dynamically change the image displayed in an Image control based on the user's selection from a dropdown list. This is useful for image galleries and product previews.
Step-By-Step Instructions
- Create a DropDownList with image names
- Create an Image control
- Handle the DropDownList SelectedIndexChanged event
- Set the Image URL based on selection
- Store images in a folder within the application
Code
using System;
public partial class ImageSelector : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DropDownList1.Items.Add("Select Image");
DropDownList1.Items.Add("Image1");
DropDownList1.Items.Add("Image2");
DropDownList1.Items.Add("Image3");
}
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
string selected = DropDownList1.SelectedItem.Text;
if (selected != "Select Image")
{
Image1.ImageUrl = "~/Images/" + selected + ".jpg";
}
}
}
Output
Key Concept
This program demonstrates the SelectedIndexChanged event and dynamic URL assignment. The Image control's ImageUrl property is set based on the dropdown selection, enabling dynamic content display without page refresh.
Q8. Write an ASP.NET Program to demonstrate use of Master Page.
Problem Explanation
Master Pages provide a template for consistent layout across multiple pages in a web application. They define common header, navigation, and footer elements that are inherited by content pages.
Step-By-Step Instructions
- Create a Master Page (.master) file
- Define common layout with header, navigation, footer
- Add ContentPlaceHolder controls for content
- Create content pages that use the Master Page
- Set MasterPageFile in page directive
Code
<%@ Master Language="C#" %>
<!DOCTYPE html>
<html>
<head>
<title>Master Page</title>
<style>
body { font-family: Arial; margin: 0; }
.header { background: #333; color: white; padding: 20px; }
.content { padding: 20px; }
.footer { background: #333; color: white; padding: 20px; text-align: center; }
</style>
</head>
<body>
<div class="header">
<h1>My Website</h1>
</div>
<div class="content">
<asp:ContentPlaceHolder ID="ContentPlaceHolder1" runat="server">
</asp:ContentPlaceHolder>
</div>
<div class="footer">
<p>© 2024 All Rights Reserved</p>
</div>
</body>
</html>
Content Page
<%@ Page Language="C#" MasterPageFile="~/Site.master" %>
<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<h2>Welcome to Home Page</h2>
<p>This is content specific to this page.</p>
</asp:Content>
Output
Key Concept
Master Pages implement the Template Method design pattern. ContentPlaceHolder controls define areas where page-specific content can be inserted. This promotes code reuse and maintains visual consistency across the application.
Q9. Program to demonstrate ADO.Net connected architecture.
Problem Explanation
Connected architecture maintains an open connection to the database throughout the operation. This program demonstrates retrieving data using SqlConnection, SqlCommand, and SqlDataReader objects.
Step-By-Step Instructions
- Create a connection string to the database
- Open SqlConnection to database
- Create SqlCommand with SQL query
- Execute command and use SqlDataReader to read results
- Close connection after reading
Code
using System;
using System.Data;
using System.Data.SqlClient;
public partial class ConnectedDB : System.Web.UI.Page
{
protected void Button1_Click(object sender, EventArgs e)
{
string connStr = "Server=localhost;Database=MyDB;User Id=sa;Password=pass;";
SqlConnection conn = new SqlConnection(connStr);
try
{
conn.Open();
string query = "SELECT * FROM Students";
SqlCommand cmd = new SqlCommand(query, conn);
SqlDataReader reader = cmd.ExecuteReader();
string result = "";
while (reader.Read())
{
result += reader[0] + " - " + reader[1] + "
";
}
Label1.Text = result;
reader.Close();
}
catch (Exception ex)
{
Label1.Text = "Error: " + ex.Message;
}
finally
{
conn.Close();
}
}
}
Output
Key Concept
Connected architecture maintains an active connection to the database. SqlDataReader provides forward-only, read-only access to data, making it efficient for displaying large datasets. Always close connections in finally blocks to prevent resource leaks.
Q10. Program to demonstrate ADO.Net disconnected architecture.
Problem Explanation
Disconnected architecture retrieves data into memory and closes the connection. This program uses DataSet to store data locally, allowing manipulation without maintaining a live database connection.
Step-By-Step Instructions
- Create connection string and SqlConnection
- Create SqlDataAdapter to fill DataSet
- Fill DataSet with data from database
- Close connection immediately
- Bind DataSet to controls for display
Code
using System;
using System.Data;
using System.Data.SqlClient;
public partial class DisconnectedDB : System.Web.UI.Page
{
protected void Button1_Click(object sender, EventArgs e)
{
string connStr = "Server=localhost;Database=MyDB;User Id=sa;Password=pass;";
SqlConnection conn = new SqlConnection(connStr);
try
{
SqlDataAdapter adapter = new SqlDataAdapter("SELECT * FROM Students", conn);
DataSet ds = new DataSet();
adapter.Fill(ds);
// Connection is closed automatically after Fill()
GridView1.DataSource = ds.Tables[0];
GridView1.DataBind();
}
catch (Exception ex)
{
Label1.Text = "Error: " + ex.Message;
}
}
}
Output
Key Concept
Disconnected architecture is more scalable for web applications. DataSet acts as an in-memory database, allowing data manipulation and binding without maintaining a live connection. This reduces database load and improves performance.
Q11. Program to demonstrate client side state management.
Problem Explanation
Client-side state management stores information on the client's browser rather than the server. This program demonstrates ViewState, hidden fields, and cookies for maintaining state between page postbacks.
Step-By-Step Instructions
- Use ViewState to store page-specific data
- Use hidden fields for form data
- Use cookies for persistent client storage
- Retrieve stored values on postback
- Display stored values
Code
using System;
public partial class StateManagement : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
// Store in ViewState
ViewState["Count"] = 0;
}
}
protected void ButtonIncrement_Click(object sender, EventArgs e)
{
int count = (int)ViewState["Count"];
count++;
ViewState["Count"] = count;
Label1.Text = "Count: " + count;
// Store in Cookie
HttpCookie cookie = new HttpCookie("Count", count.ToString());
cookie.Expires = DateTime.Now.AddDays(1);
Response.Cookies.Add(cookie);
}
protected void PageLoad_Load(object sender, EventArgs e)
{
// Retrieve from Cookie
if (Request.Cookies["Count"] != null)
{
Label2.Text = "Cookie Value: " + Request.Cookies["Count"].Value;
}
}
}
Output
Key Concept
ViewState stores page-specific data in a hidden field and is encoded for security. Cookies store data on the client browser and can persist across page visits. Both are client-side techniques unlike session which is server-side.