Click here to Skip to main content
15,889,200 members
Please Sign up or sign in to vote.
1.80/5 (3 votes)
See more:
Afternoon,

I have a problem with my combo box validation, I need it so if you select Edinburgh twice in another combo box it displays an error message. This is my code so far. I am hoping someone can help, sorry if it isn't very detailed.

What I have tried:

<pre>f (CmbDepa.Text == "Edinburgh" && CmbArrival.Text == "Edinburgh")
            {
               MessageBox.Show("You cant select edinburgh twice");
            }
            else
            {
                Listbox1.Items.Add(CmbDepa.Text);
            }

}
Posted
Updated 18-Dec-18 5:59am
v3
Comments
[no name] 18-Dec-18 11:15am    
SelectedIndex property should give you index number which is integer. If you need to check for text you can do with CmbDepa.SelectedItem.ToString()
Member 14093842 18-Dec-18 11:19am    
How would I edit my code for this to work? Sorry i'm new to C# and coding

1 solution

You assign using "=" and compare using "==" so change to "==".

if (CmbDepa.SelectedIndex == "Edinburgh") && (CmbArrival.SelectedIndex == "Edinburgh")


Next you shouldn't use exceptions for things that are expected. Exceptions are for...exceptions :) Forget all the trys etc, just show a message


if (CmbDepa.SelectedIndex == "Edinburgh") && (CmbArrival.SelectedIndex == "Edinburgh")
{
    MessageBox.Show("You cant select edinburgh twice");
}
else
{
    Listbox1.Items.Add(CmbDepa.Text);
}
 
Share this answer
 
Comments
Member 14093842 18-Dec-18 11:34am    
Hello thanks for your help! When I have entered the code into my program it is saying
Error CS0019 Operator '==' cannot be applied to operands of type 'int' and 'string' and Error CS1525 Invalid expression term '&&'
F-ES Sitecore 18-Dec-18 11:38am    
If you want to compare the text you'll need .Text or .SelectedText, whatever the property is called (don't have the docs to hand), rather than .SelectedIndex
Member 14093842 18-Dec-18 11:57am    
I have changed it to the correct way, but the validation isn't displaying a validation message when I run the code. I've updated the code.

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