FeliceM
FeliceM

Reputation: 4199

If statement on dropDownList listItem

I need to add a condition to a DropDownList where a method can be executed by button click only if the user has selected a value different than the listItem (default value).

<asp:DropDownList ID="DropDownList1" runat="server" AppendDataBoundItems="True"
     DataSourceID="SqlDataSource5" 
     DataTextField="proj_name" DataValueField="proj_name">
        <asp:ListItem Text="Select a project to clone" Value="" />
</asp:DropDownList>

How can I structure an if condition to validate that the selected value is not the ListItem (default value)?

Upvotes: 1

Views: 3931

Answers (2)

rs.
rs.

Reputation: 27427

You can use asp.net delivered validation controls

Ex:

<asp:RequiredFieldValidator id="rfv1"
                    ControlToValidate="DropDownList1"
                    Display="Static"
                    ErrorMessage="* Select a value"
                    InitialValue="DefaultValueHere"
                    runat="server"
                    ValidationGroup="V1"/> 

Then edit your button markup to use ValidationGroup

<asp:Button Id="button1" ValidationGroup="V1" .../>

In your codebehind button click code add this

protected void button1_onlick(Object sender, EventArgs e)
{
     If(Page.IsValid)
     {

       // your existing code here
     }
}

Upvotes: 3

malkassem
malkassem

Reputation: 1957

See sample code below

if (DropDownList1.SelectValue == "")
{
// Write your code here
}

you can also have:

if (DropDownList1.Text == "Select a project to clone")
{
// Write your code here
}

Upvotes: 0

Related Questions