开发者

C# DataGridViewComboBoxColumn binding problem

开发者 https://www.devze.com 2023-01-17 03:31 出处:网络
Hey everyone! I suppose this is my first post on StackOverFlow.com :-) I\'ve been having this problem for a while.

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 t开发者_运维知识库he "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 :-(


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


I managed to do it by overwriting the ToString() method in the concerned class. For you case, you could add in the definition of categories:

public override string ToString()
{
   return this.catName
}
0

精彩评论

暂无评论...
验证码 换一张
取 消