0
votes

I have a datatable filled with a report from a web service. I am now trying to display the datatable in an datagridview. This is the code I use to build the datatable:

// Create DataTabe to handle the output
DataTable dt = new DataTable();

dt.Clear();
dt.Columns.Add("EmployeeFirstName");
dt.Columns.Add("EmployeeLastName");
dt.Columns.Add("DepartmentName");
dt.Columns.Add("DepartmentCode");
dt.Columns.Add("LocationName");
dt.Columns.Add("DivisionCode");
dt.Columns.Add("EarningName");
dt.Columns.Add("OTHours");
dt.Columns.Add("WorkDate")

Fill the new datatable:

foreach (ReportRow row in report.Rows)
{
  dt.Rows.Add(string.Join(",", row.ColumnValues));
}

Then I try to bind the data in the datatable to the dataGridview:

dataGridView1.AutoGenerateColumns = true;
dataGridView1.DataSource = dt;
dataGridView1.Refresh();

When I run the application it only displays the data from the first column in the datatable. Do I need a loop of sorts to work through the columns or am I just missing a step?

3

3 Answers

0
votes

Yes that's cause you are adding only one value to your dt when you say dt.Rows.Add(string.Join(",", row.ColumnValues));. You should be doing something like below (assuming that ReportRow also has the columns with same names like "EmployeeFirstName" else change the names accordingly)

foreach (ReportRow row in report.Rows)
{
  DataRow dr = dt.NewRow();
  dr["EmployeeFirstName"] = row["EmployeeFirstName"];
  dr["EmployeeLastName"] = row["EmployeeLastName"];
  dr["DepartmentName"] = row["DepartmentName"];
  //rest of the columns fill

//once all columns filled
dt.Rows.Add(dr);
}
0
votes

dt.Rows.Add(string.Join(",", row.ColumnValues)); -> You can either add a single DataRow item or a array of objects.

From your call, you chose the later, you are adding a array of objects, except you are adding ONE SINGLE object.

string.Join(",", row.ColumnValues) is one object.

0
votes

Well after sleeping I have found the issue with dropping it into an sql table... I didn't take into account that the export to a CSV and the addition of the " , " would affect the export to sql. Here is the modification of the lines of code that was the issue:

  foreach (ReportRow row in report.Rows)
  {
      dt.Rows.Add(row.ColumnValues);
  }

Thank you all for your responses!