CODEDIGEST
Home Articles CodeDigest Tutorials FAQs
Skip Navigation LinksHome » CodeDigest » Using RequiredFieldValidator control with DropDownList control   You are not logged in.
Search
 

Technologies
 

CodeDigest Navigation
 

Technology News
No News Feeds available at this time.
 

Community News
Read more..

Read more..

 
Using RequiredFieldValidator control with DropDownList control
Using RequiredFieldValidator control with DropDownList control
Submitted By Satheesh Babu
On 10/23/2008 8:48:47 AM
Tags: asp.net,CodeDigest  

 

We use RequiredFieldValidator control to make a field mandatory in ASP.Net. This little tip will help us to use a DropDownList control with RequiredFieldValidator control. This code snippet will insert a default item as the first Item to the DropDownList with value as empty. In this scenario, When a RequiredFieldValidator is associated with DropDownList through its ControlToValidate property; it will make the DropDownList as a mandatory field when it is left with default value selection.

 

ASPX

 <asp:DropDownList ID="ddlRank" runat="server">

        </asp:DropDownList>

        <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="ddlRank"

            ErrorMessage="Select a Rank"></asp:RequiredFieldValidator>

        <asp:Button ID="btnSave" runat="server" Text="Save" />

 

CodeBehind

protected void Page_Load(object sender, EventArgs e)

    {

        if (!IsPostBack)

        {

            ddlRank.Items.Add(new ListItem("Select",""));

            ddlRank.Items.Add(new ListItem("1", "1"));

            ddlRank.Items.Add(new ListItem("2", "2"));

            ddlRank.Items.Add(new ListItem("3", "3"));

        }

    }

 

Execute the page. You will receive an error message when you click Save without selecting a value in DropDownList control.

Do you have a working code that can be used by anyone? Submit it here. It may help someone in the community!!