如何:使用行模板在 Windows 窗体 DataGridView 控件中自定义行

DataGridView 控件使用行模板作为所有行的基础,该模板通过数据绑定或在未指定要使用的现有行的情况下调用 DataGridViewRowCollection.Add 方法时添加到控件。

与提供的 RowsDefaultCellStyle 属性相比,行模板可让你更好地控制行的外观和行为。 使用行模板,可设置任何 DataGridViewRow 属性,包括 DefaultCellStyle

在某些情况下,必须使用行模板才能实现特定效果。 例如,不能将行高信息存储在 DataGridViewCellStyle 中,因此必须使用行模板来更改所有行使用的默认高度。 当创建自己的从 DataGridViewRow 派生的类并且希望在将新行添加到控件时使用自定义类型时,行模板也很有用。

注意

仅在添加行时,才使用行模板。 不能通过更改行模板来更改现有行。

使用行模板

  • 设置从 DataGridView.RowTemplate 属性检索到的对象的属性。

    DataGridViewRow^ row = this->dataGridView1->RowTemplate;
    row->DefaultCellStyle->BackColor = Color::Bisque;
    row->Height = 35;
    row->MinimumHeight = 20;
    
    
    DataGridViewRow row = this.dataGridView1.RowTemplate;
    row.DefaultCellStyle.BackColor = Color.Bisque;
    row.Height = 35;
    row.MinimumHeight = 20;
    
    With Me.dataGridView1.RowTemplate
        .DefaultCellStyle.BackColor = Color.Bisque
        .Height = 35
        .MinimumHeight = 20
    End With
    

编译代码

此示例需要:

另请参阅