How to fill a DataSet Object in C#

Add a Button control named btnLoad and a DataGrid control named dgProducts on the form/page.

using System.Data;
using System.Data.SqlClient;
private void btnLoad_Click(object sender,  System.EventArgs e)
    // Create a SqlConnection
    SqlConnection cnn = new SqlConnection(
    "Data Source=(local); Initial Catalog=Northwind;"+
    " Integrated Security=SSPI");
    // Create a SqlCommand
    SqlCommand cmd = cnn.CreateCommand();
    cmd.CommandType = CommandType.Text;
    cmd.CommandText = "SELECT * FROM Products " +
     " ORDER BY ProductName";
    // Set up the DataAdapter and fill the DataSet
    SqlDataAdapter da = new SqlDataAdapter();
    da.SelectCommand = cmd;
    DataSet ds = new DataSet();
    da.Fill(ds, "Products");
    // Display the data on the user interface
    dgProducts.DataSource = ds;
    dgProducts.DataMember = "Products";

Enjoyed this post? Share it!


Leave a comment

Your email address will not be published.