Skip to main content

Practical-23

Display the records from database using Data Reader Object

In this practical, we will learn how to display the records from a database using the Data Reader object in ASP.NET.

Step 1: Create a new ASP.NET Web Application project

  1. Open Visual Studio and create a new ASP.NET Web Application project.
  2. Choose the Empty template and click OK.

Step 2: Add a Data Reader object to the web form

  1. Open the default.aspx file in the Solution Explorer.
  2. Switch to the Design view.
  3. Drag and drop a Button control from the Toolbox onto the web form.
  4. Set the Text property of the Button control to "Display Records".

Step 3: Configure the Button click event

  1. Double-click on the Button control to generate the click event handler in the code-behind file (default.aspx.cs).
  2. In the click event handler, write the necessary code to connect to the database and retrieve the records using the Data Reader object.
  3. Use the Data Reader object to read the records and display them on the web form.
protected void Button1_Click(object sender, EventArgs e)
{
string connectionString = "your_connection_string_here";
string query = "SELECT * FROM your_table_name_here";

using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand command = new SqlCommand(query, connection);
connection.Open();

SqlDataReader reader = command.ExecuteReader();

while (reader.Read())
{
// Display the records on the web form
// Example: Response.Write(reader["column_name"].ToString());
}

reader.Close();
}
}

Step 4: Run the application

  1. Press F5 or click the Start Debugging button to run the application.
  2. Click the "Display Records" button to retrieve and display the records from the database.

That's it! You have successfully displayed the records from the database using the Data Reader object in ASP.NET.

Make sure to save your changes and submit this practical in your notebook.