VNSGU BCA Sem 6 ASP.NET Code Snippets 2026 – ADO.NET, Validation, State Management, Web Forms C# Complete Guide
Ankit Singh
1 July 2026· BCA Study Guides

📅 Last Updated: 1 July 2026 | Covers Web.config, INSERT/SELECT/UPDATE/DELETE ADO.NET, Connected vs Disconnected (SqlDataReader vs DataSet), all 6 Validation Controls, Session/ViewState/Cookies state management, Login form example, Page Lifecycle, and 10 exam FAQs. Updated for VNSGU 2026 exam pattern.
ASP.NET with C# is the core practical and theory subject in Semester 6 of BCA at Veer Narmad South Gujarat University (VNSGU). Whether you are preparing for the theory paper, the practical exam, or the external viva, you need to write accurate C# code — parameterized queries, event handlers, state management, and database operations. This guide compiles every important code snippet, concept explanation, and comparison table you need to score maximum marks.
📑 Table of Contents
- 👉 Exam Pattern & Important Topics
- 👉 ASP.NET Page Lifecycle
- 👉 1. Web.config Connection String
- 👉 2. INSERT Record (Parameterized)
- 👉 3. SELECT & GridView Binding (Disconnected)
- 👉 4. SqlDataReader – Connected Architecture
- 👉 5. UPDATE & DELETE Records
- 👉 6. State Management (Session, ViewState, Cookies)
- 👉 7. Validation Controls (All 6 Types)
- 👉 8. Login Form with Session
- 👉 Connected vs Disconnected – Comparison Table
- 👉 FAQs
📊 VNSGU BCA Sem 6 ASP.NET – Exam Pattern & Important Topics
| Topic | Theory Marks | Practical / Viva | Frequency |
|---|---|---|---|
| ADO.NET – INSERT/SELECT ⭐ | 10–15 marks | Core practical task | Every year ✅ |
| State Management ⭐ | 10 marks | Common viva Q | Every year ✅ |
| Connected vs Disconnected | 5–10 marks | Viva concept | Every year ✅ |
| Validation Controls | 5–10 marks | Practical add-on | Most years ✅ |
| Page Lifecycle / IsPostBack | 5 marks | Viva question | Most years ✅ |
| Web Forms Controls (TextBox, DropDown, GridView) | 5 marks | Core practical task | Every year ✅ |
⚙️ ASP.NET Page Lifecycle – Must Know for Viva
The VNSGU external examiner always asks: "What happens when a user clicks a button in ASP.NET?" Memorize this sequence:
| Stage | Event / Method | What Happens |
|---|---|---|
| 1. Page Request | HTTP Request received | Server receives request from browser |
| 2. Start | IsPostBack set | Page properties like Request, Response, IsPostBack initialized |
| 3. Initialization | Page_Init | Controls initialized, UniqueIDs assigned |
| 4. Load ⭐ | Page_Load | Use if(!IsPostBack) here for one-time initialization |
| 5. Validation | Validate() | All validation controls run |
| 6. Event Handling ⭐ | btnSubmit_Click | Button click or other event handler executes |
| 7. Rendering | Render() | HTML sent to browser |
| 8. Unload | Page_Unload | Cleanup — close connections if not using 'using' |
1. 🗄️ Web.config – Connection String Setup
Every ASP.NET application that connects to SQL Server must configure the connection string in Web.config. Never hardcode connection strings in C# code files.
<configuration>
<connectionStrings>
<add name="MyDbConn"
connectionString="Data Source=.\SQLEXPRESS;Initial Catalog=VnsguBcaDb;Integrated Security=True;"
providerName="System.Data.SqlClient" />
</connectionStrings>
</configuration>
Reading in C# code-behind:
using System.Configuration; string connStr = ConfigurationManager.ConnectionStrings["MyDbConn"].ConnectionString;
2. ✏️ INSERT Record – Parameterized Query (ADO.NET)
This is the most commonly asked 10-mark practical question. Always use parameterized queries — the external examiner checks for this specifically to prevent SQL Injection.
using System;
using System.Data.SqlClient;
using System.Configuration;
protected void btnSubmit_Click(object sender, EventArgs e)
{
string connStr = ConfigurationManager.ConnectionStrings["MyDbConn"].ConnectionString;
using (SqlConnection conn = new SqlConnection(connStr))
{
// Parameterized query — prevents SQL Injection ✅
string query = "INSERT INTO Students (SPID, StudentName, Class) " +
"VALUES (@spid, @name, @class)";
using (SqlCommand cmd = new SqlCommand(query, conn))
{
cmd.Parameters.AddWithValue("@spid", txtSpid.Text.Trim());
cmd.Parameters.AddWithValue("@name", txtName.Text.Trim());
cmd.Parameters.AddWithValue("@class", ddlClass.SelectedValue);
try
{
conn.Open();
int rows = cmd.ExecuteNonQuery(); // Returns rows affected
if (rows > 0)
{
lblStatus.Text = "Record inserted successfully!";
lblStatus.ForeColor = System.Drawing.Color.Green;
}
}
catch (Exception ex)
{
lblStatus.Text = "Error: " + ex.Message;
lblStatus.ForeColor = System.Drawing.Color.Red;
}
}
}
}
🎓 Viva Tip: ExecuteNonQuery() is used for INSERT, UPDATE, and DELETE. It returns the number of rows affected. ExecuteReader() is for SELECT. ExecuteScalar() is for single-value results like COUNT.
3. 📋 SELECT & Bind to GridView – Disconnected Architecture (DataSet)
The Disconnected model uses SqlDataAdapter to fetch data into a DataTable, then closes the connection. The data lives in memory and can be bound to a GridView.
using System;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
protected void Page_Load(object sender, EventArgs e)
{
// Only bind on first load — not on every postback
if (!IsPostBack)
{
BindStudentGrid();
}
}
private void BindStudentGrid()
{
string connStr = ConfigurationManager.ConnectionStrings["MyDbConn"].ConnectionString;
using (SqlConnection conn = new SqlConnection(connStr))
{
string query = "SELECT SPID, StudentName, Class FROM Students ORDER BY SPID";
using (SqlDataAdapter da = new SqlDataAdapter(query, conn))
{
DataTable dt = new DataTable();
da.Fill(dt); // Connection opens and closes automatically
gvStudents.DataSource = dt;
gvStudents.DataBind();
lblCount.Text = "Total Records: " + dt.Rows.Count;
}
}
}
4. 📖 SqlDataReader – Connected Architecture
The Connected model keeps the connection open and reads rows one at a time using SqlDataReader. It is faster for read-only, single-pass operations but requires the connection to remain open.
using System;
using System.Data.SqlClient;
using System.Configuration;
using System.Text;
protected void btnLoad_Click(object sender, EventArgs e)
{
string connStr = ConfigurationManager.ConnectionStrings["MyDbConn"].ConnectionString;
StringBuilder sb = new StringBuilder();
using (SqlConnection conn = new SqlConnection(connStr))
{
string query = "SELECT SPID, StudentName FROM Students WHERE Class = @class";
using (SqlCommand cmd = new SqlCommand(query, conn))
{
cmd.Parameters.AddWithValue("@class", ddlClass.SelectedValue);
conn.Open(); // Connection must stay open while reader is active
SqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read()) // Forward-only, read-only
{
sb.AppendLine(rdr["SPID"].ToString() + " - " +
rdr["StudentName"].ToString());
}
rdr.Close();
}
}
lblResult.Text = sb.ToString();
}
5. 🔄 UPDATE & DELETE Records
UPDATE:
protected void btnUpdate_Click(object sender, EventArgs e)
{
string connStr = ConfigurationManager.ConnectionStrings["MyDbConn"].ConnectionString;
using (SqlConnection conn = new SqlConnection(connStr))
{
string query = "UPDATE Students SET StudentName = @name, Class = @class " +
"WHERE SPID = @spid";
using (SqlCommand cmd = new SqlCommand(query, conn))
{
cmd.Parameters.AddWithValue("@name", txtName.Text.Trim());
cmd.Parameters.AddWithValue("@class", ddlClass.SelectedValue);
cmd.Parameters.AddWithValue("@spid", txtSpid.Text.Trim());
conn.Open();
int rows = cmd.ExecuteNonQuery();
lblStatus.Text = rows > 0 ? "Record updated!" : "No record found.";
}
}
}
DELETE:
protected void btnDelete_Click(object sender, EventArgs e)
{
string connStr = ConfigurationManager.ConnectionStrings["MyDbConn"].ConnectionString;
using (SqlConnection conn = new SqlConnection(connStr))
{
string query = "DELETE FROM Students WHERE SPID = @spid";
using (SqlCommand cmd = new SqlCommand(query, conn))
{
cmd.Parameters.AddWithValue("@spid", txtSpid.Text.Trim());
conn.Open();
int rows = cmd.ExecuteNonQuery();
lblStatus.Text = rows > 0 ? "Record deleted!" : "No record found.";
}
}
BindStudentGrid(); // Refresh grid after delete
}
6. 🗂️ State Management – Session, ViewState & Cookies
HTTP is a stateless protocol — each request is independent. ASP.NET provides multiple mechanisms to persist data between requests:
Session State (Server-Side) – Most Common in VNSGU Exams:
// ── STORING a value in Session ──
Session["UserSPID"] = txtSpid.Text;
Session["Username"] = txtName.Text;
Session["UserRole"] = "Student";
// ── READING from Session (always null-check first) ──
if (Session["Username"] != null)
{
lblWelcome.Text = "Welcome, " + Session["Username"].ToString();
}
else
{
Response.Redirect("Login.aspx"); // Force re-login
}
// ── CLEARING Session on Logout ──
Session.Clear(); // Removes all session variables
Session.Abandon(); // Destroys the session entirely
Response.Redirect("Login.aspx");
ViewState (Client-Side, Page-Level):
// Store a value in ViewState
ViewState["Counter"] = 0;
// Read from ViewState
if (ViewState["Counter"] != null)
{
int count = (int)ViewState["Counter"];
count++;
ViewState["Counter"] = count;
lblCount.Text = "Count: " + count;
}
Cookies (Client-Side, Persistent):
// Creating a Cookie
HttpCookie myCookie = new HttpCookie("UserPref");
myCookie["Theme"] = "Dark";
myCookie.Expires = DateTime.Now.AddDays(30); // Persists 30 days
Response.Cookies.Add(myCookie);
// Reading a Cookie
if (Request.Cookies["UserPref"] != null)
{
string theme = Request.Cookies["UserPref"]["Theme"];
lblTheme.Text = "Theme: " + theme;
}
// Deleting a Cookie (set past expiry)
if (Request.Cookies["UserPref"] != null)
{
HttpCookie del = new HttpCookie("UserPref");
del.Expires = DateTime.Now.AddDays(-1);
Response.Cookies.Add(del);
}
State Management Comparison Table:
| Feature | Session | ViewState | Cookies |
|---|---|---|---|
| Storage Location | Server memory | Client (hidden field) | Client browser |
| Scope | Across pages | Same page only | Across pages + sessions |
| Persistence | Until timeout/abandon | Until browser closes | Until Expires date |
| Security | High (server-side) | Medium (encoded) | Low (client exposed) |
| Best Use Case | Login, user data | Form data, counters | Preferences, tokens |
7. ✅ Validation Controls – All 6 Types
Validation controls ensure user input is correct before processing. They work both client-side (JavaScript) and server-side (C#). All use ControlToValidate to link to the input field.
<asp:RequiredFieldValidator ID="rfvName" runat="server"
ControlToValidate="txtName"
ErrorMessage="Name is required."
ForeColor="Red" />
<asp:RangeValidator ID="rvAge" runat="server"
ControlToValidate="txtAge"
MinimumValue="18" MaximumValue="60"
Type="Integer"
ErrorMessage="Age must be between 18 and 60."
ForeColor="Red" />
<asp:CompareValidator ID="cvPassword" runat="server"
ControlToValidate="txtConfirmPass"
ControlToCompare="txtPassword"
ErrorMessage="Passwords do not match."
ForeColor="Red" />
<asp:RegularExpressionValidator ID="revEmail" runat="server"
ControlToValidate="txtEmail"
ValidationExpression="\w+@\w+\.\w+"
ErrorMessage="Enter a valid email address."
ForeColor="Red" />
<asp:CustomValidator ID="cvSPID" runat="server"
ControlToValidate="txtSpid"
OnServerValidate="ValidateSPID"
ErrorMessage="SPID must start with S."
ForeColor="Red" />
// Code-behind:
protected void ValidateSPID(object source, ServerValidateEventArgs args)
{
args.IsValid = args.Value.StartsWith("S");
}
<asp:ValidationSummary ID="vs1" runat="server"
HeaderText="Please fix the following errors:"
DisplayMode="BulletList"
ForeColor="Red" />
8. 🔐 Complete Login Form Example (with Session)
This is a complete, exam-ready login form that validates credentials against the database and stores user data in Session:
using System;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
protected void btnLogin_Click(object sender, EventArgs e)
{
string connStr = ConfigurationManager.ConnectionStrings["MyDbConn"].ConnectionString;
using (SqlConnection conn = new SqlConnection(connStr))
{
// Use parameterized query — never concatenate passwords!
string query = "SELECT SPID, StudentName FROM Students " +
"WHERE SPID = @spid AND Password = @pwd";
using (SqlCommand cmd = new SqlCommand(query, conn))
{
cmd.Parameters.AddWithValue("@spid", txtSpid.Text.Trim());
cmd.Parameters.AddWithValue("@pwd", txtPassword.Text);
conn.Open();
SqlDataReader rdr = cmd.ExecuteReader();
if (rdr.Read()) // If a matching row is found
{
// Store user data in Session
Session["UserSPID"] = rdr["SPID"].ToString();
Session["Username"] = rdr["StudentName"].ToString();
Session["IsLoggedIn"] = true;
Response.Redirect("Dashboard.aspx");
}
else
{
lblError.Text = "Invalid SPID or Password.";
lblError.ForeColor = System.Drawing.Color.Red;
}
}
}
}
⚡ Connected vs Disconnected Architecture – Comparison Table
| Feature | Connected (SqlDataReader) | Disconnected (DataSet/DataAdapter) |
|---|---|---|
| Connection | Open while reading data | Closed after data is fetched |
| Key Class | SqlDataReader | SqlDataAdapter + DataSet/DataTable |
| Read Direction | Forward-only | Any direction, filterable |
| Data Modification | Read-only | Can modify in-memory data |
| Performance | Faster (streams data) | Slightly slower (caches all data) |
| Best For | Large read-only result sets | GridView binding, sorting, filtering |
| XML Support | No | Yes (DataSet.WriteXml) |
❓ Frequently Asked Questions
if (!IsPostBack) in Page_Load to ensure GridView binding and dropdown population only happen once — not on every button click.
if (!IsPostBack). Every button click triggers a postback which re-runs Page_Load and re-binds the grid with fresh data. Wrap your grid binding in if (!IsPostBack) { BindStudentGrid(); }.
📌 Related BCA Study Resources
- 📄 VNSGU BCA Previous Year Papers – All Semesters Free Download
- 📊 BCA Sem 4 Java Important Questions – VNSGU 2026 Guide
- 🧱 BCA Sem 3 Data Structures – Important Questions & Algorithms
- 🤖 Study Buddy AI – Ask Any ASP.NET Coding Question
- 💻 CoderMain – C# & .NET Coding Resources
Get All VNSGU BCA Sem 6 Papers
Practice actual past exam questions to understand exactly which program types, database operations, and theory concepts the VNSGU examiner focuses on.
About the Author
Ankit Singh is a BCA graduate from VNSGU and founder of QuestionBanker. He analyzed VNSGU BCA Sem 6 past papers to identify the most frequently asked ASP.NET code types, wrote production-tested code snippets for this guide, and helps BCA students score full marks in both theory and practical exams.
📧 ankit@questionbanker.in | More about me
Last updated: 1 July 2026 | Based on VNSGU BCA Sem 6 ASP.NET syllabus and past paper analysis. Code snippets tested with ASP.NET Web Forms 4.x and SQL Server.
Always verify with your current official VNSGU syllabus. Practical program requirements may vary by batch and external examiner.
Keep reading more exam guides
All Blog Posts