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

更新:2007 年 11 月

DataGridView 控件以行模板为基础,通过数据绑定或在不指定要使用的现有行的情况下调用 DataGridViewRowCollection.Add 方法向控件中添加行。

RowsDefaultCellStyle 属性相比,行模板能更好地控制行的外观和行为。使用行模板,可以设置包括 DefaultCellStyle 在内的任何 DataGridViewRow 属性。

在有些情况中,必须使用行模板才能达到特殊效果。例如,不能在 DataGridViewCellStyle 中存储行高信息,因此必须使用行模板来更改所有行使用的默认高度。当您创建从 DataGridViewRow 派生的自己的类,并在向该控件添加新行时要使用自定义类型时,行模板也十分有用。

说明:

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

使用行模板

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

    With Me.dataGridView1.RowTemplate
        .DefaultCellStyle.BackColor = Color.Bisque
        .Height = 35
        .MinimumHeight = 20
    End With
    
    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;
    
    

编译代码

此示例需要:

请参见

概念

Windows 窗体 DataGridView 控件中的单元格样式

参考

DataGridView

DataGridViewCellStyle

DataGridViewRow

DataGridView.RowTemplate

其他资源

Windows 窗体 DataGridView 控件中的基本格式设置和样式设置