Link to home
Create AccountLog in
Avatar of SJRAdmin
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);
                cn.Open();

                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;


                rdr.Close();
                cn.Close();
            }
          catch (Exception ex)
          {
              MessageBox.Show(ex.Message);
          }
        }

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of Najam Uddin
Najam Uddin
Flag of United States of America image

Link to home
membership
Create an account to see this answer
Signing up is free. No credit card required.
Create Account
Avatar of riaanvdl
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.