Asp.net webform interview question and answer and CRUD Operations using ado.net
Asp.net webform interview question and answer.
Some ASP.NET Web Forms interview questions and answers suitable for a candidate with 3 years of experience:
1. What is ASP.NET Web Forms?
- Answer: ASP.NET Web Forms is a web application framework provided by Microsoft. It allows developers to build dynamic websites with a rich user interface. The framework is event-driven and provides a drag-and-drop development model with controls like GridView, TextBox, and Button that abstract the underlying HTML.
2. What is the difference between Web Forms and MVC?
- Answer:
- Web Forms: Event-driven model, with a stateful design (view state) that makes it easier for developers to build pages quickly. The code-behind model ties the UI and logic together.
- MVC: A stateless design following the Model-View-Controller pattern, which separates the concerns of the user interface, application logic, and data. MVC offers more flexibility, better testability, and finer control over HTML output.
3. What is ViewState in ASP.NET?
- Answer: ViewState is a mechanism that allows Web Forms to persist the state of controls between postbacks. It stores the values of controls (like TextBox or DropDownList) in a hidden field in the page. This helps maintain control values across multiple requests but can add overhead and affect performance if the page has a large ViewState.
4. What is the purpose of the Global.asax
file in Web Forms?
- Answer: The
Global.asax
file is used for application-level events in an ASP.NET Web Forms application. It includes methods such asApplication_Start
,Application_End
,Session_Start
, andSession_End
, which are used to manage application-wide resources, handle global exceptions, and initialize data.
5. Explain the lifecycle of a Web Form page.
- Answer: The lifecycle of a Web Form page includes the following stages:
- Page Request: The page is requested from the browser.
- Page Initialization: Controls are initialized, and their properties are set.
- Load: If the request is a postback, the page's controls are populated with the data from the previous request.
- Postback Event Handling: If the request is a postback, the events for the controls (such as Button_Click) are handled.
- Rendering: The page calls the
Render
method for each control, providing the output to the page's HTML. - Unload: Clean up any resources used by the page.
6. What are the different types of controls in ASP.NET Web Forms?
- Answer:
- Server Controls: Controls like
Button
,TextBox
,GridView
,Label
, etc., that are rendered by ASP.NET on the server and interact with the code-behind. - HTML Controls: Standard HTML elements (e.g.,
<input>
,<button>
) used in Web Forms pages. These do not have server-side events but can be used for simple tasks. - User Controls: Custom controls created by combining existing controls into reusable components.
- Server Controls: Controls like
7. What is a GridView control, and how is it used in ASP.NET Web Forms?
- Answer: The
GridView
control is a powerful control used to display and manage data in a tabular format. It supports features like sorting, paging, editing, and deleting rows. The data is typically bound to a data source (like aDataSet
orSqlDataSource
). You can also handle events such asRowEditing
,RowDeleting
, andRowUpdating
for CRUD operations.
8. What are Master Pages in ASP.NET?
- Answer: Master Pages allow you to define a common layout (header, footer, navigation, etc.) for multiple pages in a Web Forms application. Each content page can reference a master page, ensuring consistent look and feel across the site.
9. Explain the difference between Session
and Cookies
in ASP.NET.
- Answer:
- Session: A server-side storage mechanism to store user-specific data across multiple requests. Data is stored on the server and is unique per user.
- Cookies: A client-side storage mechanism to store small amounts of data on the user's browser. Cookies persist across sessions until expired.
10. How does the GridView
control handle paging?
- Answer: The
GridView
control provides aAllowPaging
property that, when set to true, allows pagination. You can define thePageSize
property to control how many records to display per page. The control handles the generation of paging links (such as Next, Previous, and Page numbers) automatically.
11. What is the purpose of the Page_Load
method?
- Answer: The
Page_Load
method is an event handler that is called when the page is loaded into memory. It is used to initialize values, bind data, and perform actions that need to be done once when the page is requested.
12. Explain how you can handle validation in Web Forms.
- Answer: Validation in Web Forms can be done using various validation controls:
- RequiredFieldValidator: Ensures that a control has a value.
- RangeValidator: Ensures that a value is within a specific range.
- RegularExpressionValidator: Validates input based on a regular expression pattern.
- CompareValidator: Compares the values of two controls.
- CustomValidator: Allows custom validation logic to be implemented using C# code.
- ValidationSummary: Displays a summary of validation errors on the page.
13. What is the difference between Server.Transfer
and Response.Redirect
?
- Answer:
- Server.Transfer: This method transfers the request to another page on the server without changing the URL in the browser. It is faster since it does not involve a round trip to the client.
- Response.Redirect: This method sends a request to the client to redirect to a new URL. It causes a round trip to the client and updates the browser's address bar.
14. How do you secure an ASP.NET Web Forms application?
- Answer: Security in Web Forms can be implemented through:
- Authentication: Configuring authentication methods like Forms Authentication, Windows Authentication, or OAuth.
- Authorization: Using role-based access control (RBAC) to restrict access to specific pages or resources.
- HTTPS: Enforcing SSL/TLS to secure data transmission.
- Input Validation: Preventing SQL injection, cross-site scripting (XSS), and cross-site request forgery (CSRF) attacks by validating and sanitizing user input.
- Code Access Security: Limiting access to certain resources or actions based on user permissions.
15. What is the difference between HttpRequest
and HttpResponse
?
- Answer:
- HttpRequest: Represents the HTTP request from the client to the server. It includes information such as the URL, headers, query strings, and form data.
- HttpResponse: Represents the server’s response to the client. It includes the status code, cookies, headers, and the content (HTML, JSON, etc.) that is sent back to the client.
- Read more details on this link state-management-in-asp-net
16. Explain State Management Techniques in ASP.NET ?
- Answer:
- Server Side: Session, application, and Cache. (SAC)
- Client Side: Query String, Hidden field, ViewSate, Cookies, Control State. (QHVCC)
These questions cover a range of fundamental concepts and practical knowledge that a 3-year experienced developer working with ASP.NET Web Forms should be familiar with.
Some links for preparing interviews.
======================================================================
Asp.net webform CRUD Operations using ado.net
Steps to Create a CRUD Application in ASP.NET Web Forms using ADO.NET:
1. Create a new ASP.NET Web Forms Project
- Open Visual Studio.
- Create a new ASP.NET Web Forms project.
- Name the project (e.g.,
EmployeeCRUDApp
).
2. Create an SQL Server Database and Table
CREATE DATABASE EmployeeDB;
GO
USE EmployeeDB;
GO
CREATE TABLE Employees (
EmployeeID INT PRIMARY KEY IDENTITY(1,1),
FirstName NVARCHAR(50),
LastName NVARCHAR(50),
Email NVARCHAR(100),
Salary DECIMAL(18,2)
);
3. Add Connection String in Web.config
In your Web.config
file, add a connection string to your database:
<connectionStrings>
<add name="EmployeeDBConnectionString"
connectionString="Data Source=YOUR_SERVER;Initial Catalog=EmployeeDB;
Integrated
Security=True;" providerName="System.Data.SqlClient" />
</connectionStrings>
Replace YOUR_SERVER
with your SQL Server instance name.
4. Create Data Access Layer (DAL)
Create a class to interact with the database using ADO.NET.
using System;
using System.Data;
using System.Data.SqlClient;
public class EmployeeDAL
{
string cs = System.Configuration.ConfigurationManager.
ConnectionStrings
["EmployeeDBConnectionString"].ConnectionString;
public DataTable SearchEmployees(string name = null, string description = null)
{
DataTable dt = new DataTable();
using (SqlConnection con = new SqlConnection(cs))
{
string query = "SELECT * FROM Products WHERE 1=1";
// Add dynamic conditions
if (!string.IsNullOrEmpty(name))
{
query += " AND Name LIKE @Name";
}
if (!string.IsNullOrEmpty(description))
{
query += " AND Description LIKE @Description";
}
using (SqlCommand cmd = new SqlCommand(query, con))
{
// Add parameters dynamically
if (!string.IsNullOrEmpty(name))
{
cmd.Parameters.AddWithValue("@Name", $"%{name}%");
}
if (!string.IsNullOrEmpty(description))
{
cmd.Parameters.AddWithValue("@Description", $"%{description}%");
}
using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
{
sda.Fill(dt);
}
}
}
return dt;
}
public DataSet GetAllEmployees()
{
using (SqlConnection con = new SqlConnection(cs))
{
using (SqlCommand cmd = new SqlCommand("SELECT * FROM Employees", con))
{
using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
{
//DataTable work on only multiple tables but DataSet is 1 or more table also DataSet ds = new DataSet();
sda.Fill(ds);
return ds;
}
}
}
}
public void InsertEmployee(string firstName, string lastName, string email,
decimal salary)
{
using (SqlConnection con = new SqlConnection(cs))
{
string query = "INSERT INTO Employees(FirstName, LastName, Email, Salary)
VALUES (@FirstName, @LastName, @Email, @Salary)"; using (SqlCommand cmd = new SqlCommand(query, con))
{
cmd.Parameters.AddWithValue("@FirstName", firstName);
cmd.Parameters.AddWithValue("@LastName", lastName);
cmd.Parameters.AddWithValue("@Email", email);
cmd.Parameters.AddWithValue("@Salary", salary);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
}
public void UpdateEmployee(int employeeId, string firstName, string lastName,
string email, decimal salary) {
using (SqlConnection con = new SqlConnection(cs))
{
string query = "UPDATE Employees SET FirstName=@FirstName, LastName=@LastName,
Email=@Email, Salary=@Salary WHERE EmployeeID=@EmployeeID";
using (SqlCommand cmd = new SqlCommand(query, con))
{
cmd.Parameters.AddWithValue("@EmployeeID", employeeId);
cmd.Parameters.AddWithValue("@FirstName", firstName);
cmd.Parameters.AddWithValue("@LastName", lastName);
cmd.Parameters.AddWithValue("@Email", email);
cmd.Parameters.AddWithValue("@Salary", salary);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
}
public void DeleteEmployee(int employeeId)
{
using (SqlConnection con = new SqlConnection(cs))
{
string query = "DELETE FROM Employees WHERE EmployeeID=@EmployeeID";
using (SqlCommand cmd = new SqlCommand(query, con))
{
cmd.Parameters.AddWithValue("@EmployeeID", employeeId);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
}
}
5. Create the ASPX Page with a GridView
In the Default.aspx
page, create a GridView
and form elements for employee data input.
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
OnRowEditing = "GridView1_RowEditing" OnRowCancelingEdit="GridView1_RowCancelingEdit"OnRowUpdating ="GridView1_RowUpdating" OnRowDeleting="GridView1_RowDeleting"> <Columns>
<asp:BoundField DataField="EmployeeID" HeaderText="Employee ID"
ReadOnly="True"/>
<asp:BoundField DataField="FirstName" HeaderText="First Name" />
<asp:BoundField DataField="LastName" HeaderText="Last Name" />
<asp:BoundField DataField="Email" HeaderText="Email" />
<asp:BoundField DataField="Salary" HeaderText="Salary"
DataFormatString="{0:C}"/>
<asp:CommandField ShowEditButton="True" ShowDeleteButton="True" />
</Columns>
</asp:GridView>
<td>
<asp:TextBox ID="txtSearch" runat="server" placeholder="Enter text to search"></asp:TextBox>
<asp:Button ID="btnSearch" runat="server" Text="Search" OnClick="btnSearch_Click" /><br />
<asp:Button ID="btnExport" runat="server" Text="Report" OnClick="btnExport_Click" Width="114px" />
</td>
<h3>Add Employee</h3>
<asp:TextBox ID="txtFirstName" runat="server" Placeholder="First Name"></asp:TextBox>
<br />
<asp:TextBox ID="txtLastName" runat="server" Placeholder="Last Name"></asp:TextBox>
<br />
<asp:TextBox ID="txtEmail" runat="server" Placeholder="Email"></asp:TextBox>
<br />
<asp:TextBox ID="txtSalary" runat="server" Placeholder="Salary"></asp:TextBox>
<br />
<asp:Button ID="btnAdd" runat="server" Text="Add Employee" OnClick="btnAdd_Click" />
6. Code-behind for the CRUD Operations (Default.aspx.cs
)
using System;
using System.Data;
public partial class _Default : System.Web.UI.Page
{
EmployeeDAL employeeDAL = new EmployeeDAL();
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
LoadEmployees();
}
}
private void LoadEmployees()
{
GridView1.DataSource = employeeDAL.GetAllEmployees();
GridView1.DataBind();
}
protected void btnAdd_Click(object sender, EventArgs e)
{
string firstName = txtFirstName.Text;
string lastName = txtLastName.Text;
string email = txtEmail.Text;
decimal salary = decimal.Parse(txtSalary.Text);
employeeDAL.InsertEmployee(firstName, lastName, email, salary);
LoadEmployees();
}
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
LoadEmployees();
}
protected void GridView1_RowCancelingEdit(object sender,
GridViewCancelEditEventArgs e)
{
GridView1.EditIndex = -1;
LoadEmployees();
}
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
int employeeId = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Value);
string firstName = (GridView1.Rows[e.RowIndex].FindControl("txtFirstName")
as TextBox).Text; string lastName = (GridView1.Rows[e.RowIndex].FindControl("txtLastName")
as TextBox).Text;
string email = (GridView1.Rows[e.RowIndex].FindControl("txtEmail")
as TextBox).Text;
decimal salary = decimal.Parse((GridView1.Rows[e.RowIndex]
.FindControl("txtSalary")as TextBox).Text);
employeeDAL.UpdateEmployee(employeeId, firstName, lastName, email, salary);
GridView1.EditIndex = -1;
LoadEmployees();
}
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
int employeeId = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Value);
employeeDAL.DeleteEmployee(employeeId);
LoadEmployees();
}
protected void btnSearch_Click(object sender, EventArgs e)
{
// Get search query from the TextBox
string searchQuery = txtSearch.Text.Trim();
// Call the DAL method to perform the search
EmployeeDAL dal = new EmployeeDAL();
DataTable dt = dal.SearchEmployees(name: searchQuery, description: searchQuery);
// Bind the result to the GridView
GridView1.DataSource = dt;
GridView1.DataBind();
}
protected void btnExport_Click(object sender, EventArgs e)
{
// Temporarily disable event validation for export
//Page.EnableEventValidation = false;
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment;filename=GridViewData.xls");
Response.Charset = "";
Response.ContentType = "application/vnd.ms-excel";
using (System.IO.StringWriter sw = new System.IO.StringWriter())
{
using (HtmlTextWriter hw = new HtmlTextWriter(sw))
{
// Render GridView
GridView1.AllowPaging = false;
bindGrid(); // Ensure all data is loaded
GridView1.RenderControl(hw);
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();
}
}
// Re-enable event validation
Page.EnableEventValidation = true;
}
// Override for GridView rendering
public override void VerifyRenderingInServerForm(Control control)
{
// Required for exporting to work
}
}
Web.config
<configuration>
<system.web>
<pages enableEventValidation="false" /> <--Export Excel krte time error ata h-->
</system.web>
</configuration>
7. Run the Application
- Build and run the project.
- You should be able to add, edit, update, and delete employees from the GridView.
This is a basic CRUD implementation using ADO.NET in ASP.NET Web Forms. You can extend this to include more features like validation, pagination, and error handling.
How to import excel file data in asp.net webform grid and also Crud operation in excel
No comments: