Edit

Share via


How to: Access Objects in a Windows Forms DataGridViewComboBoxCell Drop-Down List

Like the ComboBox control, the DataGridViewComboBoxColumn and DataGridViewComboBoxCell types enable you to add arbitrary objects to their drop-down lists. With this feature, you can represent complex states in a drop-down list without having to store corresponding objects in a separate collection.

Unlike the ComboBox control, the DataGridView types do not have a SelectedItem property for retrieving the currently selected object. Instead, you must set the DataGridViewComboBoxColumn.ValueMember or DataGridViewComboBoxCell.ValueMember property to the name of a property on your business object. When the user makes a selection, the indicated property of the business object sets the cell Value property.

To retrieve the business object through the cell value, the ValueMember property must indicate a property that returns a reference to the business object itself. Therefore, if the type of the business object is not under your control, you must add such a property by extending the type through inheritance.

The following procedures demonstrate how to populate a drop-down list with business objects and retrieve the objects through the cell Value property.

To add business objects to the drop-down list

  1. Create a new DataGridViewComboBoxColumn and populate its Items collection. Alternatively, you can set the column DataSource property to the collection of business objects. In that case, however, you cannot add "unassigned" to the drop-down list without creating a corresponding business object in your collection.

    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";
    
  2. Set the DisplayMember and ValueMember properties. DisplayMember indicates the property of the business object to display in the drop-down list. ValueMember indicates the property that returns a reference to the business object.

    assignedToColumn.DisplayMember = "Name";
    assignedToColumn.ValueMember = "Self";
    
  3. Make sure that your business object type contains a property that returns a reference to the current instance. This property must be named with the value assigned to ValueMember in the previous step.

    public Employee Self
    {
        get { return this; }
    }
    

To retrieve the currently selected business object

  • Get the cell Value property and cast it to the business object type.

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

Example

The complete example demonstrates the use of business objects in a drop-down list. In the example, a DataGridView control is bound to a collection of Task objects. Each Task object has an AssignedTo property that indicates the Employee object currently assigned to that task. The Assigned To column displays the Name property value for each assigned employee, or "unassigned" if the Task.AssignedTo property value is null.

To view the behavior of this example, perform the following steps:

  1. Change assignments in the Assigned To column by selecting different values from the drop-down lists or pressing CTRL+0 in a combo-box cell.

  2. Click Generate Report to display the current assignments. This demonstrates that a change in the Assigned To column automatically updates the tasks collection.

  3. Click a Request Status button to call the RequestStatus method of the current Employee object for that row. This demonstrates that the selected object has been successfully retrieved.

using System;
using System.Text;
using System.Collections.Generic;
using System.Windows.Forms;

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 Task
{
    public Task(Int32 id)
    {
        idValue = id;
    }

    public Task(Int32 id, Employee assignedTo)
    {
        idValue = id;
        assignedToValue = assignedTo;
    }

    private Int32 idValue;
    public Int32 Id
    {
        get { return idValue; }
        set { idValue = value; }
    }

    private Employee assignedToValue;
    public Employee AssignedTo
    {
        get { return assignedToValue; }
        set { assignedToValue = value; }
    }
}

public class Employee
{
    public Employee(String name)
    {
        nameValue = name;
    }

    private String nameValue;
    public String Name
    {
        get { return nameValue; }
        set { nameValue = value; }
    }

    public Employee Self
    {
        get { return this; }
    }

    public void RequestStatus(Int32 taskID)
    {
        MessageBox.Show(String.Format(
            "Status for task {0} has been requested from {1}.",
            taskID, nameValue), "Status Request");
    }
}

Compiling the Code

This example requires:

  • References to the System and System.Windows.Forms assemblies.

See also