tags:

views:

608

answers:

5

Can I use the DataTable class like this:

DataTable client = new DataTable("client");

int primay_key = 1;

DataRow row = null;

row = client.findBy(primary_key);

After findBy, will the row object contains a row from the database?

I cannot find a example like that on the internet, looks like the .net built in DataTable class is not what I thought it was.

A: 

Yes, you can use a DataTable like that -- you might try DataTable.Rows.Find

Jason
erm, nope! The DataTable has not been folled with anything!
Mitch Wheat
A: 

A DataSet / DataTable is not a proper database as such. but can certainly be used for an in momory object model - but without most of the features you would normally associate with an RDBMS.

Marc Gravell
I was just about to say "Hey Marc, you're up late", but then realised you must be at the Summit...
Mitch Wheat
;-p Indeed. Just stopping in for a few moments, though ;-p
Marc Gravell
+2  A: 

A DataTable is an object that models a database table in memory. On its own, a DataTable doesn't do any kind of database interaction. You first have to create a data adapter object that's appropriate for your database system, then use it to fill your in-memory DataTable.

Example:

SqlConnection conn = new SqlConnection(connectionString); 
SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM Clients", conn); 
DataTable dt = new DataTable(); 
da.Fill(dt, "Clients");
David Brown
+3  A: 

You will need to fill a DataTable before you can 'query' it:

Assuming you already have a SqlCommand object set up:

public static DataTable GetDataTable(SqlCommand cmd)
{
    DataTable dt;

    using (SqlDataAdapter da = new SqlDataAdapter())
    {
        da.SelectCommand = cmd;
        dt = new DataTable();
        da.Fill(dt);
    }
    return dt;
}
Mitch Wheat
A: 

i just do not want to use DataAdapter to fill dataTable, cuz for each different table in DB, i have to write same code again and again.

if dot net dataTable class does not associated with actual table in DB, is there a product on market do that? a component, an open source project?

What you're looking for is called an ORM system. There are various free and open source ORM systems out there, NHibernate being the most popular. If you don't mind spending a little money, I've found OPF3 to be very good, as well.
David Brown