问题描述
我有 4 个主键字段的表.我将其加载到使用 C# 创建的 WinForm 应用程序的下拉列表中.
I have table with 4 primary key fields. I load that in to drop down list in my WinForm application created by using C#.
在下拉列表的 TextChanged 事件中,我有某个 TextBox,我想为下拉列表中选择的某个字段填写表格接收到的信息.
On the TextChanged event of drop down list I have certain TextBox and I want to fill the information recived by the table for the certain field I selected by the drop down list.
所以正如我所说的表有 4 个字段.我可以从数据集中将所有 4 个字段都放入 value member 中吗,或者你能告诉我这是否可能吗?
So as I say the table having 4 fields. Can I get those all 4 fields into value member from the data set, or could you please tell me whether is that not possible?
谢谢.
数据表 dt=dba.getName();cmb_name.ValueMember="id";cmb_name.DisplayMember="名称";cmb_name.DataSource=dt;
这是正常格式..但我有更多关键字段..所以我需要添加更多关键字段..
this is normal format.. but i have more key fields.. so i need to add more key fields..
推荐答案
你可以使用 DataSource 属性将源数据绑定到 ComboBox(例如实体列表或 DataTable 等),然后将 ComboBox 的 DisplayMember
属性设置为(字符串) 要显示的字段的名称.
You can use DataSource property to bind your source data to the ComboBox (e.g. a List of Entities, or a DataTable, etc), and then set the DisplayMember
property of the ComboBox to the (string) name of the field you want to display.
在用户选择了一个项目后,您可以将 SelectedItem
转换回原始行数据类型(实体、DataRow 等 - 它仍然与您输入的类型相同),然后您可以检索原始项目的 4 个复合键.
After the user has selected an Item, you can then cast the SelectedItem
back to the original row data type (Entity, DataRow, etc - it will still be the same type as you put in), and then you can retrieve your 4 composite keys to the original item.
这样可以完全避免 SelectedValue
问题.
This way you avoid the SelectedValue
problem entirely.
编辑:
如下填充:
cmb_name.DisplayMember = "name";
cmb_name.DataSource = dt;
// Ignore ValueMember and Selected Value entirely
当您想要检索所选项目时
When you want to retrieve the selected item
var selectedRow = (cmb_name.SelectedItem as DataRowView );
现在您可以检索 PK 的 4 个值,例如selectedRow["field1"], selectedRow["field2"], selectedRow["field3"] 等
Now you can retrieve the 4 values of your PK, e.g. selectedRow["field1"], selectedRow["field2"], selectedRow["field3"] etc
但是,如果您的意思是要向用户 DISPLAY 4 列(即与您的表键无关),请参见此处 如何绑定 ComboBox 以使 displaymember 成为源数据表的2个字段的concat?
If however you mean that you want to DISPLAY 4 columns to the user (i.e. nothing to do with your Table Key), then see here How do I bind a ComboBox so the displaymember is concat of 2 fields of source datatable?
这篇关于向 C# 编码的值成员添加 2 个或更多字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!