Binding a GridView control programmatically with dataset

Binding a GridView with a dataset is done after creating the dataset. To create a DataSet, we need to follow the steps given below.
  • Declare the string variable 'connectionString' to hold the Connection String
  • Declare the Connection object
  • Declare the string variable 'str_Account_Select' to hold the SQL statement
  • Declare the Command object
  • Declare the DataSet object
  • Instantiate the Connection object
  • Open the connection
  • Instantiate the Command object
  • Instantiate the DataSet object
  • Instantiate the SqlDataAdapter object
  • Populate the DataSet
All the above steps happen in the Page_Load() method.

After creating the dataset, we can bind the GridView with a dataset. To bind the GridView control programmatically, we set DataSource property and call DataBind() method of the GridView control in the Page_Load() method.

In the following code example, the GridView control is bound to the DataSet object. After the DataSource property is set, the DataBind() method is called explicitly. We need to place the following code in a .aspx page to create a GridView control.
<asp:GridView ID="GridView1"  runat="server" />
In the Page_Load method, we place the following code to bind the GridView with a dataset.

protected void Page_Load(object sender, EventArgs e)
{
	if (!Page.IsPostBack)
	{
	string connectionString = "server=SYS2;" + "integrated security=SSPI;" + 	
    	"database=ERPFinAccounting";
	SqlConnection myConnection;
	string str_Account_Select = "SELECT * FROM AccountsTable";
	SqlCommand myCommand;
	DataSet myDataSet;
	myConnection = new SqlConnection(connectionString);
	myConnection.Open();
	myCommand = new SqlCommand(str_Account_Select, myConnection);
	SqlDataAdapter mySQLDataAdapter;
	myDataSet = new DataSet();
	mySQLDataAdapter = new SqlDataAdapter(myCommand);
	mySQLDataAdapter.Fill(myDataSet, "AccountsTable");
	GridView1.DataSource = myDataSet;
	GridView1.DataBind();
	}
}