C#动态添加DataGridViewRow故障
本文关键字:故障 DataGridViewRow 添加 动态 | 更新日期: 2023-09-27 18:25:04
我有一个程序,可以在特定条件下动态添加行,我尝试用这种方式实现函数:
if (student.UUID == AppliedStudent)
{
using (DataGridViewRow row = new DataGridViewRow())
{
row.SetValues(new object[] { lesson.Name, Course.Course_Name, lesson.Level, lesson.Time, Teacher.C_Name, lesson.Price, Classroom.Classroom_Name });
row.DefaultCellStyle.BackColor = Color.LightGreen;
row.DefaultCellStyle.SelectionBackColor = Color.SkyBlue;
dataGridView1.Rows.Add(row);
}
}
有了这段代码,它确实可以添加行,但它们都是空的,所有这些行都没有数据。(已经确认lesson
、course
和Teacher
不是null
。)有人能帮忙吗?谢谢
我终于自己想好了,我把row.SetValues
换成了row.CreateCells
:
if (student.UUID == AppliedStudent)
{
DataGridViewRow row = new DataGridViewRow();
row.CreateCells(dataGridView1, lesson.Name, Course.Course_Name, lesson.Level, lesson.Time, Teacher.C_Name, lesson.Price, Classroom.Classroom_Name);
row.DefaultCellStyle.BackColor = Color.LightGreen;
row.DefaultCellStyle.SelectionBackColor = Color.SkyBlue;
dataGridView1.Rows.Add(row);
}
使用此代码,它将运行良好。感谢大家的帮助!
您需要省略using
部分。之后将处理row
对象:
if (student.UUID == AppliedStudent)
{
DataGridViewRow row = new DataGridViewRow();
row.SetValues(new object[] { lesson.Name, Course.Course_Name, lesson.Level, lesson.Time, Teacher.C_Name, lesson.Price, Classroom.Classroom_Name });
row.DefaultCellStyle.BackColor = Color.LightGreen;
row.DefaultCellStyle.SelectionBackColor = Color.SkyBlue;
dataGridView1.Rows.Add(row);
}