Search code examples
c#winformsdatagridviewcomboboxdatagridviewcomboboxcolumn

Tables A DataGridViewComboBoxColumn value displayed in Tables B DataGridViewComboBoxColumn


Is it possible to display for example table A's DataGridViewComboBoxColumn value in table B's DataGridViewComboBoxColumn?

I've tried using DataGridViewComboBoxColumn A's name(name as in defined Name = "Something") to pass to DataMember DataGridViewComboBoxColumn "B", but it doesn't seem to work, as it throws an error, that column "Something" cannot be found.


Solution

  • Scenario:

    You have tables like:

    Employee
    FirstName - e.g. "John"
    DepartmentID - e.g. 1 (for Tech)
    
    Department
    ID - e.g. 1
    Name - e.g. Tech
    

    And you want to have a datagridview with a combobox column that show/chooses the department

    • Your datagridview is bound to a datatable for the employee
    • You have created a datagridviewcomboboxcolumn (DGVCBC)

    You should set up your DGVCBC so it has:

    • .DataSource = the datatable in which the department data is kept
    • .ValueMember = string name of the column in which the department ID is kept (in the department table) e.g. "ID" in my example
    • .DisplayMember = string name of the column in which the department Name is kept (in the department table) e.g. "ID" in my example
    • .DataMember = string name of the column in which the employee's department id is kept (e.g. "DepartmentID" in my example)

    You can do this setup in the designer or in code. Set up thus, the DGVCBC will read the id from DepartmentID, it will look up that ID in departmentDatatable.ID, it will show the related name in departmentDatatable.Name. When you change the combo to a new value, it will take the selected new ID value and apply it to DepartmentID, thus changing the department of the employee