Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 :-(

like image 551
Maghoumi Avatar asked Sep 21 '10 09:09

Maghoumi


People also ask

What C is used for?

C programming language is a machine-independent programming language that is mainly used to create many types of applications and operating systems such as Windows, and other complicated programs such as the Oracle database, Git, Python interpreter, and games and is considered a programming foundation in the process of ...

What is C in C language?

What is C? C is a general-purpose programming language created by Dennis Ritchie at the Bell Laboratories in 1972. It is a very popular language, despite being old. C is strongly associated with UNIX, as it was developed to write the UNIX operating system.

What is the full name of C?

In the real sense it has no meaning or full form. It was developed by Dennis Ritchie and Ken Thompson at AT&T bell Lab. First, they used to call it as B language then later they made some improvement into it and renamed it as C and its superscript as C++ which was invented by Dr.

Is C language easy?

Compared to other languages—like Java, PHP, or C#—C is a relatively simple language to learn for anyone just starting to learn computer programming because of its limited number of keywords.


1 Answers

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
like image 158
Thomas Levesque Avatar answered Sep 21 '22 10:09

Thomas Levesque