¿Cómo obtener un objeto DataTable de una base de datos usando su nombre de tabla en C#?

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.)

¿Cómo puedo hacer eso?

Ya lo he intentado:

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?)

Intenté usar 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;

preguntado el 31 de julio de 12 a las 12:07

por que exactamente DataTable? why not use EF, SubSonic, NHibernate, ...?! -

can you explain more Andreas Niedermair? -

Hossein, ya sabes there's no excuse to not uppercase sentences, nor for the odd spacing before punctuation. Please fix that? -

Nice. I fixed a bit more, but your effort was good enough for an upvote ;-) -

1 Respuestas

You are correct. the schema needs to come somewhere Here is typical code I use to connect and get a table.

string connectionstring = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=MYDATA.MDB;"

OleDbConnection new OleDbConnection(connectionstring);
OleDbCommand cmd = new OleDbCommand(Sql, conn);
OleDbDataAdapter adapter = new OleDbDataAdapter(cmd);
DataTable table = new DataTable();

Respondido 31 Jul 12, 18:07

Here is a article from c-sharpcorner.com/uploadfile/suprotim/… dealing with retrieving schema for tables. - gary kindel

Thank you verymuch i'll give it a try - Hossein

by the way what does that "WHERE 1=0" mean ? would it not give an empty datatable ? with no rows ? cause 1 never equals to 0 and thus no row will be selected !! cant we just say "SELECT * FROM MYTABLE" ? - Hossein

WHERE 1=0 is a way of getting an empty structure. It works from MS Access and SQL server. Not sure about MySQL. - gary kindel

so i was right then :) by the way shouldnt we open the connection prior to using adapter? or close it afterwards? - Hossein

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.