CRUD operations (Create, Read, Update, Delete) are fundamental for any data-driven application. In ASP.NET Web Forms, you can implement these operations using various data access techniques, such as ADO.NET or Entity Framework. This guide will demonstrate how to perform CRUD operations using a simple example with a SQL Server database.
1. Setting Up the Database
First, create a SQL Server database and a table to store the data. For this example, we will create a Products
table.
CREATE TABLE Products (
ProductID INT PRIMARY KEY IDENTITY(1,1),
ProductName NVARCHAR(100),
Price DECIMAL(18, 2)
);
2. Creating the ASP.NET Web Forms Application
Next, create a new ASP.NET Web Forms application in Visual Studio. Add a connection string to your Web.config
file:
<configuration>
<connectionStrings>
<add name="MyDatabase"
connectionString="Server=YOUR_SERVER;Database=YOUR_DATABASE;User Id=YOUR_USERNAME;Password=YOUR_PASSWORD;"
providerName="System.Data.SqlClient" />
</connectionStrings>
</configuration>
3. Designing the User Interface
In your ASPX page, create a form for adding and updating products, along with a GridView to display the products.
<asp:TextBox ID="txtProductName" runat="server" Placeholder="Product Name" />
<asp:TextBox ID="txtPrice" runat="server" Placeholder="Price" />
<asp:Button ID="btnAdd" runat="server" Text="Add Product" OnClick="btnAdd_Click" />
<asp:GridView ID="gvProducts" runat="server" AutoGenerateColumns="false" OnRowCommand="gvProducts_RowCommand">
<Columns>
<asp:BoundField DataField="ProductID" HeaderText="ID" />
<asp:BoundField DataField="ProductName" HeaderText="Product Name" />
<asp:BoundField DataField="Price" HeaderText="Price" />
<asp:ButtonField ButtonType="Button" CommandName="Edit" Text="Edit" />
<asp:ButtonField ButtonType="Button" CommandName="Delete" Text="Delete" />
</Columns>
</asp:GridView>
4. Implementing CRUD Operations in Code-Behind
In the code-behind file (e.g., Default.aspx.cs), implement the CRUD operations.
4.1 Create Operation
protected void btnAdd_Click(object sender, EventArgs e)
{
using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["MyDatabase"].ConnectionString))
{
string query = "INSERT INTO Products (ProductName, Price) VALUES (@ProductName, @Price)";
SqlCommand command = new SqlCommand(query, connection);
command.Parameters.AddWithValue("@ProductName", txtProductName.Text);
command.Parameters.AddWithValue("@Price", decimal.Parse(txtPrice.Text));
connection.Open();
command.ExecuteNonQuery();
BindGrid();
}
}
4.2 Read Operation
private void BindGrid()
{
using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["MyDatabase"].ConnectionString))
{
string query = "SELECT * FROM Products";
SqlCommand command = new SqlCommand(query, connection);
SqlDataAdapter adapter = new SqlDataAdapter(command);
DataTable dataTable = new DataTable();
adapter.Fill(dataTable);
gvProducts.DataSource = dataTable;
gvProducts.DataBind();
}
}
4.3 Update Operation
protected void gvProducts_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Edit")
{
int index = Convert.ToInt32(e.CommandArgument);
GridViewRow row = gvProducts.Rows[index];
txtProductName.Text = row.Cells[1].Text;
txtPrice.Text = row.Cells[2].Text;
ViewState["EditIndex"] = index;
}
else if (e.CommandName == "Delete")
{
int index = Convert.ToInt32(e.CommandArgument);
DeleteProduct(index);
}
}
private void DeleteProduct(int index)
{
int productId = Convert.ToInt32(gvProducts.DataKeys[index].Value);
using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["MyDatabase"].ConnectionString))
{
string query = "DELETE FROM Products WHERE ProductID = @ProductID";
SqlCommand command = new SqlCommand(query, connection);
command.Parameters.AddWithValue("@ProductID", productId);
connection.Open();
command.ExecuteNonQuery();
BindGrid();
}
}
protected void btnUpdate_Click(object sender, EventArgs e)
{
int index = (int)ViewState["EditIndex"];
int productId = Convert.ToInt32(gvProducts.DataKeys[index].Value);
using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["MyDatabase"].ConnectionString))
{
string query = "UPDATE Products SET ProductName = @ProductName, Price = @Price WHERE ProductID = @ProductID";
SqlCommand command = new SqlCommand(query, connection);
command.Parameters.AddWithValue("@ProductName", txtProductName.Text);
command.Parameters.AddWithValue("@Price", decimal.Parse(txtPrice.Text));
command.Parameters.AddWithValue("@ProductID", productId);
connection.Open();
command.ExecuteNonQuery();
BindGrid();
}
}
5. Conclusion
Implementing CRUD operations in ASP.NET Web Forms is straightforward with the use of ADO.NET for data access. By following the steps outlined above, you can create a simple application that allows users to add, view, edit, and delete products from a database. This foundational knowledge can be expanded upon to create more complex data-driven applications.