Complete CRUD Operations using ASP.NET Web Forms with C#

Complete CRUD Operations using ASP.NET Web Forms with C#

Introduction:

    CRUD operations—Create, Read, Update, and Delete—are essential for most data-driven applications. In this blog post, we'll explore how to implement these operations using ASP.NET Web Forms with the .NET Framework and C#. This guide will help you understand the basics and get you started with managing data in your web applications.

Setting Up the Project

Before we dive into CRUD operations, let's set up an ASP.NET Web Forms project.

Create a New ASP.NET Web Forms Project:

Open Visual Studio.
Select "File" > "New" > "Project".
Choose "ASP.NET Web Application (.NET Framework)".
Select the "Web Forms" template and click "Create".

Add a Database:


Right-click on the project in Solution Explorer and select "Add" > "New Item".
Choose "SQL Server Database" and name it ProductsDB.mdf.
Right-click on the database in Server Explorer and select "Add New Table".
Create a table named Products with columns ProductID (Primary Key, Identity), Name, Price, and Quantity.

Set Up the Entity Framework:

Right-click on the project in Solution Explorer and select "Manage NuGet Packages".
Install the EntityFramework package.
Right-click on the project and select "Add" > "New Item".
Choose "ADO.NET Entity Data Model", name it ProductModel.edmx, and click "Add".
Choose "EF Designer from Database", connect to your ProductsDB.mdf, and select the Products table.
Implementing CRUD Operations
Now that we have our project set up, let’s implement the CRUD operations.

1. Create
To add a new product to the database:

Design the Form:

Open the Default.aspx page.

Add TextBox controls for Name, Price, and Quantity.
Add a Button control for submitting the form.
html:

<asp:TextBox ID="txtName" runat="server" placeholder="Product Name"></asp:TextBox><br />
<asp:TextBox ID="txtPrice" runat="server" placeholder="Price"></asp:TextBox><br />
<asp:TextBox ID="txtQuantity" runat="server" placeholder="Quantity"></asp:TextBox><br />
<asp:Button ID="btnAdd" runat="server" Text="Add Product" OnClick="btnAdd_Click" />
Handle the Button Click:

In the code-behind (Default.aspx.cs), add the following method to handle the button click event.

csharp:

protected void btnAdd_Click(object sender, EventArgs e)
{
    using (var db = new ProductsDBEntities())
    {
        var product = new Product
        {
            Name = txtName.Text,
            Price = decimal.Parse(txtPrice.Text),
            Quantity = int.Parse(txtQuantity.Text)
        };
        db.Products.Add(product);
        db.SaveChanges();
    }
    Response.Redirect("Default.aspx");
}

2. Read

To display the list of products:

Design the GridView:

Add a GridView control to the Default.aspx page to display the products.

html:

<asp:GridView ID="gvProducts" runat="server" AutoGenerateColumns="False" DataKeyNames="ProductID">
    <Columns>
        <asp:BoundField DataField="ProductID" HeaderText="ID" ReadOnly="True" />
        <asp:BoundField DataField="Name" HeaderText="Name" />
        <asp:BoundField DataField="Price" HeaderText="Price" />
        <asp:BoundField DataField="Quantity" HeaderText="Quantity" />
        <asp:CommandField ShowEditButton="True" ShowDeleteButton="True" />
    </Columns>
</asp:GridView>

Bind Data to GridView:

In the Page_Load event of Default.aspx.cs, bind the GridView to the database.

csharp:

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        BindGrid();
    }
}

private void BindGrid()
{
    using (var db = new ProductsDBEntities())
    {
        gvProducts.DataSource = db.Products.ToList();
        gvProducts.DataBind();
    }
}

3. Update

To update an existing product:

Handle GridView Editing:

Add the RowEditing, RowCancelingEdit, and RowUpdating event handlers to the GridView in the code-behind.

csharp

protected void gvProducts_RowEditing(object sender, GridViewEditEventArgs e)
{
    gvProducts.EditIndex = e.NewEditIndex;
    BindGrid();
}

protected void gvProducts_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
    // Cancel the editing mode in GridView
    gvProducts.EditIndex = -1;

    // Rebind the GridView to its data source to display the original data
    BindGrid();
}

Summary

In this blog post, we've covered the essential CRUD operations using ASP.NET Web Forms with the .NET Framework and C#. Here's a quick recap of what we've done:

  1. Create: We added new products to the database using a form.
  2. Read: We displayed a list of products using a GridView control.
  3. Update: We allowed users to edit and update product details directly within the GridView.
  4. Delete: We enabled users to delete products from the database.

These operations form the backbone of most data-driven web applications, and understanding them will allow you to build robust and dynamic systems. If you're new to ASP.NET Web Forms, this guide should give you a solid foundation to start creating more complex applications.

Prepare for your ASP.NET C# interview with confidence! Focus on core areas like state management, page lifecycle, server controls, and data handling to increase your chances of success.

#ASP.NET #CSharp #InterviewQuestions #Freshers #DotNet #WebDevelopment #TechCareers #Programming #Developer #Coding

Post a Comment

0 Comments