2012-10-06 129 views
0

在一個C#窗體窗體類中,我綁定了像這樣的文本框。textbox百分比格式化和非格式化

this.textMargin.DataBindings.Add(new Binding("Text", dt, "Margin", true, DataSourceUpdateMode.OnValidation, 0, "P")); 

這適用於顯示文本框「textMargin」爲百分比。但是,當我的文本框的值傳遞給我的更新語句,我得到即使我試圖用Decimal.Parse這樣的字符串格式錯誤:

decimal testconvert = Decimal.Parse(this.textMargin.Text); 

我想傳遞的價值'100%',但它需要提交回數據庫爲1.

這裏有什麼祕訣?

感謝

回答

4

嘗試

string textMargin = this.textMargin.Text.EndsWith("%") ? this.textMargin.Text.Replace("%","") : this.textMargin.Text; 

decimal testconvert = Decimal.Parse(textMargin)/100; 
+0

適合我!謝謝你的時間。 – Ryan

+0

+1爲條件運算符 – Kinected

0

正如你可以看到Decimal.Parse將不接受非數字值,但你可以使用一個簡單的算法如下面擺脫非數字:

public static string RemoveNonDigits(string s) 
    { 
     string newS = ""; 
     if (s.Length == 0) return newS; 
     for (int i = 0; i < s.Length; i++) 
     { 

      if (Char.IsDigit(s[i]) || s[i] == '.') 
       newS += s[i]; 

      else if (!Char.IsDigit(s[i])) 
      { 
       newS += ""; 
      } 

      return newS; 
     } 

然後就可以調用

Decimal percent = Decimal.Parse(RemoveNonDigits(textMargin.Text.ToString())); 
+0

這些作品無論是用' 「100%」'。發帖前請先測試。 – Oded

+0

@Oded Check edits – Kinected

+0

'Decimal.Parse'將接受一個不是數字的'.'。 – Oded

1

%不是小數的有效部分,並且不能由Decimal.Parse進行解析。

在解析之前,您需要將其清除出字符串。

2

這應該適用於您,使用decimal.TryParse來避免錯誤,並且String.Replace可以刪除您的%。

decimal.TryParse(this.textMargin.Text.Replace("%", ""), out testconvert); 
testconvert = testconvert/100;