SqlDataAdapter Fill Method

Introduction

In this article, we will learn about SqlDataAdapter Fill Method in SQL.

SqlDataAdapter 

  • It is a part of the ADO.NET Data Provider.
  • SqlDataAdapter is used to retrieve data from a data source and store the results in a DataSet.
  • Dataset represents a collection of data(tables) retrieved from the Data Source.

Diagram

1.gif

Steps

  1. Create a query string.
  2. Create a connection object and open it.
  3. Create a SqlDataAdapter object accompanying the query string and connection object.
  4. Create a DataSet object.
  5. Use the Fill method of the SqlDataAdapter object to fill the DataSet with the result of the query string.
  6. Close the connection object

Example

private void button1_Click(object sender, EventArgs e)
{
     SqlConnection con;
     SqlDataAdapter adapter ;
     DataSet ds = new DataSet();
      try {
           //create connection object
           con = new SqlConnection("connetionString");
           //create query string(SELECT QUERY)
           String query="SELECT * FROM SOMETABLE WHERE...";
           con.Open();
           //Adapter bind to query and connection object
           adapter = new SqlDataAdapter(query, con);
           //fill the dataset
           adapter.Fill(ds);
            }
    catch (Exception ex)
      {
          con.Close();                  
      }
}

Result

Your DataSet contains the result table of the SELECT query. You can play around with the table and its data.

Conclusion

In this article, we learned about SqlDataAdapter Fill Method with code examples in SQL.


Similar Articles