In ASP.NET, you can connect your web application to a database to store and retrieve data. Let's create a simple example of connecting to a SQL Server database and performing basic CRUD (Create, Read, Update, Delete) operations using ASP.NET Web Forms.
Example: Connecting to a SQL Server Database in ASP.NET Web Forms
Set Up Your Project:
Add a Database to Your Project:
SampleDB.mdf
.Design Your Web Page:
Example
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="YourProjectName._Default" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>ASP.NET Web Page with Database</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="GridView1" runat="server"></asp:GridView>
</div>
</form>
</body>
</html>
Default.aspx.cs
(code-behind file) in Visual Studio.Example
using System;
using System.Data;
using System.Data.SqlClient;
namespace YourProjectName
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
// Connect to the database
string connectionString = @"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\SampleDB.mdf;Integrated Security=True";
using (SqlConnection connection = new SqlConnection(connectionString))
{
// Define the SQL query
string query = "SELECT * FROM Users";
// Create a SqlCommand object
using (SqlCommand command = new SqlCommand(query, connection))
{
// Open the database connection
connection.Open();
// Execute the SQL query and retrieve data into a DataTable
DataTable dt = new DataTable();
using (SqlDataReader reader = command.ExecuteReader())
{
dt.Load(reader);
}
// Bind the DataTable to the GridView control
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
}
}
}
}
Default.aspx
page in your browser.That's it! You've created a simple ASP.NET web page connected to a SQL Server database. This example demonstrates the basic concept of accessing data from a database and displaying it in a web application using ASP.NET Web Forms.