arrays and datagrids

  • Thread starter Thread starter alan
  • Start date Start date
A

alan

I wonder if someone could help me.

I've got a 2 Dimension Array that I'm working with and want to display
the results from this array in a datagrid.

I'm quite new to C# and seem unable to link the two together.

So, the question is, how do I set up my datagrid to accept the array
as the source?


Thanks,

Alan
 
The datagrid component can display automatically array but only of one
dimension.
If you want to display a 2 dimensional array you must use a datatable that
contain data of your array.
I wrote for you this little function that receive an array of title, a 2
dimensional array and return a datatable with data of your array.
Insert this code in a new WindowsApplication project with a datagrid named
dt and use it.

private DataTable createDT(string[] title, object[,] array)

{

int row = 0, col = 0;

DataTable dt = new DataTable("MyArray");

DataRow dr;

for(col = 0; col < title.GetLength(0); col++)

dt.Columns.Add(title[col]);

for(row = 0; row < array.GetLength(0); row++)

{

dr = dt.NewRow();

for(col = 0; col < array.GetLength(1); col++)

dr[title[col]] = array[row, col];

dt.Rows.Add(dr);

}

return dt;

}


Then modify the Form1_load in this manner

private void Form1_Load(object sender, System.EventArgs e)

{

string[] title = new string[] {"Colonna1", "Colonna2", "Colonna3",
"Colonna4", "Colonna5"};

string[,] myArray = new string[5,5];

for(int x = 0; x < 5; x++)

for(int y = 0; y < 5; y++)

myArray[x,y] = (x * y).ToString();

dg.SetDataBinding(createDT(title, (object[,])myArray), null);

}

If you have made all how you must you can now see your array in the
datagrid.
I hope of to be useful for you.
Excuse my english but im italian and i dont know a good englis.
 
Alan,

A jagged array isn't really a good candidate for data binding. Rather,
you should change your structure to a data table, and bind to that.

Two dimensional arrays can not be bound to by the data set. With a
jagged array, you have a one dimensional array whose elements are other one
dimensional arrays. Now you can bind to this, but you will see the
properties of each element of the first array, which is the properties for
an Array class.

Hope this helps.
 
Back
Top