Checking if DropDownList is set to an index value does matter

In my C # web application, I have three text fields, three drop-down lists and one button.

The button should start the SQL string, which will take the values ​​of what is in the text field, regardless of what is selected, and be inserted into the database. The values ​​entered may not be zero, so I do not want any empty entries. By default, I have a DropDownList, as in the source:

<asp:DropDownList ID="ReadDrop" runat="server">
    <asp:ListItem></asp:ListItem>
    <asp:ListItem Value="1">Yes</asp:ListItem>
    <asp:ListItem Value="0">No</asp:ListItem>
</asp:DropDownList>

So there is an empty entry (default), and then yes / no. Attached are three of these drop-down lists. In my C # code, I have the following to prevent the button from starting when there is an empty entry:

if (UsernameBox.Text != "" & FirstNameBox.Text != "" & LastNameBox.Text != "" /* check for blank dropdownlist? */)

My current problem is that I do not know how to check the drop-down list for an empty entry. I would rather check to see if ReadDrop.Text is empty, but I'm relatively inexperienced in ASP.NET, and I'm wondering if there is a “right” way to do this.

Thank!

+4
source share
1 answer

You can use SelectedIndex > 0:

if (UsernameBox.Text != "" & FirstNameBox.Text != "" & LastNameBox.Text != "" && ReadDrop.SelectedIndex > 0)
{
    // ...
}

Note that it SelectedIndexis -1 if no items are selected and yes / no has 1/2.

Another option is to use SelectedItem:

ListItem selectedItem = ReadDrop.SelectedItem;
if(selectedItem != null && !String.IsNullOrEmpty(selectedItem.Text))
{
  // ...
} 

However, I think that you really want to prevent the user from selecting any items, or, in other words, confirming that he is choosing something. Then use RequiredFieldValidator, you should set InitialValueto "":

<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" 
    ErrorMessage="Select Something" ControlToValidate="ReadDrop" 
    InitialValue=""></asp:RequiredFieldValidator>

Value InitialValue:

+4

All Articles