To display data retrieved from a database using ADO.NET in an ASP.NET application, you typically use ASP.NET server controls like GridView, Repeater, DataList, etc. These controls provide a convenient way to bind data and display it in a tabular or list format on your web page.
Here's a basic example demonstrating how to display data retrieved from a database using ADO.NET and ASP.NET GridView control:
First, retrieve data from the database using ADO.NET as shown in the previous examples. Suppose we have retrieved data into a DataTable named dataTable
.
In your ASP.NET web form (e.g., Default.aspx
), add a GridView control to display the data:
Example
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebApplication.Default" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Display Data with ADO.NET and GridView</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="true">
</asp:GridView>
</div>
</form>
</body>
</html>
Default.aspx.cs
), bind the DataTable to the GridView control:Example
using System;
using System.Data;
using System.Data.SqlClient; // Assuming SQL Server database
namespace WebApplication
{
public partial class Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
// Retrieve data from the database (example)
DataTable dataTable = new DataTable();
using (SqlConnection connection = new SqlConnection("YourConnectionString"))
{
string query = "SELECT * FROM YourTable";
SqlCommand command = new SqlCommand(query, connection);
SqlDataAdapter adapter = new SqlDataAdapter(command);
adapter.Fill(dataTable);
}
// Bind data to the GridView control
GridView1.DataSource = dataTable;
GridView1.DataBind();
}
}
}
}
Replace "YourConnectionString"
with your actual database connection string, and "YourTable"
with the name of the table from which you want to retrieve data.
When you run the ASP.NET web application, the GridView control will automatically display the data retrieved from the database in a tabular format.
This is a basic example of displaying data using ADO.NET and the GridView control in ASP.NET. You can customize the appearance of the GridView and handle events as per your requirements. Additionally, you can use other ASP.NET server controls like Repeater, DataList, ListView, etc., to display data in different formats/styles.