代码之家  ›  专栏  ›  技术社区  ›  Nate CSS Guy

webforms文本输入=>双字符串和布尔值

  •  1
  • Nate CSS Guy  · 技术社区  · 15 年前

    有没有更好的方法在webforms中进行“输入表单”?

    我总是以这样的代码结尾:

    Double d = 0; // chuckle inside
    if(Double.TryParse(myNumberTextField.Text, out d))
    {
        myObject.DoubleVal = d;
    }
    

    有没有更好的方法来处理自由形式的“数字”输入。

    1 回复  |  直到 15 年前
        1
  •  1
  •   Jon    15 年前

    您可以使用比较验证器验证文本框,然后如果页面通过验证,则使用double.parse方法。

    <asp:TextBox ID="txtDouble" runat="server"></asp:TextBox>
        <asp:CompareValidator ID="CompareValidator1" runat="server" 
            ErrorMessage="Input must contain a double." ControlToValidate="txtDouble" 
            Operator="DataTypeCheck" SetFocusOnError="True" Type="Double"></asp:CompareValidator>
    <br />
    <asp:Button ID="btnSubmit" runat="server" Text="Submit" />
    
    /*C#*/
    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        if (Page.IsValid)
        {
            double d = double.Parse(txtDouble.Text);
        }
    }