Tech Junkie Blog: ADO.NET: Using System.Data.SqlClient.SqlDataAdapter To Fill System.Data.DataTable

Sunday, June 19, 2016

ADO.NET: Using System.Data.SqlClient.SqlDataAdapter To Fill System.Data.DataTable

In this example we will use the SqlDataAdapter to fill a DataTable then bind the data to a GridView

 1. Drag a GridView into your ASP.NET page

2. Use the following code to the fill the dtProducts DataTable with the adapter SqlDataAdapter, then bind it to the GridView1 control.

        protected void Page_Load(object sender, EventArgs e)
        {
            DataTable dtProducts = new DataTable();

              string connString = WebConfigurationManager.ConnectionStrings["NorthwindConnectionString"].
ConnectionString;

              using (SqlConnection conn = new SqlConnection(connString))
                {
                    SqlCommand cmd = new SqlCommand("SELECT * FROM Products", conn);
                    conn.Open();
                    SqlDataAdapter adapter = new SqlDataAdapter(cmd);
                    adapter.Fill(dtProducts);

                    GridView1.DataSource = dtProducts;
                    GridView1.DataBind();

                }
        }


No comments:

Post a Comment