Check if values ​​were selected from dropdown in C #

I have 3 dropdowns (combo box) in asp.net environment. They are all optional, therefore, if the user selects something, I update the database, if nothing was selected at all, I am still updating the database with zero values.

I tried to do this:

 int? CountryId = Convert.ToInt32(ddCountries.SelectedItem.Value);

I was hoping that if nothing is selected, a null value will be inserted into CountryId, but an exception will be thrown instead.

I tried to find ddCountries.isSelected (or something like that), but it obviously does not exist ..

so how do you know if a selection was highlighted in the drop-down list? - through the C # code.

Many thanks

ps: I have a thought: I put each drop-down list in a try ... catch block, and if an exception occurs, set the null variables manually. but I'm not sure if this is the best way to do this!

+5
source share
2 answers

You are looking for

if(ddCountries.SelectedIndex > -1)

You should not use exceptions to control program flow.

+8
source

If ComboBoxChannel.SelectedValue.ToString.ToLower = "system.data.datarowview" Then exit Sub

0
source

All Articles