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

标签 c# .net datagridview

我正在尝试运行这段代码,但出现异常:

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 中手动创建了列,现在我想使用这个小方法填充字段。

最佳答案

你只漏了一行:-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);

关于c# - 如何手动将数据添加到 dataGridView?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6092463/

相关文章:

vb.net - DataGridView - 如何卡住一列?

c# - 通过Wireshark检查Mysql查询进程

c# - Windows Server 2008 R2 上的 WPF 样式

.net - 使用 XmlAttributeOverrides 预编译 XmlSerializer

c# - 任何用于 .NET 的 NIO 框架?

vb.net - vb.net Datagridview 中的一列不应允许粘贴非整数

c# - public IEnumerator GetEnumerator() 的返回类型?

c# - 如何在 C# 控制台应用程序中计算正确?

c# - 记录操作延迟

c# - 如何更改 winform DataGridview 标题的颜色?