0

What's the fastest way in term of speed of coding to add rows to a DataTable? I don't need to know neither the name of columns nor datatype. Is it possible to add rows without previously specify the number or name of dataTable columns?

        DataTable t = new DataTable();
        t.Rows.Add(value1,
            value1,
            value2,
            value3,
            ...
            valueN
            );
        DataSet ds = new DataSet();
        ds.Tables.Add(t);
3
  • Fast? in term of speed of execution, speed of coding, speed of rendering? Commented Nov 15, 2012 at 15:45
  • N values, string and decimals. Commented Nov 15, 2012 at 15:45
  • @SteveB Speed of coding. Commented Nov 15, 2012 at 15:47

3 Answers 3

1

If the input comes out of a collection, you could loop it to create the DataColumns with the correct type:

var data = new Object[] { "A", 1, 'B', 2.3 };
DataTable t = new DataTable();
// create all DataColumns
for (int i = 0; i < data.Length; i++)
{
    t.Columns.Add(new DataColumn("Column " + i, data[i].GetType()));
}
// add the row to the table
t.Rows.Add(data);
Sign up to request clarification or add additional context in comments.

Comments

1

To answer your first question: no, you have to have columns defined on the table. You can't just say, "Hey, make a column for all these values." Nothing stopping you from creating columns on the fly, though, as Mr. Schmelter says.

Comments

0

Without knowing the rows or columns (you first need to add columns, without that not possible)

 for(int intCount = 0;intCount < dt.Rows.Count; intCount++)
 {
  for(int intSubCount = 0; intSubCount < dt.Columns.Count; intSubCount++)
   {
         dt.Rows[intCount][intSubCount] = yourValue; // or assign to something
   }
 }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.