我有一个程序会在某些条件下动态添加行,我尝试以这种方式实现该功能:
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
。)任何人都可以提供帮助吗?谢谢!
答案 0 :(得分:3)
我终于自己弄明白了,我将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);
}
使用此代码可以很好地工作。谢谢大家的帮助!
答案 1 :(得分:2)
您需要省略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);
}