Search code examples
c#asp.netstring-parsingrangevalidator

dynamically get the maximum value of range validator from database asp.net and convert to int


Ive tried to get the TotalQuantity of a product in stock form the database, and use it as a max value for a range validator while adding the product to the cart. I used the code in the front end:

 <td class="style2">
   QUANTITY<br />
           <asp:TextBox ID="TextBox1" runat="server" ></asp:TextBox>
           <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" 
               ControlToValidate="TextBox1" ErrorMessage="must fill some value"></asp:RequiredFieldValidator>

           <asp:RangeValidator ID="RangeValidator1" runat="server" 
               ControlToValidate="TextBox1" ErrorMessage="must fill value lesser than the Total Quantity in stock" 
               MaximumValue="<%=maxValue %>" MinimumValue="1" Display="Dynamic" ></asp:RangeValidator>
           <br />

The backend cs code is:

 public partial class productDetail : System.Web.UI.Page
{
    public int maxValue=0;
    public int minValue = 1;
     .....
       protected void Page_Load(object sender, EventArgs e)
    {
      //Defined SQL Conn string...
        connection1.Open();
        string cartCmd = "select TotalQuantity from Product where ProductName= \'"+prodName+"\';";
        SqlCommand cmd = new SqlCommand(cartCmd, connection1);
        SqlDataReader readerTotQquantity = cmd.ExecuteReader();
        if (readerTotQquantity .HasRows)
        {
            readerTotQquantity .Read();
            TotalQuantity = readerTotQquantity ["TotalQuantity"].ToString();
        }

        double val = Convert.ToDouble(TotalQuantity);
        maxValue = (int)val;
        // also tried maxValue=Convert.ToInt32(TotalQuantity);
        // tired maxValue=int.Parse(TotalQuantity); etc


        connection1.Close();
     }
}

I tired to print the value on the Visual Studio output panel and it shows the correct value and the type as System.Int32. but the error on the page shows "The MaximumValue <%=maxValue %> cannot be less than the MinimumValue 1 of RangeValidator1".

I also tried several times adding/removing the Type="Integer" to the RangeValidator but the error persists. Pls do help me as this has taken up few hours of my time trying to figure out where its going wrong.


Solution

  • range validator is runet server control and this <%= statement running soo late for it. its running when page rendering.

    you you can use '<%#' this statement. and bind your range validatator.

    <%#maxValue %>
    

    and you need to call validators or validators any parents DataBind() method.

    maxValue = Convert.ToInt32(TotalQuantity);
    RangeValidator1.DataBind();
    

    OR just set RangeValidator1.MaximumValue directly :)

    RangeValidator1.MaximumValue = Convert.ToInt32(TotalQuantity);