Samet Samet - 29 days ago 7
C# Question

How to create datatable with known numbers of columns and unknown numbers of rows in C#

I have 60 columns and unknown rows. I'm getting the datas continuously such as

Current.Cursor.Position.X
and
Current.Cursor.Position.Y
and many of them. So there is no unknown numbers of rows. I want to save these datas nicely. I dont want to be busy with db. I'm new on this topic. I tried to save them in a text file. I was successfull, but that wasn't in a order. I want to make it in order. What could be the perfect solution for this? If you can provide example codes, It will be perfect for me to understand better.

System.Data.DataTable DT = new System.Data.DataTable();

DT.Columns.Add( " 1 ");
DT.Columns.Add("Column2");
DT.Columns.Add("Column3");
DT.Columns.Add("Column60");


DT.Rows.Add(skeleton.Joints[JointID.Head].Position.X,skeleton.Joints[JointID.Head].Position.Y, skeleton.Joints[JointID.Head].Position.Z);


foreach (DataRow row in DT.Rows)
{

StreamWriter fileWriter = new StreamWriter("table.csv",true);
fileWriter.WriteLine(row[0].ToString() + row[1].ToString() + row[2].ToString());
fileWriter.Close();

}

Answer

This code should get you starting

//create an instance of a table
System.Data.DataTable DT = new System.Data.DataTable();
//dynamically add columns
DT.Columns.Add("Column1");
DT.Columns.Add("Column2");
DT.Columns.Add("Column3");
.
.
.
DT.Columns.Add("Column60");

//this is how you add rows to it
DT.Rows.Add("val1", "val2", "val3",...."val60");

//this is how you retrieve it
foreach (DataRow row in DT.Rows)
{
   Console.Writeline(row[0].toString()); //returns the first column for each iteration
}

Hope this was helpful to you.. dont forget to vote up