- 1 year ago
How can I read and display selected SQL Server columns in C# DataGridView?
Comment
1 / 1
To read and display selected SQL Server columns in a C# DataGridView, you can follow these steps:
- Set up a connection to the SQL Server database using the
SqlConnection
class. Make sure to replace the connection string with the appropriate values for your database:
csharpstring connectionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=Username;Password=Password";
SqlConnection connection = new SqlConnection(connectionString);
- Open the connection to the SQL Server database:
csharpconnection.Open();
- Create a SQL query that selects the desired columns from the database table:
csharpstring query = "SELECT Column1, Column2, Column3 FROM TableName";
- Create a
SqlCommand
object using the SQL query and the connection:
csharpSqlCommand command = new SqlCommand(query, connection);
- Create a
SqlDataReader
object to execute the SQL command and read the data from the database:
csharpSqlDataReader reader = command.ExecuteReader();
- Create a new
DataTable
to store the retrieved data:
csharpDataTable dataTable = new DataTable();
dataTable.Load(reader);
- Close the
SqlDataReader
and the database connection:
csharpreader.Close();
connection.Close();
- Bind the
DataTable
to theDataGridView
control:
csharpdataGridView.DataSource = dataTable;
Make sure you have a DataGridView
control named dataGridView
on your form where you want to display the data.
This code will execute the SQL query, retrieve the selected columns from the SQL Server database, load the data into a DataTable
, and bind the DataTable
to the DataGridView
for display.
Note: You may need to handle exceptions, dispose of resources properly, and implement appropriate error handling based on your specific application requirements.
Remember to replace "ServerName," "DatabaseName," "Username," "Password," "TableName," and the column names with the actual values specific to your SQL Server database and table.