如何手动将数据添加到 dataGridView? [英] How can I manually add data to a dataGridView?
本文介绍了如何手动将数据添加到 dataGridView?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试运行此代码,但出现异常:
I'm trying to run this code, and I get an exception:
索引超出范围.必须是非负且小于集合.参数名称:index
Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index
private void LoadStudentGrades(int gradeParaleloId, int subjectId)
{
GradeStudentRepository gradeStudentRepo = new GradeStudentRepository();
students = gradeStudentRepo.FindAllGradeStudents().Where(g => g.GradeParaleloId == gradeParaleloId)
.Select(g => g.Student);
int i = 1;
foreach (var student in students)
{
DataGridViewRow row = new DataGridViewRow();
row.Cells[0].Value = i.ToString();
row.Cells[1].Value = student.LastNameFather + " " + student.LastNameMother + ", " + student.Name;
dataGridView1.Rows.Add(row);
i++;
}
}
我在 datagridview 中手动创建了列,现在我想使用这个小方法填充字段.
I manually created the columns in the datagridview, and now I would like to populate the fields using this small method.
推荐答案
新创建的行中有 0 个单元格,这就是您收到该异常的原因.你不能使用像
There are 0 cells in the newly created row, that's why you are getting that exception. You cannot use statements like
row.Cells[0].Value = i.ToString();
除非您手动将单元格添加到空白行.
unless you manually add cells to the blank row.
这篇关于如何手动将数据添加到 dataGridView?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文