How fill existing DataTable?

B

Bill Todd

I have a DataSet with an existing DataTable that was created at design
time. At runtime I want to fill the existing DataTable with data from
a DataAdapter. When I call

MyAdapter.Fill(MyDataSet, 'MyTable');

I get the error, "A DataTable named 'MyTable' already belongs to this
DataSet".

What is the right way to fill an existing DataTable?
 
M

Miha Markic [MVP C#]

Hi Bill,

This overload of fill method tries to create a new DataTable with that name.
Instead, invoke Fill(MyDataSet.MyTable) version.
 
W

William Ryan eMVP

Bill:

Like Miha said, when you call Fill with the DataSet, DataTable constructor,
it will create the new DataTable. Notice that you never have to declare
"Mytable" when you use this constructor...that's because it will create it
for you. However, you may have situations where you aren't working with
DataSet as all and you can't just call
DataAdapter.Fill("StringNameForDataTable"). The only reason you can use the
String name is because you've given the fill method a dataset context to
work in. Anyway, to fill a datatable alone, you'd need to declare and
instantiate it first. So, each time you call fill with that constructor, C#
is trying to create another table named MyTable. You can reference it by
name or index after that..MyAdapter.Fill(MyDataSet.Tables[0]); or
MyDataSet.Tables["MyTable"]); or whatever you named the table.

You can also just call fill that way (with the named table from the onset to
avoid any ambiguity. each way is valid, but it may be a little more clear
if you specify the table in the method call.

HTH,

Bill
 
B

Bill Todd

Thanks. Makes since when you think about it. Guess I was too tired
when I was reading the help last night.<g>
 
K

Kevin Yu [MSFT]

Thanks for Bill and Miha's quick response!

Hi Bill,

Bill and Miha's replies are exactly what I want to say. If you have any
further questions, please feel free to post them in the community. Here is
a link for all the overloads of DbDataAdapter.Fill method:

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/
frlrfsystemdatacommondbdataadapterclassfilltopic.asp

HTH.

Kevin Yu
=======
"This posting is provided "AS IS" with no warranties, and confers no
rights."
 
K

Kevin Yu [MSFT]

Hi Bill,

I'd like to know if this issue has been resolved yet. Is there anything
that I can help. I'm still monitoring on it. If you have any questions,
please feel free to post them in the community.

Kevin Yu
=======
"This posting is provided "AS IS" with no warranties, and confers no
rights."
 

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