Click here to Skip to main content
15,921,382 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,

How can I create a DataTable with the same structure as my SQL table?
I want to do this dynamically, so I don't want to add all the columns with their types hardcoded.
Posted
Updated 31-May-10 2:37am
v2

String CmdString = "select * from YourTable";
   SqlDataAdapter mySqlDataAdapter = new SqlDataAdapter(SelectCmdString, myConnection);
   SqlDataAdapter mySqlDataAdapter = new SqlDataAdapter(CmdString);

DataSet myDataSet = new DataSet();
   mySqlDataAdapter.Fill(myDataSet,"YourTable");


Here the entire table “YourTable” with the same structure will be copied to the DataTable.

myDataSet.Tables[0];



[kschuler addition]
If you want the structure without also pulling the data, one trick you could use would be to add a where 1=2 clause to the select statement above. So instead of using "select * from YourTable" which was suggested up above, you would use "select * from YourTable where 1=2"
 
Share this answer
 
v4
Have a look here.
 
Share this answer
 
Comments
William Winner 1-Jun-10 14:49pm    
Reason for my vote of 2
seriously...do you just google the first keyword you see, in this case "DataTable" and then give them the first link?

That link doesn't talk about SQL at all. Sure, it shows how to add columns and data to a DataTable, but that's really the long way around to populating a DataTable from SQL when there are classes to do just that.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900