user3690808
user3690808

Reputation: 1

Prevent the Selected Index Changed event of dropdown on selecting the default value in ASP.NET

I have a dropdown having values

<asp:DropDownList ID="DropDownList1" runat="server" 
                  onselectedindexchanged="DropDownList1_SelectedIndexChanged">
    <asp:ListItem>SELECT</asp:ListItem>
    <asp:ListItem>AUS</asp:ListItem>
    <asp:ListItem>BAN</asp:ListItem>
    <asp:ListItem>CAN</asp:ListItem>
    <asp:ListItem>DEN</asp:ListItem>
    <asp:ListItem>ENG</asp:ListItem>
    <asp:ListItem>IND</asp:ListItem>
</asp:DropDownList>

on Selected Index Changed I am writing the Item Name as:

protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
    Response.Write(DropDownList1.SelectedItem);
}

I want when I will select The default value that is Select, The event shouldn't be called. It should called only if I will select anything except Select.

Please help me to get this.

Upvotes: 0

Views: 1764

Answers (2)

Win
Win

Reputation: 62290

You can PostBack to server yourself based on the selected option.

Note: Do not set AutoPostBack="True" for DropDownList.

<asp:DropDownList runat="server" ID="DropDownList1"
    onChange="changeDropDownList();" 
    OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged">
    <asp:ListItem Value="" Text="SELECT" />
    <asp:ListItem Value="AUS" Text="AUS" />
    <asp:ListItem Value="BAN" Text="BAN" />
    <asp:ListItem Value="CAN" Text="CAN" />
    <asp:ListItem Value="DEN" Text="DEN" />
    <asp:ListItem Value="ENG" Text="ENG" />
    <asp:ListItem Value="IND" Text="IND" />
</asp:DropDownList>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript">
    function changeDropDownList() {
        // If you want to check by selected text, use this line.
        // var text= $('#<%= DropDownList1.ClientID %> option:selected').text(); 

        var value = $('#<%= DropDownList1.ClientID %> option:selected').val();
        if (value != "") {
            __doPostBack('<%= DropDownList1.ClientID %>', '');
        } else {
            return false;
        }
    }
</script>

Upvotes: 1

Sid M
Sid M

Reputation: 4354

One of the simplest way would be to use a Required Field Validator like this

<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" 
 ControlToValidate="DropDownList1" ErrorMessage="" InitialValue="SELECT" >
</asp:RequiredFieldValidator>

when you give InitialValue="SELECT" it won't allow you to do any postback for SELECT value

Upvotes: 0

Related Questions