Cyanic Wolf
Cyanic Wolf

Reputation: 69

Which ComboBox event handler should I use?

I have this problem with my code where I would like to display the change after the total amount is summed up and the user picks a banknote from the ComboBox but I'm not sure if I am using the correct event handler/trigger function and if I should do those conversions. The error I am getting is:

Error 2 The event 'System.Windows.Forms.ComboBox.SelectedIndexChanged' can only appear on the left hand side of += or -= J:\EDPtest1\EDPtest1\Form1.cs 100 49 EDPtest1

private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
    if (Convert.ToDouble(comboBox1.SelectedIndexChanged == total))
    {
        lblChange.Text = "Amount Correct";
    }
    else if (Convert.ToDouble(comboBox1.SelectedIndexChanged > total))
    {
        lblChange.Text = "Total change: " + comboBox1.SelectedIndexChanged - total;
    }
    else if(Convert.ToDouble(comboBox1.SelectedIndexChanged < total))
    {
        lblChange.Text = "Please add more money";
    }
}

Upvotes: 0

Views: 96

Answers (3)

Salah Akbari
Salah Akbari

Reputation: 39976

You should use ComboBox.SelectedItem Property instead of SelectedIndexChanged event in your if statements. And also based on your comment that you get this error:

The operators '>' cannot be applied to operands of type 'objects' and 'double'

You should cast second operand to double:

if (Convert.ToDouble(comboBox1.SelectedItem) == (double) total)
{
    lblChange.Text = "Amount Correct";
}

Upvotes: 2

Prabhat-VS
Prabhat-VS

Reputation: 1530

if (Convert.ToDouble(comboBox1.SelectedValue) == (total.ToDouble()))
{
    lblChange.Text = "Amount Correct";
}

Upvotes: 0

sujith karivelil
sujith karivelil

Reputation: 29036

SelectedIndexChanged is an event you cannot compare that with a variable total assume that the variable is of type double you what you need to do here is, You need to convert the SelectedText/SelectedValue to double and then do the comparison. Probably double.TryParse() will be more suitable for converting string to double, than Convert.ToDouble(). I have included all these points in the snippet below:

double input;
if (double.TryParse(comboBox1.SelectedText, out input)) // can use comboBox1.SelectedValue also if you are binding the values
   {
     if (input == total)
     {
        lblChange.Text = "Amount Correct";
     }
     else if (input > total)
     {
        lblChange.Text = "Total change: " + (input - total);
     }
     else if (input < total)
     {
        lblChange.Text = "Please add more money";
     }
  }
  else
  {
       lblChange.Text = "Please add more money";
  }

Upvotes: 0

Related Questions