Reputation: 1901
I'm trying to add data manually to a DataGridView (displaying a grid view of a student's attendance for the year). The problem is, when I add a row of data to the DataGridView instead of a new row being created and the data being added to it. A new blank row is made and the data is added to the top row. Here is the relevant code:
foreach (IndividualAttendanceRecord rec in DatabaseInterfacer.GetRecords("pi404"))
{
if (dataGrid.ColumnCount < rec.Attendance.Count)
dataGrid.ColumnCount = rec.Attendance.Count;
List<String> row = new List<string>();
foreach (string entry in rec.Attendance)
row.Add(entry);
string[] rowArray = row.ToArray<string>();
dataGrid.Rows.Add(rowArray);
}
Doing this code makes a DataGridView with all the data in one line, then two blank lines at the bottom.
Any help?
EDIT: Still completely stumped on this. I've simplified my code and added a few test rows to the foreach statement and I don't understand why it's outputting the way it is at all. Here is my new code:
foreach (IndividualAttendanceRecord rec in DatabaseInterfacer.GetRecords("pi404"))
{
if (dataGrid.ColumnCount < rec.Attendance.Count)
dataGrid.ColumnCount = rec.Attendance.Count;
string[] row = rec.Attendance.ToArray<string>();
dataGrid.Rows.Add(row);
dataGrid.Rows.Add("1", "2", "3");
dataGrid.Rows.Add("One", "Two", "Three");
}
And here is what it outputs: https://i.sstatic.net/JG63O.png
I don't see why it is still putting all the information in the IndividualAttendanceRecord in a single line on it's own, and then creating a blank line and puting the "1 2 3" and "one two three".
Can anyone see why this is happening? I'm probably being really stupid.
Upvotes: 0
Views: 1162
Reputation: 1901
I looked through the rest of my code and found the problem. There was no problem with the display code, the problem was actually in the database. For some reason all the data was actually in one line of the database with two blank lines underneath.
Upvotes: 0
Reputation: 125197
The control is showing what you said to show:
First you said to grid to create some columns by setting ColumnCount
to the count of items of your list:
dataGrid.ColumnCount = rec.Attendance.Count;
Then you add a row containing some values using Add( params object[] values)
method. when you pass an array to the method, it will adds a row and use those values as columns:
string[] rowArray = row.ToArray<string>();
dataGrid.Rows.Add(rowArray);
If you want to added all values in a single column, as an option you can:
dataGrid.ColumnCount = 1;
foreach (string entry in rec.Attendance)
dataGrid.Rows.Add(entry);
Upvotes: 1