here’s an example C# code that retrieves data from a SQL Server database using a query and displays it in an ASP.NET GridView control:
// First, create a SqlConnection object to connect to your database
using (SqlConnection connection = new SqlConnection("YourConnectionString"))
{
// Create a SqlCommand object to execute your SQL query
SqlCommand command = new SqlCommand("SELECT * FROM YourTable", connection);
// Open the connection to the database
connection.Open();
// Create a SqlDataReader object to read the results of your query
SqlDataReader reader = command.ExecuteReader();
// Bind the SqlDataReader to the GridView control
yourGridView.DataSource = reader;
yourGridView.DataBind();
// Close the SqlDataReader and the connection to the database
reader.Close();
connection.Close();
}
Replace “YourConnectionString” with the connection string to your SQL Server database, and “YourTable” with the name of the table you want to query. Also, replace “yourGridView” with the ID of your GridView control in your ASP.NET page.

Ankit Srivastava is an IT trainer, technology educator, and digital skills mentor with expertise in programming, data analytics, AI, and software development. He has successfully trained thousands of learners, with more than 10,000 student enrollments on Udemy. His practical teaching approach empowers students and professionals to build in-demand technical skills. Colorstech channel where Ankit posts video tutorials has more than 8000 Subscribers.

