如何获得与组合框选定索引关联的主键? [英] How do I get the primary key associated with a Combo Box Selected Index?

查看:71
本文介绍了如何获得与组合框选定索引关联的主键?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有自动递增主键的数据库.我的组合框按字母顺序显示名称列表.我可以获取索引,但是我对如何获取主键感到困惑.

I have a database with a primary key that''s automatically incremented. My Combo Box displays a list of names in alphabetical order. I can get the index but I''m stuck on how to get the primary key.

private void cmdEdit_Click(object sender, EventArgs e)
{
    string strField = this.cboClients.ValueMember;
    int intClient = this.cboClients.SelectedIndex;
}



预先感谢您的帮助.



Thanks in advance for your help.

推荐答案

在加载组合框时,您可以指定显示文本而不是值...因此您可以将名称作为显示内容,但是保留主键值作为值. 此处 [
When you load the combobox you can specify display text versus a value...so you could put your names as the display but keep a primary key value as the value. Here[^] is an article that explains this.


我认为您应该像这样绑定组合框您的主键值应绑定为值成员,并且要在组合框中显示的主要内容应绑定为显示成员,以便以后可以直接指向主键,例如....

I think for that you should bind your combo box like your primary key value should be bind as a value member and the main thing that you want to display in combo box that should be bind as display member so later on you can directly point to the primary key like....

//bind combo box like this...
     this.cboClients.DataSource = ds.Tables["tableName"]; // for that you need to fire a select query that fill the record in dataset
     this.cboClients.DisplayMember = "FieldName"; // give the name of field that you want to display in combo box
     this.cboClients.ValueMember = "FieldName"; // give the name of primary field...


private void cmdEdit_Click(object sender, EventArgs e)
{
    string strField = this.cboClients.ValueMember;
    int intClient = this.cboClients.SelectedValue;
}


我是C#的新手,是负责任.

解决方案太简单了:

int intClientKey = this.persDataDataSet.Clients [this.cboClients.SelectedIndex] .ClientKey;
I''m new to C#, mea culpa.

The solution was just too straight forward:

int intClientKey = this.persDataDataSet.Clients[this.cboClients.SelectedIndex].ClientKey;


这篇关于如何获得与组合框选定索引关联的主键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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