C#DataGridViewComboBoxColumn绑定问题 [英] C# DataGridViewComboBoxColumn binding problem

查看:990
本文介绍了C#DataGridViewComboBoxColumn绑定问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好!我想这是我的第一次StackOverFlow.com后: - )

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

我一直有这个问题了一会儿。
,使这一切简单,假设我们有一个名为的书2数据库表的和的类别的有以下模式:

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:

书(ID,标题,CATID)结果
类(ID,catName)

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

显然在书中的CATID的字段的表的外键,并指定一本书属于一个类别。

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

我已经建立了必要的LINQ to SQL类,并创建必要的BindingSource对象。
我试图做的是显示一个DataGridView对象中的所有书籍。我希望它有一个名为列的类别的这类型的 DataGridViewComboBoxColumn 的包含所有现有的类别,并为每个书显示,具体书所属的类别。用户可以通过选择在组合框中另一个类别重新分配一书的类别。

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.

我已经设法用的组合框和它的作品就像我想要的。
但是,当涉及到的 DataGridView的的我只是不明白。

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

推荐答案

这应该工作:

// 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

这篇关于C#DataGridViewComboBoxColumn绑定问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆