Click here to Skip to main content
15,896,310 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
in form1 it have comboBox1 and label1
in combo there items 1 , 2 ,3 , , etc when u select" 1 "then label1.text = "1" and so on

but this code not work

C#
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{

  switch (comboBox1.SelectedItem)
    {
      case 1:
            l1.Text = "11111111111";
          break ;
      case 2:
        l1.Text = "22222222222";
          break ;
      case 3:
          l1.Text = "33333333333";
          break ;


    }
}
Posted

You can't use switch keyword because ComboBox items is type object.

You can try

C#
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{

  switch (int.Parse(comboBox1.SelectedItem))
    {
      case 1:
            l1.Text = "11111111111";
          break ;
      case 2:
        l1.Text = "22222222222";
          break ;
      case 3:
          l1.Text = "33333333333";
          break ;


    }
}
 
Share this answer
 
Comments
majid5487 15-Feb-12 7:31am    
i changed to comboBox1.Text and its worked but why .SelectedItem will not compile :o
here it fixed code thanks you :D
switch (int.Parse(comboBox1.Text ))
{
case 1:
l1.Text = "11111111111";
break;
case 2:
l1.Text = "22222222222";
break;
case 3:
l1.Text = "33333333333";
break;


}
krumia 15-Feb-12 10:19am    
Because, as Ibrahim has said, SelectedItem property returns something of object type, where string (note the lowercase 's') is treated as primitive type.
void comboBox1_SelectedIndexChanged(object sender, EventArgs e){
 l1.Text = comboBox1.SelectedItem.ToString();
}


Or you can use SelectedIndex, which will be a zero based index.

Is this a homework question? If so, you would be much better off actually learning the material instead of posting it here. You will find your course/job/employment prospects very hard if you are stuck at this basic level and don't have the initiative to learn it yourself.
 
Share this answer
 
Comments
majid5487 15-Feb-12 7:26am    
homework
majid5487 15-Feb-12 7:33am    
thanks you too :D but teacher told us to use switch, :D

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