Windows 窗体 DataGrid 控件添加表和列

来源:互联网 发布:视频聊天软件 编辑:程序博客网 时间:2024/05/12 21:51
Windows 窗体 DataGrid 控件添加表和列
===========================================================

通过创建 DataGridTableStyle 对象,并将它们添加到 GridTableStylesCollection 对象(通过 DataGrid 控件的 TableStyles 属性访问),可以表和列的形式在 Windows 窗体 DataGrid 控件中显示数据。每个表样式显示在 DataGridTableStyle 对象的 MappingName 属性中指定的任意数据表的内容。默认情况下,未指定列样式的表样式将显示该数据表中的所有列。通过将 DataGridColumnStyle 对象添加到 GridColumnStylesCollection 对象(通过各 DataGridTableStyle 对象的 GridColumnStyles 属性访问),可以限制所显示的表中的列。

在设计器中向 DataGrid 控件添加表

为在表中显示数据,必须首先将 DataGrid 控件绑定到数据集。有关更多信息,请参阅将 Windows 窗体 DataGrid 控件绑定到数据源。
在“属性”窗口中选择 DataGrid 控件的 TableStyles 属性,然后单击该属性旁边的省略号按钮 (),即可显示 DataGridTableStyle 集合编辑器。
在集合编辑器中,单击“添加”按钮以插入表样式。
单击“确定”关闭集合编辑器,然后单击 TableStyles 属性旁边的省略号按钮将其重新打开。
在重新打开集合编辑器后,绑定到该控件的所有数据表都会显示在该表样式的 MappingName 属性的下拉列表中。

在集合编辑器的“成员”框中,单击该表样式。
在集合编辑器的“属性”框中,选择要显示的表的 MappingName 值。
在设计器中向 DataGrid 控件添加列

在 DataGridTableStyle 集合编辑器的“成员”框中,选择适当的表样式。在集合编辑器的“属性”框中,选择 GridColumnStyles 集合,然后单击该属性旁边的省略号按钮()以显示 DataGridColumnStyle 集合编辑器。
在集合编辑器中,单击“添加”按钮以插入列样式或单击“添加”按钮旁边的向下箭头以指定列类型。下拉框将允许您选择“DataGridTextBoxColumn”或“DataGridBoolColumn”类型。
单击“确定”以关闭 DataGridColumnStyle 集合编辑器,然后单击 GridColumnStyles 属性旁边的省略号按钮将其重新打开。
在重新打开集合编辑器后,绑定数据表中的所有数据列都会显示在该列样式的 MappingName 属性的下拉列表中。

在集合编辑器的“成员”框中,单击该列样式。
在集合编辑器的“属性”框中,选择要显示的列的 MappingName 值。
以编程方式向 DataGrid 添加表和列

警告 当以编程方式指定列样式时,在向 GridTableStylesCollection 对象添加 DataGridTableStyle 对象之前,请务必先创建 DataGridColumnStyle 对象并将其添加到 GridColumnStylesCollection 对象中。当将空的 DataGridTableStyle 对象添加到集合时,会自动生成 DataGridColumnStyle 对象。因此,如果试图向 GridColumnStylesCollection 对象添加具有重复的 MappingName 值的新 DataGridColumnStyle 对象,则会引发异常。
为在表中显示数据,必须首先将 DataGrid 控件绑定到数据集。有关更多信息,请参阅将 Windows 窗体 DataGrid 控件绑定到数据源。
声明新的表样式并设置其映射名称。
'Visual Basic
Dim ts1 as New DataGridTableStyle()
ts1.MappingName = "Customers"

// C#
DataGridTableStyle ts1 = new DataGridTableStyle();
ts1.MappingName = "Customers";
声明新的列样式并设置其映射名称及其他属性。
'Visual Basic
Dim myDataCol As New DataGridBoolColumn()
myDataCol.HeaderText = "My New Column"
myDataCol.MappingName = "Current"

// C#
DataGridBoolColumn myDataCol = new DataGridBoolColumn();
myDataCol.HeaderText = "My New Column";
myDataCol.MappingName = "Current";
调用 GridColumnStylesCollection 对象的 Add 方法以将该列添加到表样式中
'Visual Basic
ts1.GridColumnStyles.Add(myDataCol)

// C#
ts1.GridColumnStyles.Add(myDataCol);
调用 GridTableStylesCollection 对象的 Add 方法以将表样式添加到数据网格中。
'Visual Basic
DataGrid1.TableStyles.Add(ts1)

// C#
dataGrid1.TableStyles.Add(ts1); 

原创粉丝点击