Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to initialize DataTable with empty rows of certain length?

Tags:

c#

.net

datatable

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();
like image 668
Yoda Avatar asked Mar 17 '26 10:03

Yoda


1 Answers

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].

like image 88
Tim Schmelter Avatar answered Mar 19 '26 00:03

Tim Schmelter



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!