Exporting dataTable to dataGridView, not working

1.2k Views Asked by At

I've been working on a project that takes two csv file as input, imported in dataTable. Now I wanted to join those two and finally show the joined one to a dataGridView.

The program is working fine till the import part.

The code that I've created so far does not show any error but it's not working, I mean, my destination Data Grid View remains blank.

Please observe the following code and provide some solution that works. Best regards.

P.S: I'm trying to do the Full Outer Join at here.

var tbl1 = tb1;
var tbl2 = tb2;
var res1 = from t2 in tbl2.AsEnumerable()
           join t1 in tbl1.AsEnumerable() on t2["BBL"] equals t1["BBL"] into g
           from t1 in g.DefaultIfEmpty()
           where t1 == null
           select t2;

dataGridView3.DataSource = res1;
2

There are 2 best solutions below

6
On

You must create your columns or copy the schema for res1.

Example:

res1.columns.Add("RowError",typeof(string));
9
On

The problem here is that res1 is a collection of DataRow and its non indexed properties are being rendered as columns.

Solution 1

You can select an anonymous type of object with the row's contents as its properties.

e.g.,

var tbl1 = tb1;
var tbl2 = tb2;
var res1 = from t2 in tbl2.AsEnumerable()
           join t1 in tbl1.AsEnumerable() on t2["BBL"] equals t1["BBL"] into g
           from t1 in g.DefaultIfEmpty()
           where t1 == null
           select new { Amount = t2["amount"], Payee = t2["payee"] };

where amount and payee are two columns in tb2.

If you set AutoGenerateColumns on dataGridView3 to true, then the names of the properties of this anonymous class (viz. Amount and Payee) will be used as column names.

Solution 2

As in your comment you said that you wanted to show all columns, so here is another less elegant solution (please leave your Linq expression as is):

foreach (DataColumn dCol in tbl1.Columns)
{
    dataGridView1.Columns.Add(dCol.ColumnName, dCol.Caption);
}

foreach (var s in res1)
{
    foreach (var item in res1)
    {
        dataGridView1.Rows.Add(item.ItemArray);
    }
}

You should remove the dataGridView3.DataSource = res1; if you go ahead with this approach.