beginIT
beginIT

Reputation: 227

Required Field Validation Error Message is working for Text Box but not working for Drop Down List

In my aspx page, I have 2 search options

One is for searching a product through text box. Another is viewing category by drop down selection.

So this is what I have done in my .aspx file

<div class="searchbox">
        <strong>Search by Product Name<br /></strong> 
        <br />
        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox> &nbsp;
        <asp:Button ID="Button8" runat="server" OnClick="Search_Product"  Text="Search Product" />
&nbsp;
            <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="TextBox1" ErrorMessage="Please enter a product name"></asp:RequiredFieldValidator>
        &nbsp;<asp:Label ID="Label3" runat="server"></asp:Label>
        <br />
        <br />
        </div>

        <br />

        <div class="searchbox">
             <strong>View by Category: View Product on Category Selection</strong><br />
            <br />
            <asp:DropDownList AppendDataBoundItems ="true" ID="DropDownList1" runat="server" DataSourceID="SqlDataSource1" DataTextField="Product_Category_Name" DataValueField="Product_Category_Name">
                <asp:ListItem>Select a Category</asp:ListItem>
            </asp:DropDownList>
             <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:Grocery_DemoConnectionString %>" SelectCommand="SELECT Product_Category_Name FROM Product_Category"></asp:SqlDataSource>
&nbsp; 
            <asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ControlToValidate="DropDownList1" ErrorMessage="Please select a category"></asp:RequiredFieldValidator>
            <br />
            <br />
            <asp:Button ID="Button9" runat="server"  OnClick="View_Product" CausesValidation="false" Text="View Product" />
            &nbsp;
            </div>

And this is what I have done in my .cs file

private void DisplayProducts()
        {
         if (Session["BranchAdmin"] != null)
            {
                string branch = Session["BranchAdmin"].ToString();
                string CS;
                CS = "data source=LAPTOP-ODS96MIK\\MSSQL2014; database = Grocery_Demo; integrated security=SSPI";
                SqlConnection con = new SqlConnection(CS);
                SqlCommand cmd = new SqlCommand("AdminViewProductsOnBranch", con);
                cmd.CommandType = System.Data.CommandType.StoredProcedure;
                cmd.Parameters.AddWithValue("@GroceryBranchName", branch);

                con.Open();
                GridView1.DataSource = cmd.ExecuteReader();
                GridView1.DataBind();
                con.Close();
            }
        }

        protected void Search_Product(object sender, EventArgs e)
        {
            if (Session["BranchAdmin"] != null)
            {
                string branch = Session["BranchAdmin"].ToString();
                string CS;
                CS = "data source=LAPTOP-ODS96MIK\\MSSQL2014; database = Grocery_Demo; integrated security=SSPI";
                SqlConnection con = new SqlConnection(CS);
                SqlCommand cmd = new SqlCommand("AdminSearchProductsOnBranch", con);
                cmd.Parameters.AddWithValue("@ProductName", TextBox1.Text + "%");
                cmd.Parameters.AddWithValue("@GroceryBranchName", branch);
                cmd.CommandType = System.Data.CommandType.StoredProcedure;
                con.Open();
                GridView1.DataSource = cmd.ExecuteReader();
                GridView1.DataBind();
                con.Close();

                con.Open();
                SqlDataReader read = cmd.ExecuteReader();
                read.Read();
                if (read.HasRows == false)
                {
                    Label3.Text = "Couldn't find your product";
                    con.Close();
                }
            }
        }

        protected void View_Product(object sender, EventArgs e)
        {
            if (Session["BranchAdmin"] != null)
            {
                string branch = Session["BranchAdmin"].ToString();
                string CS;
                CS = "data source=LAPTOP-ODS96MIK\\MSSQL2014; database = Grocery_Demo; integrated security=SSPI";
                SqlConnection con = new SqlConnection(CS);
                SqlCommand cmd = new SqlCommand("AdminViewCategoriesOnBranch", con);
                cmd.Parameters.AddWithValue("@ProductCategoryName", DropDownList1.SelectedValue);
                cmd.Parameters.AddWithValue("@GroceryBranchName", branch);
                cmd.CommandType = System.Data.CommandType.StoredProcedure;
                con.Open();
                GridView1.DataSource = cmd.ExecuteReader();
                GridView1.DataBind();
                con.Close();

                con.Open();
                SqlDataReader read = cmd.ExecuteReader();
                read.Read();
                con.Close();
            }
    }

If I search a Product in text box and click on the search button it shows the grid view display if it has the data in table. If the search result doesn't match with data in table, then it shows a Label Text Message: "Couldn't find your Product". And If I keep the text box blank and click on search button, it shows a required field validation message "Please enter a product name". Everything is OK with product search option through text box.

On the other hand, when I select a category from drop down and click on view button, it works perfectly. Now the issues is if I don't select any category from drop down and click on view button, then it is not showing the required field validation error message "Please select a category" and at the same time it is turning the grid view display into blank which I don't want.

What I'm trying to achieve is that if a category is not selected from drop down list and then a view button is clicked, it should show the required field validation error message "Please select a category" and at the same time it should not change the default Grid View display into blank.

If there is any mistake in the codes in either .aspx file or .cs, then it would be helpful if the recommended solution syntax is provided.

Upvotes: 0

Views: 468

Answers (2)

Mohsin Mehmood
Mohsin Mehmood

Reputation: 4246

Specify ValidationGroup for TextBox1 required field validator and Search button controls like this:

<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="TextBox1" ValidationGroup="SearchByName" ErrorMessage="Please enter a product name"></asp:RequiredFieldValidator>

<asp:Button  ValidationGroup="SearchByName"  ID="Button8" runat="server" OnClick="Search_Product"  Text="Search Product" />

Specify a different ValidationGroup from dropdown validator and View_Product button

        <asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ControlToValidate="DropDownList1" ErrorMessage="Please select a category" ValidationGroup="SearchByCategory"></asp:RequiredFieldValidator>

        <asp:Button ID="Button9" runat="server"  OnClick="View_Product" ValidationGroup="SearchByCategory"   Text="View Product" />

Note: I have removed the CausesValidation="false" attribute from View Product button.

Set the value of default list item as -1 and then specifying the InitialValue of dropdown validator?

<asp:ListItem value="-1">Select a Category</asp:ListItem> <asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ControlToValidate="DropDownList1" InitialValue="-1" ErrorMessage="Please select a category" ValidationGroup="SearchByCategory">

Upvotes: 1

Chetan Sanghani
Chetan Sanghani

Reputation: 2111

Please try this

<asp:RequiredFieldValidator runat="server" ControlToValidate="DropDownList1"
cssclass="required" display="dynamic" errormessage="Please select a category" setfocusonerror="true"
initialvalue="0"></asp:RequiredFieldValidator>

Add display="dynamic"property.

Upvotes: 0

Related Questions