Recently, I had an requirement to save DataTable to multi-dimension string array.I googled but could not find everything in one place, so this post is the result of it.
Here is some data we will use for this example
ID | Name |
1 | aaa |
2 | bbb |
3 | ccc |
4 | ddd |
5 | eee |
Below is the function we will use to convert DataTable to string[,] array
public string[,] ConvertDataTableToArray(DataTable dt)
{
//Declare 2D-String array
string[,] arrString =
new string[dt.Rows.Count + 1, dt.Columns.Count];
int index = 0;
//Save ColumnName in 1st row of the array
foreach (DataColumn dc in dt.Columns)
{
arrString[0, index] =
Convert.ToString(dc.ColumnName);
index++;
}
//Reset Index
index = 0;
//Now save DataTable values in array,
//here we start from second row as ColumnNames are stored in first row
for (int row = 1; row < dt.Rows.Count + 1; row++)
{
for (int col = 0; col < dt.Columns.Count; col++)
{
arrString[row, col] =
Convert.ToString(dt.Rows[row – 1][col]);
}
}
//Return 2D-String Array
return arrString;
}
So now we have 2D-String Array converted from DataTable, but how to read values from this array, I leave it on readers to find out.
Hint:
To find total row and total columns in Multidimension Array we have to use .GetLength() method
NJoy!!!
Comments good as well as bad are most welcome.