Thursday, April 5, 2007

Matrix Derived from 2 DataTables

My latest project required the creation of a matrix derived from two DataTables, DT1 and DT2, returned from two separate stored procedures. It was an interesting problem and took me a couple days to come up with a solution. Basically, I had to create a temporary table or matrix, DT, with the top row being the data returned from DT1 and the left-most column being the data returned from DT2.

Then, I initialized the PrimaryKey property of DT as follows:

DataColumn[] keys = new DataColumn[1];
keys[0] = DT.Columns["column_name"];
DT.PrimaryKey = keys;

The initialization of PrimaryKey was required, because I wanted to a search in DT and populate its cells as follows:

DataRow dr = DT.Rows.Find("search_string");
dr["column_name"] = "cell_value";

It is interesting to note that as the DataRow dr is changed, DT is also changed, because dr is a reference to a row in DT.

The last step was to bind DT the DataSource property of the DataGrid and execute its DataBind() event.

I also had to generate a CVS file for DT to be downloaded.

Here is a screenshot of the report:

Report

No comments: