private void Initial_Table(DataGridView dataGridView, string[] columnsNames)
{
dataGridView.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
dataGridView.BackgroundColor = Color.White;
dataGridView.AllowUserToResizeRows = false;//不可改变行高
dataGridView.AllowUserToAddRows = false;//不允许用户自己添加行,否则总是在表格中存在一行可以编辑的行
dataGridView.ReadOnly = true;//不可编辑
int columns = columnsNames.Length;
dataGridView.ColumnCount = columns;
for (int i = 0; i < columns; i++)
{
dataGridView.Columns[i].HeaderText = columnsNames[i];
dataGridView.Columns[i].SortMode = DataGridViewColumnSortMode.NotSortable;//禁止列的元素进行排序
}
}
private void AddRow<T>(DataGridView dataGridView, List<T > rows)
{
foreach ( var item in rows)
{
Student student = item as Student;
if(student !=null)
{
object[] obj = { student.Name, student.Age, student.Gender };
dataGridView.Rows.Add(obj);
}
}
}
private void ClearRows(DataGridView dataGridView )
{
dataGridView.Rows.Clear();
}
class Student
{
public Student(string name, int age, char gender)
{
this.Name = name;
this.Age = age;
this.Gender = gender;
}
public string Name { get; set; }
public int Age { get; set; }
public char Gender { get; set; }
}
调用:
Initial_Table(dataGridView1, new string[] { "Name", "Age", "Gender" });
List<Student> students = new List<Student>() { new Student("小王", 3, '男') , new Student("小李", 3, '女') , new Student("小宋", 30, '女') };
AddRow<Student>(dataGridView1 ,students );
输出: