3

I have a comboBox with ValueMember = ID and DisplayMember = Name. I need the value that is associated with that name so I do something like this:

if (cboTypeOfMaterial.SelectedIndex != -1) { string temp = cboTypeOfMaterial.SelectedValue.ToString(); //More code here... } 

Which returns the ID value as a string. For example - "7".

If I try :

if (cboTypeOfMaterial.SelectedIndex != -1) { string temp = cboTypeOfMaterial.DisplayMember.ToString(); //More code here... } 

I get the string Name which is the key.

And what I need is to get the value of the selected element's Name

1
  • simply cboTypeOfMaterial.SelectedItem.ToString() should also work. Give it a try. Commented Feb 26, 2013 at 7:49

6 Answers 6

4

SelectedValue will return the value of the property defined in ValueMember, SelectedItem will return the entire object that is selected, if you want to get another value other than your SelectedValue you will have to cast as the object in your ComboBox then you can access your Name property.

string temp = (cboTypeOfMaterial.SelectedItem as YourObjectType).Name; 
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, this works and is something new for so I'm gonna use it!
4

Try to access the element via SelectedItem which will give you the whole object associated with that entry and then you can access the properties you need, in your case ID.

Comments

2

I know this is an old question, but I'm surprised no one has mentioned:

ComboBox1.GetItemText(ComboBox1.SelectedItem) 

which returns the text representation of the selected item (i.e. the DisplayMember) and is helpful in cases involving a data bound ComboBox, or any ListControl for that matter.

Comments

1

What you can do is to create a custom class for the entries in the comboBox. This can look like:

public class ComboBoxItem { public string Display { get; set; } public int Id { get; set; } public override string ToString() { return this.Display; } } 

Then you can get the selected ComboBoxItem through the following code:

ComboBoxItem cbi = (ComboBoxItem)cboTypeOfMaterial.SelectedValue; if(cbi != null) // Access the Property you need 

Comments

0
string temp = cboTypeOfMaterial.ValueMember.ToString(); 

Comments

-2

I think you can also use the Text property but it is not a nice solution. the better solution is what @dutzu is suggested.

string temp = cboTypeOfMaterial.Text; 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.