Link to home
Create AccountLog in
Avatar of SJRAdmin

asked on

DataTable or BindingSource?? C# Question

I am using C# Windows Forms and dealing with databases and recordsets. I am finding that I have code that works the same using a bindingsource and datatable. You can see the code I have attached. Previously my code utilized the datatable, then as a test I modified a couple of lines of code to use the bindingsource instead and found that it works as well.

Can someone tell me the difference between these 2 items and which is better to use?

SqlConnection cn = new SqlConnection(PubVar.dbConn);

                SqlCommand cmd = new SqlCommand(PubVar.dbConn, cn);
                cmd.CommandText = "sp_LookupPrices";
                cmd.CommandType = CommandType.StoredProcedure;

                SqlParameter param;
                param = cmd.Parameters.AddWithValue("@CustomerNumber", txtCustomerNumber.Text);
                param = cmd.Parameters.AddWithValue("@CustomerName", txtCustomerName.Text);
                param = cmd.Parameters.AddWithValue("@ProductNumber", txtProductNumber.Text);
                param = cmd.Parameters.AddWithValue("@ProductName", txtProductName.Text);
                param = cmd.Parameters.AddWithValue("@CompanyID", PubVar.CompanyID);
              //---OLD 1 line of code using the datatable
               // DataTable tbl = new DataTable();

                SqlDataReader rdr = cmd.ExecuteReader();

             //--OLD 2 lines of code using the datatable
               // tbl.Load(rdr);
                //dgPriceSearch.DataSource = tbl;

              //---new 2 lines of code using the bindingsource
                BindingSource bs1 = new BindingSource(rdr, null);
                dgPriceSearch.DataSource = bs1;

          catch (Exception ex)

Open in new window

Avatar of Najam Uddin
Najam Uddin
Flag of United States of America image

Link to home
Create an account to see this answer
Signing up is free. No credit card required.
Create Account
Avatar of riaanvdl

As far as I know using BindingSource is quicker than using a DataTable because it binds directly to the datasource, where if you use a datatable you bind, then have to read the data and then load it.
BindingSource also provides a bit more functionality to data manipulation like currency management and change notification.

BindingSource is definately the way to go.