【问题标题】:How to use int in a C# textBox [duplicate]如何在 C# 文本框中使用 int [重复]
【发布时间】:2019-09-16 21:12:02
【问题描述】:

我做了一个使用文本框的计算器。

private void Btnrovnase_Click(object sender, EventArgs e)
    {

        int vysledek;
        vysledek = (int.Parse(textBox1.Text) / int.Parse(textBox2.Text));
        textBox3.Text = vysledek.ToString();

我的代码看起来像这样,但现在我想在其中使用名为 a 的 int。

问题是,有没有办法将 int 放入 textbox1textbox2 中?

【问题讨论】:

  • 不清楚。在文本框中,您可以编写任何您喜欢的内容,直到达到 MaxLength 字符数。您是在问如何强制您的用户只输入数字?
  • 你应该研究数据清理,因为你将两个数字分成一个整数,这并不总是发生,甚至可能不会使用数字。

标签: c# textbox int calculator


【解决方案1】:

如果您只需要数字和数字,您可以使用 NumericUpDown 控件。

但是如果你想要一个 TextBox,你可以使用 KeyPress 事件:

private void NumericTextBox_KeyPress(object sender, KeyPressEventArgs e)
{
  if ( !char.IsDigit(e.KeyChar) ) 
    e.Handled = true;
}

您可以将 NumericTextBox_KeyPress 分配给所有需要的文本框。

如果你想处理诸如小数分隔符之类的东西,你可以使用例如:

System.Globalization.CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator

这样:

string separatorDecimal = CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator;

if ( !char.IsDigit(e.KeyChar) 
  && new string(e.KeyChar, 1) != separatorDecimal )
  e.Handled = true;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-07-23
    • 2021-03-02
    • 2014-08-29
    • 2019-02-07
    • 1970-01-01
    • 2017-07-17
    • 1970-01-01
    • 2015-03-16
    相关资源
    最近更新 更多