Reputation: 25934
I'm trying to get a DataTable object out of a database using a table name that I have already. (I mean I want to choose between multiple tables. For this I only have a string which represents a table name. So I'm looking for a way to get my hands on the actual object.)
How can I do that?
I have already tried:
DataTable table = new DataTable(TableName);
But I believe this is wrong. (How is the application supposed to know where that table name comes from or where to search for it?)
I tried using con.GetSchema("Tables")
, but that gives out only table names which are strings, and not DataTable objects. I also tried this but it seems DataTables are not enumerable:
public static DataTable GetTable(string TableName, string conncetionstring)
{
SqlConnection con = new SqlConnection(conncetionstring);
foreach (DataTable table in con.GetSchema("Tables"))
{
if (table.TableName == TableName)
{
return table;
}
}
return null;
}
Upvotes: 3
Views: 1542
Reputation: 17699
You are correct. the schema needs to come somewhere Here is typical code I use to connect and get a table.
string Sql="SELECT * FROM MYTABLE WHERE 1=0";
string connectionstring = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=MYDATA.MDB;"
OleDbConnection new OleDbConnection(connectionstring);
conn.Open();
OleDbCommand cmd = new OleDbCommand(Sql, conn);
OleDbDataAdapter adapter = new OleDbDataAdapter(cmd);
DataTable table = new DataTable();
adapter.Fill(table);
conn.Close();
Upvotes: 4