Click here to Skip to main content
15,922,584 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
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.

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


Thanks in advance for your help.
Posted

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.
 
Share this answer
 
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...

C#
private void cmdEdit_Click(object sender, EventArgs e)
{
    string strField = this.cboClients.ValueMember;
    int intClient = this.cboClients.SelectedValue;
}
 
Share this answer
 
Comments
kaushal16 15-Jun-11 1:47am    
Nice Solution.......
I'm new to C#, mea culpa.

The solution was just too straight forward:

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

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900