DataGridView.AutoGenerateColumns 속성

정의

DataSource 또는 DataMember 속성을 설정할 때 열이 자동으로 생성되는지 여부를 나타내는 값을 가져오거나 설정합니다.

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

속성 값

Boolean

열이 자동으로 생성되어야 하면 true이고, 그렇지 않으면 false입니다. 기본값은 true입니다.

특성

예제

다음 코드 예제에서는 수동으로 열을 추가하고 설정할 AutoGenerateColumns 때 데이터 원본에 바인딩하는 false방법을 보여 줍니다. 이 예제에서는 DataGridView 컨트롤이 비즈니스 개체 목록에 Task 바인딩됩니다. 그런 다음 열이 추가되고 속성을 통해 속성에 Task DataGridViewColumn.DataPropertyName 바인딩됩니다. 이 예제는 방법: Windows Forms DataGridViewComboBoxCell Drop-Down 목록의 개체에 액세스하는 방법에서 사용할 수 있는 더 큰 예제의 일부입니다.

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 DataSource 되거나 DataMember 변경되면 열이 자동으로 생성됩니다. 속성이 .로 변경 false true될 때 AutoGenerateColumns 열이 자동으로 생성될 수도 있습니다. 이 속성이 true 변경 DataSource 되어 이전 DataSource 값의 열과 일치하지 않는 열이 있는 경우 일치하지 않는 열의 데이터가 삭제됩니다. 또는 DataMember 속성이 설정되지 않은 경우 DataSource 이 속성은 무시됩니다.

설정true되면 AutoGenerateColumns 컨트롤은 DataGridView 데이터 원본에 있는 개체의 각 공용 속성에 대해 하나의 열을 생성합니다. 바인딩된 개체가 인터페이스를 구현하는 ICustomTypeDescriptor 경우 컨트롤은 메서드에서 반환 GetProperties 된 각 속성에 대해 하나의 열을 생성합니다. 각 열 머리글에는 열이 나타내는 속성 이름의 값이 포함됩니다.

속성을 설정 DataSource 하지만 설정 AutoGenerateColumns false하면 열을 수동으로 추가해야 합니다. 바인딩된 개체에 의해 노출되는 속성의 이름으로 속성을 설정 DataGridViewColumn.DataPropertyName 하여 추가된 각 열을 데이터 원본에 바인딩할 수 있습니다.

참고

DataSource Windows Forms 디자이너에서 설정하면 속성 falseAutoGenerateColumns 자동으로 설정되고 데이터 원본의 각 속성에 대한 열을 추가하고 바인딩하는 코드가 생성됩니다. 디자인 타임에 생성되는 코드는 다음 예제에 표시된 수동으로 추가된 코드와 동일합니다. 속성이 로 설정된 true경우 발생하는 AutoGenerateColumns 런타임 시 열의 자동 생성과는 다릅니다.

적용 대상

추가 정보