DataGridView.AutoGenerateColumns 属性

定义

获取或设置一个值,该值指示在设置 DataSourceDataMember 属性时是否自动创建列。Gets or sets a value indicating whether columns are created automatically when the DataSource or DataMember properties are set.

public:
 property bool AutoGenerateColumns { bool get(); void set(bool value); };
[System.ComponentModel.Browsable(false)]
public bool AutoGenerateColumns { get; set; }
member this.AutoGenerateColumns : bool with get, set
Public Property AutoGenerateColumns As Boolean

属性值

如果应自动创建列,为 true;否则为 falsetrue if the columns should be created automatically; otherwise, false. 默认值为 trueThe default is true.

属性

示例

下面的代码示例演示如何在将 AutoGenerateColumns 设置为 @no__t 时,手动添加列并将它们绑定到数据源。The following code example demonstrates how to add columns manually and bind them to a data source when you set AutoGenerateColumns to false. 在此示例中,@no__t 0 的控件绑定到 @no__t 1 业务对象的列表。In this example, a DataGridView control is bound to a list of Task business objects. 然后,将添加列并通过 @no__t 属性将其绑定到 Task 属性。Then, columns are added and are bound to Task properties through the DataGridViewColumn.DataPropertyName property. 此示例摘自 [How 中提供的更大示例的一部分:访问 Windows 窗体 DataGridViewComboBoxCell 下拉列表 @ no__t-0 中的对象。This example is part of a larger example available in How to: Access Objects in a Windows Forms DataGridViewComboBoxCell Drop-Down List.

public class Form1 : Form
{
    private List<Employee> employees = new List<Employee>();
    private List<Task> tasks = new List<Task>();
    private Button reportButton = new Button();
    private DataGridView dataGridView1 = new DataGridView();

    [STAThread]
    public static void Main()
    {
        Application.Run(new Form1());
    }

    public Form1()
    {
        dataGridView1.Dock = DockStyle.Fill;
        dataGridView1.AutoSizeColumnsMode = 
            DataGridViewAutoSizeColumnsMode.AllCells;
        reportButton.Text = "Generate Report";
        reportButton.Dock = DockStyle.Top;
        reportButton.Click += new EventHandler(reportButton_Click);

        Controls.Add(dataGridView1);
        Controls.Add(reportButton);
        Load += new EventHandler(Form1_Load);
        Text = "DataGridViewComboBoxColumn Demo";
    }

    // Initializes the data source and populates the DataGridView control.
    private void Form1_Load(object sender, EventArgs e)
    {
        PopulateLists();
        dataGridView1.AutoGenerateColumns = false;
        dataGridView1.DataSource = tasks;
        AddColumns();
    }

    // Populates the employees and tasks lists. 
    private void PopulateLists()
    {
        employees.Add(new Employee("Harry"));
        employees.Add(new Employee("Sally"));
        employees.Add(new Employee("Roy"));
        employees.Add(new Employee("Pris"));
        tasks.Add(new Task(1, employees[1]));
        tasks.Add(new Task(2));
        tasks.Add(new Task(3, employees[2]));
        tasks.Add(new Task(4));
    }

    // Configures columns for the DataGridView control.
    private void AddColumns()
    {
        DataGridViewTextBoxColumn idColumn = 
            new DataGridViewTextBoxColumn();
        idColumn.Name = "Task";
        idColumn.DataPropertyName = "Id";
        idColumn.ReadOnly = true;

        DataGridViewComboBoxColumn assignedToColumn = 
            new DataGridViewComboBoxColumn();

        // Populate the combo box drop-down list with Employee objects. 
        foreach (Employee e in employees) assignedToColumn.Items.Add(e);

        // Add "unassigned" to the drop-down list and display it for 
        // empty AssignedTo values or when the user presses CTRL+0. 
        assignedToColumn.Items.Add("unassigned");
        assignedToColumn.DefaultCellStyle.NullValue = "unassigned";

        assignedToColumn.Name = "Assigned To";
        assignedToColumn.DataPropertyName = "AssignedTo";
        assignedToColumn.AutoComplete = true;
        assignedToColumn.DisplayMember = "Name";
        assignedToColumn.ValueMember = "Self";

        // Add a button column. 
        DataGridViewButtonColumn buttonColumn = 
            new DataGridViewButtonColumn();
        buttonColumn.HeaderText = "";
        buttonColumn.Name = "Status Request";
        buttonColumn.Text = "Request Status";
        buttonColumn.UseColumnTextForButtonValue = true;

        dataGridView1.Columns.Add(idColumn);
        dataGridView1.Columns.Add(assignedToColumn);
        dataGridView1.Columns.Add(buttonColumn);

        // Add a CellClick handler to handle clicks in the button column.
        dataGridView1.CellClick +=
            new DataGridViewCellEventHandler(dataGridView1_CellClick);
    }

    // Reports on task assignments. 
    private void reportButton_Click(object sender, EventArgs e)
    {
        StringBuilder report = new StringBuilder();
        foreach (Task t in tasks)
        {
            String assignment = 
                t.AssignedTo == null ? 
                "unassigned" : "assigned to " + t.AssignedTo.Name;
            report.AppendFormat("Task {0} is {1}.", t.Id, assignment);
            report.Append(Environment.NewLine);
        }
        MessageBox.Show(report.ToString(), "Task Assignments");
    }

    // Calls the Employee.RequestStatus method.
    void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
    {
        // Ignore clicks that are not on button cells. 
        if (e.RowIndex < 0 || e.ColumnIndex !=
            dataGridView1.Columns["Status Request"].Index) return;

        // Retrieve the task ID.
        Int32 taskID = (Int32)dataGridView1[0, e.RowIndex].Value;

        // Retrieve the Employee object from the "Assigned To" cell.
        Employee assignedTo = dataGridView1.Rows[e.RowIndex]
            .Cells["Assigned To"].Value as Employee;

        // Request status through the Employee object if present. 
        if (assignedTo != null)
        {
            assignedTo.RequestStatus(taskID);
        }
        else
        {
            MessageBox.Show(String.Format(
                "Task {0} is unassigned.", taskID), "Status Request");
        }
    }

}
Public Class Form1
    Inherits Form

    Private employees As New List(Of Employee)
    Private tasks As New List(Of Task)
    Private WithEvents reportButton As New Button
    Private WithEvents dataGridView1 As New DataGridView

    <STAThread()> _
    Public Sub Main()
        Application.Run(New Form1)
    End Sub

    Sub New()
        dataGridView1.Dock = DockStyle.Fill
        dataGridView1.AutoSizeColumnsMode = _
            DataGridViewAutoSizeColumnsMode.AllCells
        reportButton.Text = "Generate Report"
        reportButton.Dock = DockStyle.Top

        Controls.Add(dataGridView1)
        Controls.Add(reportButton)
        Text = "DataGridViewComboBoxColumn Demo"
    End Sub

    ' Initializes the data source and populates the DataGridView control.
    Private Sub Form1_Load(ByVal sender As Object, _
        ByVal e As EventArgs) Handles Me.Load

        PopulateLists()
        dataGridView1.AutoGenerateColumns = False
        dataGridView1.DataSource = tasks
        AddColumns()

    End Sub

    ' Populates the employees and tasks lists. 
    Private Sub PopulateLists()
        employees.Add(New Employee("Harry"))
        employees.Add(New Employee("Sally"))
        employees.Add(New Employee("Roy"))
        employees.Add(New Employee("Pris"))
        tasks.Add(New Task(1, employees(1)))
        tasks.Add(New Task(2))
        tasks.Add(New Task(3, employees(2)))
        tasks.Add(New Task(4))
    End Sub

    ' Configures columns for the DataGridView control.
    Private Sub AddColumns()

        Dim idColumn As New DataGridViewTextBoxColumn()
        idColumn.Name = "Task"
        idColumn.DataPropertyName = "Id"
        idColumn.ReadOnly = True

        Dim assignedToColumn As New DataGridViewComboBoxColumn()

        ' Populate the combo box drop-down list with Employee objects. 
        For Each e As Employee In employees
            assignedToColumn.Items.Add(e)
        Next

        ' Add "unassigned" to the drop-down list and display it for 
        ' empty AssignedTo values or when the user presses CTRL+0. 
        assignedToColumn.Items.Add("unassigned")
        assignedToColumn.DefaultCellStyle.NullValue = "unassigned"

        assignedToColumn.Name = "Assigned To"
        assignedToColumn.DataPropertyName = "AssignedTo"
        assignedToColumn.AutoComplete = True
        assignedToColumn.DisplayMember = "Name"
        assignedToColumn.ValueMember = "Self"

        ' Add a button column. 
        Dim buttonColumn As New DataGridViewButtonColumn()
        buttonColumn.HeaderText = ""
        buttonColumn.Name = "Status Request"
        buttonColumn.Text = "Request Status"
        buttonColumn.UseColumnTextForButtonValue = True

        dataGridView1.Columns.Add(idColumn)
        dataGridView1.Columns.Add(assignedToColumn)
        dataGridView1.Columns.Add(buttonColumn)

    End Sub

    ' Reports on task assignments. 
    Private Sub reportButton_Click(ByVal sender As Object, _
        ByVal e As EventArgs) Handles reportButton.Click

        Dim report As New StringBuilder()
        For Each t As Task In tasks
            Dim assignment As String
            If t.AssignedTo Is Nothing Then
                assignment = "unassigned"
            Else
                assignment = "assigned to " + t.AssignedTo.Name
            End If
            report.AppendFormat("Task {0} is {1}.", t.Id, assignment)
            report.Append(Environment.NewLine)
        Next
        MessageBox.Show(report.ToString(), "Task Assignments")

    End Sub

    ' Calls the Employee.RequestStatus method.
    Private Sub dataGridView1_CellClick(ByVal sender As Object, _
        ByVal e As DataGridViewCellEventArgs) _
        Handles dataGridView1.CellClick

        ' Ignore clicks that are not on button cells. 
        If e.RowIndex < 0 OrElse Not e.ColumnIndex = _
            dataGridView1.Columns("Status Request").Index Then Return

        ' Retrieve the task ID.
        Dim taskID As Int32 = CInt(dataGridView1(0, e.RowIndex).Value)

        ' Retrieve the Employee object from the "Assigned To" cell.
        Dim assignedTo As Employee = TryCast(dataGridView1.Rows(e.RowIndex) _
            .Cells("Assigned To").Value, Employee)

        ' Request status through the Employee object if present. 
        If assignedTo IsNot Nothing Then
            assignedTo.RequestStatus(taskID)
        Else
            MessageBox.Show(String.Format( _
                "Task {0} is unassigned.", taskID), "Status Request")
        End If

    End Sub

End Class

注解

如果将此属性设置为 true,并设置或更改 @no__t 或 DataMember 属性,则会自动生成列。Columns are automatically generated when this property is set to true and the DataSource or DataMember properties are set or changed. AutoGenerateColumns 属性从 @no__t 更改为 true 时,还可以自动生成列。Columns can also be automatically generated when the AutoGenerateColumns property is changed from false to true. 如果此属性 true,并且 DataSource 发生更改,因此存在与以前 DataSource 值的列不匹配的列,则将放弃不匹配列中的数据。If this property is true and the DataSource changes so there are columns that do not match the columns of the previous DataSource value, data in the unmatched columns is discarded. 如果未设置 DataSource 或 @no__t 属性,则忽略此属性。This property is ignored if the DataSource or DataMember properties are not set.

如果 @no__t 设置为 true,则 @no__t 2 控件将为数据源中的对象的每个公共属性生成一列。When AutoGenerateColumns is set to true, the DataGridView control generates one column for each public property of the objects in the data source. 如果绑定对象实现 ICustomTypeDescriptor 接口,则该控件会为 GetProperties 方法返回的每个属性生成一列。If the bound objects implement the ICustomTypeDescriptor interface, the control generates one column for each property returned by the GetProperties method. 每个列标题将包含列所表示的属性名称的值。Each column header will contain the value of the property name the column represents.

如果设置了 DataSource 属性,但将 @no__t 设置为 false,则必须手动添加列。If you set the DataSource property but set AutoGenerateColumns to false, you must add columns manually. 可以通过将 DataGridViewColumn.DataPropertyName 属性设置为绑定对象公开的属性名称,将每个已添加的列绑定到数据源。You can bind each added column to the data source by setting the DataGridViewColumn.DataPropertyName property to the name of a property exposed by the bound objects.

备注

设置 Windows 窗体设计器中的 @no__t 0 会自动将 @no__t 属性设置为 false,并为数据源中的每个属性生成代码以添加和绑定列。Setting the DataSource in the Windows Forms Designer automatically sets the AutoGenerateColumns property to false and generates code to add and bind a column for each property in the data source. 在设计时生成的代码等效于下面的示例中所示的手动添加的代码。The code that is generated at design-time is equivalent to the manually added code shown in the following example. 这不同于在运行时自动生成列,这是在 AutoGenerateColumns 属性设置为 true 时发生的。It is not the same as the auto-generation of columns at run-time that occurs when the AutoGenerateColumns property is set to true.

适用于

另请参阅