Adding a Datatable to a dataset

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

Hi,
I'm currently getting up to speed with ADO.NET & have a few questions on it.

This question relates to why a data table is added to a data set such:

DataTable dtEmp = ds.Tables.Add["employees"]; // From book

i would have thought it would be more like:

DataTable dtEmp = New DataTable("employees");
ds.Tables.Add(dtEmp); // The way I think it should be. Works ok

So what is going on in the first line? (from the book)
Is dtEmp being referenced to the "employees" table that is being added to
the dataset? (As opposed to dtEmp actually being added?). It doesn't seem
intuitutive to me...

Thanks for any comments
Ant
 
Ant,

What book, what writter,
DataTable dtEmp = ds.Tables.Add["employees"]; // From book
Dataset.tables is a property which is a collection of datarows.

Probably was meant

DataTable dtEmp = ds.Tables["employees"]; //And is it a typo.


Cor
 
Hopefully that was my book you got the code from ;-) [Comments inline
below]
Ant said:
Hi,
I'm currently getting up to speed with ADO.NET & have a few questions on
it.

This question relates to why a data table is added to a data set such:

DataTable dtEmp = ds.Tables.Add["employees"]; // From book

i would have thought it would be more like:

DataTable dtEmp = New DataTable("employees");
ds.Tables.Add(dtEmp); // The way I think it should be. Works ok
--Ant - they are both correct. Your way is probably more clear per se, but
it's also less concise. Obviously any time you have a collection (which
tables is in a dataset), then you can declare an instance of whatever that
collection holds and add it. However if you look at the documentation for
DataSet.Tables.Add, it returns a DataTable. So using that syntax, you're
declaring a DataTable and setting it to the return value of the Add method
(which is of type DataTable). I much prefer that syntax b/c it's more
concise. Just to verify what's going, on, do a Debug.WriteLine dtEmp
TableName and you'll see it's 'employees' which verfies that a new table was
added..

think of it as a method that looks like this...
public DataTable Add(String tableName){

DataTable dt = new DataTable(tableName); //So it creates a new
DataTable based on the name you specified.
this.Tables.Add(tableName);//It takes this table and adds it to the
internal Tables collection
return dt; //It returns it so you can reference it.
}

At the end of the day, the same process is happening, it's just that in one
you do it yourself, the other one does the same thing behind the scenes for
you.
 
Back
Top