2015-09-20 68 views

回答

0

經過研究,我發現了這段代碼。這段代碼正是我想要的。

private void form_3_Load(object sender, EventArgs e) 
    { 
     textBox1.Text = "$0.00"; 
    } 

    private void textBox1_TextChanged(object sender, EventArgs e) 
    { 
     /// 
     //Remove previous formatting, or the decimal check will fail including leading zeros 
     string value = textBox1.Text.Replace(",", "") 
      .Replace("$", "").Replace(".", "").TrimStart('0'); 
     decimal ul; 
     //Check we are indeed handling a number 
     if (decimal.TryParse(value, out ul)) 
     { 
      ul /= 100; 
      //Unsub the event so we don't enter a loop 
      textBox1.TextChanged -= textBox1_TextChanged; 
      //Format the text as currency 
      textBox1.Text = string.Format(CultureInfo.CreateSpecificCulture("en-US"), "{0:C2}", ul); 
      textBox1.TextChanged += textBox1_TextChanged; 
      textBox1.Select(textBox1.Text.Length, 0); 
     } 
     bool goodToGo = TextisValid(textBox1.Text); 
     btn_test.Enabled = goodToGo; 
     if (!goodToGo) 
     { 
      textBox1.Text = "$0.00"; 
      textBox1.Select(textBox1.Text.Length, 0); 
     } 
     /// 
    } 

    private bool TextisValid(string text) 
    { 
     Regex money = new Regex(@"^\$(\d{1,3}(\,\d{3})*|(\d+))(\.\d{2})?$"); 
     return money.IsMatch(text); 
    } 


    void tb_TextChanged(object sender, EventArgs e) 
    { 
     //Remove previous formatting, or the decimal check will fail 
     string value = textBox1.Text.Replace(",", "").Replace("$", ""); 
     decimal ul; 
     //Check we are indeed handling a number 
     if (decimal.TryParse(value, out ul)) 
     { 
      //Unsub the event so we don't enter a loop 
      textBox1.TextChanged -= tb_TextChanged; 
      //Format the text as currency 
      textBox1.Text = string.Format(CultureInfo.CreateSpecificCulture("en-US"), "{0:C2}", ul); 
      textBox1.TextChanged += tb_TextChanged; 
     } 
    } 
0

下面是基本方法,當文本改變其轉換爲十進制,然後將文本更改爲十進制的字符串表示。

textBox1.TextChanged += (s,e) => 
{ 
    var value = Decimal.Parse(textBox1.Text); 
    textBox1.Text = value.ToString("C"); 
} 

您還應該檢查文本框中的非法數字。看看Decimal.TryParse

+0

我在textchange方法下試過這段代碼,但是它似乎給了我(s,e)的紅色錯誤行@Richard Schnider – taji01

+0

糟糕忘了'=>' –

+0

嗨,這對我沒有用。代碼仍然給我一個錯誤。該代碼正確地上升到兩位數然後(錯誤:var value = Decimal.Parse(textBox1.Text);)在此行上。 @理查德施耐德 – taji01

相關問題