Back to Blog
BCAASP.NETVNSGUCode SnippetsADO.NETC#Sem 62026

VNSGU BCA Sem 6 ASP.NET Code Snippets 2026 – ADO.NET, Validation, State Management, Web Forms C# Complete Guide

A

Ankit Singh

1 July 2026· BCA Study Guides

VNSGU BCA Sem 6 ASP.NET Code Snippets 2026 – ADO.NET, Validation, State Management, Web Forms C# Complete Guide

📅 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.

📊 VNSGU BCA Sem 6 ASP.NET – Exam Pattern & Important Topics

Topic Theory Marks Practical / Viva Frequency
ADO.NET – INSERT/SELECT ⭐10–15 marksCore practical taskEvery year ✅
State Management ⭐10 marksCommon viva QEvery year ✅
Connected vs Disconnected5–10 marksViva conceptEvery year ✅
Validation Controls5–10 marksPractical add-onMost years ✅
Page Lifecycle / IsPostBack5 marksViva questionMost years ✅
Web Forms Controls (TextBox, DropDown, GridView)5 marksCore practical taskEvery 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 RequestHTTP Request receivedServer receives request from browser
2. StartIsPostBack setPage properties like Request, Response, IsPostBack initialized
3. InitializationPage_InitControls initialized, UniqueIDs assigned
4. Load ⭐Page_LoadUse if(!IsPostBack) here for one-time initialization
5. ValidationValidate()All validation controls run
6. Event Handling ⭐btnSubmit_ClickButton click or other event handler executes
7. RenderingRender()HTML sent to browser
8. UnloadPage_UnloadCleanup — 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 LocationServer memoryClient (hidden field)Client browser
ScopeAcross pagesSame page onlyAcross pages + sessions
PersistenceUntil timeout/abandonUntil browser closesUntil Expires date
SecurityHigh (server-side)Medium (encoded)Low (client exposed)
Best Use CaseLogin, user dataForm data, countersPreferences, 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.

1. RequiredFieldValidator – Field must not be empty:
<asp:RequiredFieldValidator ID="rfvName" runat="server"
    ControlToValidate="txtName"
    ErrorMessage="Name is required."
    ForeColor="Red" />
2. RangeValidator – Value must be in range:
<asp:RangeValidator ID="rvAge" runat="server"
    ControlToValidate="txtAge"
    MinimumValue="18" MaximumValue="60"
    Type="Integer"
    ErrorMessage="Age must be between 18 and 60."
    ForeColor="Red" />
3. CompareValidator – Compare two fields (e.g., passwords):
<asp:CompareValidator ID="cvPassword" runat="server"
    ControlToValidate="txtConfirmPass"
    ControlToCompare="txtPassword"
    ErrorMessage="Passwords do not match."
    ForeColor="Red" />
4. RegularExpressionValidator – Validate email/phone pattern:
<asp:RegularExpressionValidator ID="revEmail" runat="server"
    ControlToValidate="txtEmail"
    ValidationExpression="\w+@\w+\.\w+"
    ErrorMessage="Enter a valid email address."
    ForeColor="Red" />
5. CustomValidator – Custom server-side logic:
<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");
}
6. ValidationSummary – Show all errors in one place:
<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)
ConnectionOpen while reading dataClosed after data is fetched
Key ClassSqlDataReaderSqlDataAdapter + DataSet/DataTable
Read DirectionForward-onlyAny direction, filterable
Data ModificationRead-onlyCan modify in-memory data
PerformanceFaster (streams data)Slightly slower (caches all data)
Best ForLarge read-only result setsGridView binding, sorting, filtering
XML SupportNoYes (DataSet.WriteXml)

❓ Frequently Asked Questions

Q1: What is the difference between Connected and Disconnected ADO.NET architecture? A: Connected uses SqlDataReader — connection stays open, forward-only, fast reads. Disconnected uses SqlDataAdapter + DataSet — connection closes after fetch, data stored in memory, can be sorted/filtered/modified, and bound to GridViews.
Q2: What is Page.IsPostBack and why do we use it? A: IsPostBack returns false on first page load and true on subsequent form submissions (button clicks etc.). Use if (!IsPostBack) in Page_Load to ensure GridView binding and dropdown population only happen once — not on every button click.
Q3: What is the difference between Session and ViewState? A: Session is stored on the server, persists across multiple pages, used for login data. ViewState is stored in a hidden field on the page, persists only across postbacks on the same page, used for small page-level data like counters.
Q4: Why should I always use parameterized queries? A: Parameterized queries prevent SQL Injection attacks. If a user types SQL commands into a TextBox, parameterized queries ensure they are treated as plain text data — not executable SQL. The VNSGU external examiner specifically checks for this in practical exams.
Q5: What are the 6 ASP.NET Validation Controls? A: (1) RequiredFieldValidator – not empty. (2) RangeValidator – within a range. (3) CompareValidator – compare two fields. (4) RegularExpressionValidator – pattern match (email/phone). (5) CustomValidator – custom logic. (6) ValidationSummary – display all errors together.
Q6: What is the ASP.NET Page Lifecycle sequence? A: Page Request → Start (IsPostBack set) → Init (Page_Init) → Load (Page_Load) → Validation → Event Handling (Button_Click) → Rendering → Unload. The most important stages for practical coding are Load and Event Handling.
Q7: Why does my GridView disappear after clicking a button? A: You are binding the GridView in Page_Load without 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(); }.
Q8: What is the difference between ExecuteReader, ExecuteNonQuery, and ExecuteScalar? A: ExecuteReader — for SELECT, returns SqlDataReader. ExecuteNonQuery — for INSERT/UPDATE/DELETE, returns rows affected. ExecuteScalar — for single-value results like COUNT/MAX, returns the first cell of the first row.
Q9: What is the difference between Session and Cookies? A: Session is server-side — more secure, lost when browser closes (by default). Cookies are client-side — stored in browser, can persist across browser sessions via Expires property. Session is better for sensitive data; Cookies for preferences and persistent tokens.
Q10: Where can I find VNSGU BCA Sem 6 past ASP.NET papers? A: Download free VNSGU BCA Sem 6 past papers at questionbanker.in/papers/bca. Past papers reveal the exact INSERT/SELECT question formats, practical program types, and viva questions that repeat every year.

📌 Related BCA Study 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