Attach a DataTable to a DataSet

S

Sylvain Larin

I have a business object that return the list of contacts to the user
interface. Here is the code of the method:

public DataTable getContact ()
{
// I know, this part should be in the Data Layer...

SqlConnection conn = new SqlConnection (...);
DataSet dsContact = new DataSet ();
SqlDataAdapter adptContact = new SqlDataAdapter ("SELECT * FROM
Contact ORDER BY Contact", conn);
adptContact.Fill (dsContact, "Contact");
return dsContact.Tables ["Contact"];
}

The user interface should get the list and add it to it's DataSet. A
control will then be bounded to this list.

I have some questions:

- Must I pass through a DataSet and a DataAdapter class to fill a DataTable?
- I return a DataTable instead of a DataSet because I figure that it is
smaller and should be faster. Am I right in this assumption?
- When a DataTable (or DataSet) is passed like this between layers, what
is really passed between the EXE and the DLL, a XML string or the object
is marshalled and passed?
- In the user interface, I would like to put all the tables I get like
this in a DataSet instead of defining a property for each one, but I
can't get the DataSet to add the DataTable. Here is the code:

Contact contact = new Contact ();
DataTable dtContact = contact.getContact ();
dsMain.Tables.Add (dtContact); // Exception is throwed here

Any suggestions?

TIA
 
E

Elton Wang

You can try directly fill data table in method getContact:

public DataTable getContact ()
DataTable contactTable = new DataTable();
SqlDataAdapter adptContact = new SqlDataAdapter("SELECT
* FROM Contact ORDER BY Contact", CONNECTION_STRING);
adptContact.Fill(contactTable);
return contactTable;
}

HTH

Elton Wang
(e-mail address removed)
 
R

Robbe Morris [C# MVP]

Your getContact method is already establishing a reference
to a DataSet. Make that method fill a datatable instead of a
dataset and you should be fine. I do this sort of thing
all the time in my apps.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top