TAGS :Viewed: 1 - Published at: a few seconds ago

[ How to initialize DataTable with empty rows of certain length? ]

I know how many rows and columns I want in my DataTable. Let it be rows X columns. How can I initilize database so there will be already enough space.

I want to do this for convienience. I want to be able to write: datasource.Rows[i].ItemArray[j] = "2"; where i and j are less then rows and columns and don't cause an exception.

var datasource = new System.Data.DataTable();

Answer 1


If you want to create a DataTable with x rows and y columns which is empty:

var datasource = new System.Data.DataTable();
int columns = 10;
int rows = 100;
for(int i = 0; i < columns; i++)
    datasource.Columns.Add();
string[] fields = new string[columns];
for(int i = 0; i < rows; i++)
    datasource.Rows.Add(fields);

Now this works for example:

datasource.Rows[25][6] = "2";

Note that it doesn't work via DataRow.ItemArray which you've shown in your question:

datasource.Rows[i].ItemArray[j] = "2" 

because the ItemArray property-getter returns a new object[], so it can be used only if you want to replace all fields in a row, therefore i've used the row-indexer: Rows[25][6].