Reputation: 581
In my C# web application, I have three textboxes, three drop down lists, and one button.
The button is suppose to run a SQL string that will take the values of whatever is in typed in the textboxes, whatever is selected, and be inserted into the database. The values inserted may not be null so I don't want any blank entries. By default, I have the DropDownList like so 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 a blank entry (default), and then the yes/no. There are three of these drop down lists in the application. In my C# code, I have the following to prevent the button from firing if there is a blank entry:
if (UsernameBox.Text != "" & FirstNameBox.Text != "" & LastNameBox.Text != "" /* check for blank dropdownlist? */)
My current issue is that I don't know how to check the dropdownlist for a blank entry. My guess would have been to check to see if ReadDrop.Text is blank, but I am relatively inexperienced in ASP.NET and am wondering if there is a "proper" way to do this.
Thanks!
Upvotes: 4
Views: 17907
Reputation: 460138
You could use SelectedIndex > 0
:
if (UsernameBox.Text != "" & FirstNameBox.Text != "" & LastNameBox.Text != "" && ReadDrop.SelectedIndex > 0)
{
// ...
}
Note that the SelectedIndex
is -1 if no item is selected and yes/no have 1/2.
Another option is to use the SelectedItem
:
ListItem selectedItem = ReadDrop.SelectedItem;
if(selectedItem != null && !String.IsNullOrEmpty(selectedItem.Text))
{
// ...
}
However, i think that you actually want to prevent that the user selects no item, or in other words, validate that he selects something. Then use a RequiredFieldValidator
, you have to set the InitialValue
to ""
:
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server"
ErrorMessage="Select Something" ControlToValidate="ReadDrop"
InitialValue=""></asp:RequiredFieldValidator>
You could assign a different Value
to your empty item and change the InitialValue
appropriately:
Upvotes: 4