Binding a Two Dimensional Array to a DataGrid






3.55/5 (38 votes)
Jan 9, 2004
1 min read

386850

12837
Binding a two dimensional array to a DataGrid
Introduction
Data binding refers to the process of automatically setting properties of one or more form controls at run time from a structure that contains data. More interesting point is binding of custom objects; one of these cases is binding of two dimensional arrays to DataGrid
.
The thing is little bit tricky, but in general, it consists of implementing some classes which represent view of the data and they in order need to implement ending list of interfaces.
Here, you can see interfaces and internal class structure of the library.
Using the Code
It is very simple.
//
// 1. Create two dimensional array
//
const int dim = 1000;
double[,] array = new double[dim,dim];
Random ran = new Random();
for(int r = 0; r < dim; r++)
{
for(int c = 0; c < dim; c++)
{
array[r,c] = (ran.Next(dim)); // fill it with random numbers.
}
}
// 2. Create ArrayDataView class in which
// constructor you pass the array
// and assign it to DataSource property of DataGrid.
dataGrid1.DataSource = new ArrayDataView(array);
When you change data in array and want to see update in DataGrid
, you need to call Reset
method of ArrayDataView
class. You can use all kinds of base types like double
, int32
, string
and so on.
In addition, there is a constructor with additional parameter which is array of column names, length must be equal to columns of the array, if not, exception is raised.
History
- 7th January, 2004: Created
- 29th January, 2004: Source code of library added
License
This article has no explicit license attached to it, but may contain usage terms in the article text or the download files themselves. If in doubt, please contact the author via the discussion board below. A list of licenses authors might use can be found here.