簡體   English   中英

文本框接受Windows Form C#中的所有值

[英]Text Box to accept all values in Windows Form C#

我已經寫了一個用於算術運算的程序。 結果運行良好。 但我想繼續前進。 我想要一個文本框,它接受所有值,例如正值,負值,十進制值(整數,浮點數,長整數,雙精度),例如字符串或字符。 輸入String或Character時,它應該引發錯誤消息(我將在try和Catch的消息框中執行此操作)

private void button1_Click(object sender, EventArgs e)
{
int num1, num2, res;
num1 = int.Parse(textBox1.Text);
num2 = int.Parse(textBox2.Text);
res = num1 * num2;
textBox3.Text = (num1 * num2).ToString();
}

使用TryParse ,將num1num2類型更改為最通用的一種( double ):

private void button1_Click(object sender, EventArgs e) {
  // double as the most general numeric type
  double num1, num2;

  if (!double.TryParse(textBox1.Text, out num1)) {
    if (textBox1.CanFocus) 
      textBox1.Focus();

    MessageBox.Show(String.Format("\"{0}\" is not a valid value", textBox1.Text));
  } 
  else if (!double.TryParse(textBox2.Text, out num2)) {
    if (textBox2.CanFocus) 
      textBox2.Focus();

    MessageBox.Show(String.Format("\"{0}\" is not a valid value", textBox2.Text));
  }
  else
    textBox3.Text = (num1 * num2).ToString();
}

您可以使用try catch,並將變量用作float,以便可以在文本框輸入中自由輸入float和int數據

  private void button1_Click(object sender, EventArgs e)
  {
    float num1, num2, res;
    try
          {
             num1 = float.Parse(textBox1.Text);
          }
        catch (Exception)
          {
             MessageBox.Show("Error");       
          }
        try
          {
             num2 = float.Parse(textBox2.Text);
          }
        catch (Exception)
          {
             MessageBox.Show("Error");      
          }
    res = num1 * num2;
    textBox3.Text = (num1 * num2).ToString();
  }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM