Search code examples
c#winformsdata-bindingdatagridview

C# DataGridViewComboBoxColumn binding problem


Hey everyone! I suppose this is my first post on StackOverFlow.com :-)

I've been having this problem for a while. To make it all simple, suppose we have 2 database tables named "books" and "categories" with the following schema:

books(id, title, catId)
categories(id, catName)

Obviously the "catId" field in the "books" table is a foreign key and specifies a category that a book belongs to.

I have created the necessary LinQ to Sql classes and created the necessary bindingSource object. What I'm trying to do is to display all the books in a DataGridView object. I want it to have a column named "Category" which is of type DataGridViewComboBoxColumn containing all existing categories and for each book displays the category that the specific book belongs to. The user can reassign a book's category by choosing another category in the combo box.

I've managed to do exactly what I want with a ComboBox and it works just as I want. But when it comes to the DataGridView I just can't figure it out.

Any help would be greatly appreciated I've spent days to figure something out but no luck so far :-(


Solution

  • This should work:

    // create the column (probably better done by the designer)
    DataGridViewComboBoxColumn categoryColumn = ...
    
    
    // bind it
    categoryColumn.DataSource = db.Categories.ToList();
    categoryColumn.DisplayMember = "catName";  // display category.catName
    categoryColumn.ValueMember = "id";         // use category.id as the identifier
    categoryColumn.DataPropertyName = "catId"; // bind the column to book.catId