如何在TextBox中获取整数值?

时间:2013-06-26 05:09:34

标签: c#-4.0

我在Windows应用程序中有一个文本框。此文本框仅允许整数值而不是字符串。任何人都可以有解决方案吗?

3 个答案:

答案 0 :(得分:0)

使用此功能。

int value = Convert.ToInt32(textBox1.Text);

您使用此代码并获取整数值。谢谢

答案 1 :(得分:0)

转换它。

public int GetIntValue(TextBox tb)
{
    try
    {
        return Convert.toInt32(tb.Text);
    }
    catch (Exception ex)
    {
        //This is called if the converting failed for some reason
    }

    return 0; //This should only return 0 if the textbox does not contain a valid integer value
}

像这样使用:

int number = GetIntValue(textBox1);

希望这有帮助!

答案 2 :(得分:0)

我找到了C# How do I make a textbox that only accepts numbers

的解决方案

希望它会对你有所帮助。

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

        // only allow one decimal point
        if (e.KeyChar == '.' 
            && (sender as TextBox).Text.IndexOf('.') > -1)
        {
            e.Handled = true;
        }
    }
相关问题