2017-03-10 39 views
0

我试图从数据库中获得库存产品的TotalQuantity,并将其用作范围验证器的最大值,同时添加产品到购物车。 我使用的代码在前端:从数据库asp.net动态获取范围验证器的最大值并将其转换为int

<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 /> 

后端CS代码是:

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(); 
    } 
} 

我累打印在Visual Studio输出面板上的值,并将其显示正确的值和所述键入System.Int32。但页面上的错误显示为 “MaximumValue <%= maxValue%>不能小于RangeValidator1的MinimumValue 1”。

我也尝试了多次向RangeValidator添加/删除Type =“Integer”,但错误仍然存​​在。请帮助我,因为这花了我几个小时的时间试图找出它出错的地方。

回答

1

范围验证程序是runet服务器控件,并且此<%=语句运行得非常晚。它在页面渲染时运行。

你可以用'<%#'这个语句。并绑定你的范围validatator。

<%#maxValue %> 

你需要调用验证器或验证器任何父母DataBind()方法。

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

或只是设置RangeValidator1.MaximumValue直接:)

RangeValidator1.MaximumValue = Convert.ToInt32(TotalQuantity); 
+0

为我工作。非常感谢! – user3387677

相关问题