C#.NET: Getting query results with SqlDataAdapter
While the SqlDataSource control is a nifty little thing, oftentimes a developer has to have more control over the page lifecycle (asp.net) or doesn’t want to use a BindingSource (winforms). Instead, you just want to query your database and get a DataSet back. Maybe you’re building a data access layer, or you’re using someone else’s framework, or it’s just biting you in the butt that binding with SqlDataSource fires off events in a completely unintuitive order.
We’ve seen how to execute a query that just returns one thing with ExecuteScalar. Now, though, we need entire results. And for whatever reason, we want a DataSet, not a SqlDataReader.
Luckily for us, querying and getting results into a DataSet using SqlDataAdapter is extremely easy, and works the same both in web forms and winforms. The following code is a full working example for querying Northwind (I just can’t get used to AdventureWorks yet, sorry) and getting a DataSet back. You can Bind a DataGridView to it, or a GridView, or loop the tables, or whatever.
Notes:
1. You have to have a using System.Data and using System.Data.SqlClient.
2. Your connection string should normally be stored in Settings (winforms) or web.config (web forms). In this example, I was playing with winforms, so it’s a Setting. For web forms, you’d use ConfigurationManager.ConnectionStrings.
private void button1_Click(object sender, EventArgs e)
{
DataSet myDataSet = new DataSet();
using (SqlConnection sqlconnection = new SqlConnection(Properties.Settings.Default.Northwind))
{
SqlCommand command = new SqlCommand("select * from products", sqlconnection);
SqlDataAdapter adapter = new SqlDataAdapter(command);
adapter.Fill(myDataSet);
}
}
It’s really that easy. Happy coding!
If you found this post helpful, please spread the love and share using one of the bookmark links below. Thanks!
Tags: C#.NET, csharp, database queries, DataSet, SqlDataAdapter
You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.
Do note that SqlCommand inherits from DbCommand, which implements the IDisposable interface, which means that the command should be disposed when it is done:
DataSet myDataSet = new DataSet();
using (SqlConnection sqlconnection = new SqlConnection(Properties.Settings.Default.Northwind))
{
using (SqlCommand command = new SqlCommand(”select * from products”, sqlconnection))
{
SqlDataAdapter adapter = new SqlDataAdapter(command);
adapter.Fill(myDataSet);
}
}
You caught me being lazy with my examples again, didn’t you Jesse? Good catch.
[...] SqlDataSource doesn’t work for what you want to do. It’s a great control, but as I’ve mentioned before, it can interfere with your plans because of the page lifecycle. You should also know how to run [...]