使用外键将父表中的值绑定到DataGridView的文本框中 [英] Binding a value from a parent table into a DataGridView's text box using the foreign key

查看:110
本文介绍了使用外键将父表中的值绑定到DataGridView的文本框中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个DataGridView,其中列出了在数据库中找到的所有用户.现在,每个用户都有其类型.因此,当涉及到较低级别时,用户表具有一个名为user_type_id的外键列,该列指向user_type表(在其中代表主键).

I have a DataGridView which list all users found in a database. Now, every user has its type. So, when it comes to low level, a user table has a foreign key column called user_type_id which points to user_type table (where it represents the primary key).

此外,我实现了双向绑定,并且在同一窗口的表单上具有组合框,该组合框可更新用户的类型.实际的问题在于网格视图及其设置(Edit Columns...选项)中的其他重要值,如下所示:

Also, I have implemented two-way binding, and I have combobox on a form on the same window, that updates the type of a user. The actual problem is with grid view and in its settings (Edit Columns... option) among others, the important values looks like this :

标题文本-用户类型

Header Text - User Type

DataPropertyName-user_type_id

DataPropertyName - user_type_id

ColumnType-DataGridViewTextBoxColumn

ColumnType - DataGridViewTextBoxColumn

因此,在我的网格视图中,因为我只能访问外键列(user_type_id),所以我只能显示这些ID,而不能显示用户类型的真实名称(存储在父表中-user_type).

So in my grid view, because I only have access to a foreign key colum (user_type_id), I only can show those ids, rather than a real name of a user type (which is stored in parent table - user_type).

您如何处理?我是否缺少某些设置,还是应该手动获取此设置,而不是期望获得一些自动解决方案?

How do you handle this ? Is there some setting that I am missing or I should fetch this manually rather than expecting for some automatic solution?

推荐答案

我建议对User_Type_ID列使用组合框列.您可以在其中用用户类型的名称填充组合.这是我知道的从外键表显示有意义的值,但仅将ID值存储在要显示/编辑的主表中的最简单方法.

I would suggest using a combobox column for the User_Type_ID column. There you can fill the combo with names of the user types. This is the easiest way I know to display meaningful values from a foreign key table but only store the ID value in the main table you are displaying/editing.

下面是一个简单的示例:

A simple example below:

var comboCol = new DataGridViewComboBoxColumn();
comboCol.DataSource = GetUserTypeNames(); // Retrive these from your database somehow
comboCol.ValueMember = "user_type_id";
comboCol.DisplayMember = "user_type_name";
// This will display just the text
comboCol.DisplayStyle = DataGridViewComboBoxDisplayStyle.Nothing;

这篇关于使用外键将父表中的值绑定到DataGridView的文本框中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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