2010-04-14 51 views
1

有沒有更好的方式在WebForms中執行「輸入表單」?WebForms文本輸入=>雙打&字符串&布爾值

我總是落得這樣的代碼:

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

是否有更好的方法來處理自由形式的「數字」輸入。

回答

1

您可以使用比較驗證器驗證文本框,然後如果頁面通過驗證,則使用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); 
    } 
}