3

What is the difference between each of these? Can I use any of these methods to display the text of a combo box in label, or is there any difference?

label1.Text = comboBox1.SelectedItem.ToString();
label2.Text = comboBox1.Text;
label3.Text = comboBox1.SelectedValue.ToString();

I am testing these values of the Combo box, but I'm confused as to how they work. I want to display the text of a combo box in label. Using comboBox.Text it works fine but the remaining two give the following error:

error message:Object reference not set to an instance of an object.
abdulmanan
  • 45
  • 1
  • 7

1 Answers1

5

Here is my example.

private void comboSelectChanged(object sender, SelectionChangedEventArgs e)
{
  textBox1.Text = comboBox1.SelectedItem.ToString();
  textBox2.Text = comboBox1.Text;
  textBox3.Text = comboBox1.SelectedIndex.ToString();
}

Items collection: enter image description here

And the results:

One selected

Two selected

Three selected


SelectedItem: Gets or sets currently selected item in the ComboBox.
Based on ComboBox.SelectionChangeCommitted

Text: Gets or sets the text associated with this control. (Overrides Control.Text.)
setting the text value will change the current value of the combobox

SelectedValue: Gets or sets the value of the member property specified by the ValueMember property. (Inherited from ListControl.)
Based on ListControl.SelectedValueChanged

This question might be a duplicate of ComboBox SelectedItem vs SelectedValue.

Source msdn
Further reading at dotnetperls.

Community
  • 1
  • 1
Scott Solmer
  • 3,871
  • 6
  • 44
  • 72