如何手动将数据添加到dataGridView?

Onl*_*ere 10 .net c# datagridview

我正在尝试运行此代码,我得到一个例外:

指数超出范围.必须是非负数且小于集合的大小.参数名称: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++;
    }
}
Run Code Online (Sandbox Code Playgroud)

我在datagridview中手动创建了列,现在我想使用这个小方法填充字段.

小智 28

你只是错过了一行:-P

DataGridViewRow row = new DataGridViewRow();
row.CreateCells(dataGridView1);  // this line was missing
row.Cells[0].Value = "Cell1";
row.Cells[1].Value = "Cell2";
dataGridView1.Rows.Add(row);
Run Code Online (Sandbox Code Playgroud)

  • 这个答案依赖于程序员在表单上的 DataGridView 实例中定义了列(称为“dataGridView1”)。对 CreateCells 方法的调用依赖于此定义来设置新行的列。对于寻求完全编程方式定义 DataGridView 的人来说,您首先需要定义列。请参阅SO @ http://stackoverflow.com/questions/5524075/programatically-add-new-column-to-datagridview (2认同)

Nik*_*raj 7

这很简单,

myDataGridView.Rows.Add(value1, value2, value3...);
Run Code Online (Sandbox Code Playgroud)

当我通过GUI为先前的数据列配置我的DGV时,它工作正常.所以在你的情况下,它会像:

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)
    {
        dataGridView1.Rows.Add(i.ToString(), student.LastNameFather + " " + student.LastNameMother + ", " + student.Name);
        i++;
    }
}
Run Code Online (Sandbox Code Playgroud)

您可能需要分别为列及其名称配置DGV.


Mam*_*a D 3

新创建的行中有 0 个单元格,这就是您收到该异常的原因。你不能使用类似的语句

row.Cells[0].Value = i.ToString();
Run Code Online (Sandbox Code Playgroud)

除非您手动将单元格添加到空白行。