check if a values has been selected from dropdown in c#
Asked Answered
S

3

8

I have 3 dropdown boxes (combo box) in asp.net environment. They are all optional, so if a user has selected anything, i am updating database, if nothing has been selected at all, i am still updating database with null values.

I tried to do this:

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

I was hoping that if nothing is selected null will be inserted in CountryId, but, instead its throwing an exception.

I tried to search for ddCountries.isSelected (or something like that) but it obviously doesnt exist..

so how do I find out if a selection has been made on a dropdown box? - through c# code.

Many Thanks

ps: I have a thought - i put each dropdown box in a try... catch block and if exception arises, set variables to null manually.. but I am not sure thats the best way to do it!

Sepulveda answered 16/8, 2010 at 10:32 Comment(2)
i dont want to have required field validator because the selection is optional.... thanks!Sepulveda
why not using int.TryParse()? It returns false if it failed to pase the input as an integer.Juglandaceous
K
17

You're looking for

if(ddCountries.SelectedIndex > -1)

You should never be using exceptions to control program flow.

Kilocalorie answered 16/8, 2010 at 10:35 Comment(2)
Hi, I used a mix of your answer and the one below (from LukasW with ternary operator) and its working now. Plus thanks much for info on using exception to control program flow.Sepulveda
+1 for the "You should never be using exceptions to control program flow.". This seems to not be repeated often enough for some.Phototherapy
O
0
ddCountries.SelectedIndex > 0;

This worked for me, assuming that you have an empty item on index 0 that you have inserted.

ddCountries.Items.Insert(0, new ListItem(string.Empty, string.Empty));

ddCountries.SelectedIndex = 0;
Olva answered 31/3, 2022 at 10:42 Comment(0)
S
-1

You can use this:

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

Please note that it is in VB.Net

Slippery answered 20/8, 2017 at 6:56 Comment(1)
The question is c# related, not vb.net. You should consider translating to code into c#, it is pretty straightforward. It would be something similar to if (ComboBoxChannel.SelectedValue.ToString().ToLower() == "system.data.datarowview") return;Juglandaceous

© 2022 - 2024 — McMap. All rights reserved.