简体   繁体   English

C# DataGridViewComboBoxColumn 绑定问题

[英]C# DataGridViewComboBoxColumn binding problem

Hey everyone!大家好! I suppose this is my first post on StackOverFlow.com :-)我想这是我在 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:为简单起见,假设我们有 2 个名为“books”“categories”的数据库表,其架构如下:

books(id, title, catId)书籍(ID,标题,catId)
categories(id, catName)类别(ID,猫名)

Obviously the "catId" field in the "books" table is a foreign key and specifies a category that a book belongs to.显然, books”表中的“catId”字段是外键,指定一本书所属的类别。

I have created the necessary LinQ to Sql classes and created the necessary bindingSource object.我已经创建了必要的 LinQ to Sql 类并创建了必要的 bindingSource 对象。 What I'm trying to do is to display all the books in a DataGridView object.我想要做的是在 DataGridView 对象中显示所有书籍。 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.我希望它有一个名为“Category”的列,它是DataGridViewComboBoxColumn类型,包含所有现有的类别,并为每本书显示特定书籍所属的类别。 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.我已经设法用ComboBox做我想做的事,而且它按我的意愿工作。 But when it comes to the DataGridView I just can't figure it out.但是当涉及到DataGridView 时,我就是想不通。

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.我设法通过覆盖相关类中的 ToString() 方法来做到这一点。 For you case, you could add in the definition of categories:对于您的情况,您可以添加类别的定义:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM