有时,你会想仅显示在 Windows 窗体 DataGridView 控件中可用的某些列。 例如,你可能想要向具有管理凭据的用户显示员工工资列,同时将其隐藏给其他用户。 或者,你可能希望将控件绑定到一个包含许多列的数据源,然而你只想显示其中的一部分列。 在这种情况下,您通常会删除那些不需要显示的列,而不是简单地将它们隐藏。
在 DataGridView 控件中,Visible 属性值决定列是否显示。
Visual Studio 中支持此任务。 另请参阅 如何:使用设计器隐藏 Windows 窗体 DataGridView 控件中的列。
以编程方式隐藏列
将 DataGridViewColumn.Visible 属性设置为
false。 若要隐藏CustomerID在数据绑定期间自动生成的列,请将以下代码示例置于事件处理程序中 DataBindingComplete 。this.dataGridView1.Columns["CustomerID"].Visible = false;Me.dataGridView1.Columns("CustomerID").Visible = False
编译代码
此示例需要:
名为 DataGridView 的
dataGridView1控件,其包含一个名为CustomerID的列。对 System 和 System.Windows.Forms 程序集的引用。