HOW TO:移除 Windows Forms DataGridView 控制項中自動產生的資料行How to: Remove Autogenerated Columns from a Windows Forms DataGridView Control

當您DataGridView控制項設定為自動產生,根據其資料來源及其資料行時,您可以選擇性地省略某些資料行。When your DataGridView control is set to autogenerate its columns based on data from its data source, you can selectively omit certain columns. 您可以藉由呼叫Remove方法Columns集合。You can do this by calling the Remove method on the Columns collection. 或者,您可以從檢視的資料行設定隱藏Visible屬性設falseAlternatively, you can hide columns from view by setting the Visible property to false. 當您想要顯示隱藏的資料行,在某些情況下,或您需要存取而不會顯示它的資料行中的,這個技術非常有用。This technique is useful when you want to display the hidden columns in certain conditions, or when you need to access the data in the columns without displaying it.

若要移除自動產生的資料行To remove autogenerated columns

  • 呼叫Remove方法Columns集合。Call the Remove method on the Columns collection.

    dataGridView1.AutoGenerateColumns = true;
    dataGridView1.DataSource = customersDataSet;
    dataGridView1.Columns.Remove("Fax");
    
    With dataGridView1
        .AutoGenerateColumns = True
        .DataSource = customersDataSet
        .Columns.Remove("Fax")
    End With
    

若要隱藏自動產生的資料行To hide autogenerated columns

  • 設定的資料行Visible屬性設falseSet the column's Visible property to false.

    dataGridView1.Columns["CustomerID"].Visible = false;
    
    dataGridView1.Columns("CustomerID").Visible = False
    

範例Example

private void BindDataAndInitializeColumns()
{
    dataGridView1.AutoGenerateColumns = true;
    dataGridView1.DataSource = customersDataSet;
    dataGridView1.Columns.Remove("Fax");
    dataGridView1.Columns["CustomerID"].Visible = false;
}
Private Sub BindDataAndInitializeColumns()

    With dataGridView1
        .AutoGenerateColumns = True
        .DataSource = customersDataSet
        .Columns.Remove("Fax")
        .Columns("CustomerID").Visible = False
    End With

End Sub

編譯程式碼Compiling the Code

這個範例需要:This example requires:

  • ADataGridView控制項,名為dataGridView1繫結至資料表,其中包含FaxCustomerID資料行,例如CustomersNorthwind 範例資料庫中的資料表。A DataGridView control named dataGridView1 bound to a table that contains Fax and CustomerID columns, such as the Customers table in the Northwind sample database.

  • SystemSystem.Windows.Forms 組件的參考。References to the System and System.Windows.Forms assemblies.

另請參閱See also