views:

27

answers:

2

hi

Are there any other fast way to fill a Data table in ADO.Net without using Data adaptor.Fill method?

A: 

You can manually create DataTables and their content using the methods of the various types involved.

This does take a little code but is possible (I've done it from a custom serialisation in .NET 1.1 to populate a data source for a control that needed a DataSet).

[A more specific answer would really require knowing why you are interested in this.]

Richard
+3  A: 

Yes, you can. Here a short example:

var results = new DataTable();
using(var connection = new SqlConnection(...))
using(var command = connection.CreateCommand())
{
   command.Text = "sql statement";
   var parameter = command.CreateParameter();
   parameter.Name = "name";
   parameter.Value = aValue;
   command.Parameters.Add(parameter);

   connection.Open();
   results.Load(command.ExecuteReader());
}
return results;

If you just need to create a data table, e.g. for storing data not comming from a database, then you can create a new DataTable and populate it you self, like this:

var x = new DataTable("myTable");
x.Columns.Add("Field1", typeof(string));
x.Columns.Add("Field2", typeof(string));
x.Columns.Add("Field3", typeof(int));

x.Rows.Add("fred", "hugo", 1);
x.Rows.Add("fred", "hugo", 2);
x.Rows.Add("fred", "hugo", 3);
Obalix