【问题标题】:TextBox String To Double, error Empty TextBox in C#TextBox String To Double,C#中的错误Empty TextBox
【发布时间】:2014-07-28 16:47:03
【问题描述】:

我希望有人可以帮助我。

我在 C# 中创建了一个 Windows 窗体,但我在使用 TextBox 时遇到了一些问题。我是编程新手。

///variables
double n, x, i = 15.0, act = 25.0, f, z;
string ac;
int n2, pos, f2;


///Form1 Load
private void Form1_Load(object sender, EventArgs e)
{
    ///This allow to have decimal with the initial value of 25.0
    textBox2.Text = string.Format("{0:0.0}", act);
}

///TextBox2
private void textBox2_TextChanged(object sender, EventArgs e)
{

    if (textBox2.Text != null )
    {
        ac = Convert.ToString(textBox2.Text);
        z = double.Parse(textBox2.Text);


        if (z >= 0.0 && z <= 30.0)
        {
            ///Operations
            f = 30.0 - z;
            f2 = (int)f * 5;

            this.pictureBox4.Size = new System.Drawing.Size(25, f2);

        }

        if (textBox2.Text == "")
        {
            ///Operations
            z = 0.0;
            textBox2.Text = "0,0";

            this.pictureBox4.Size = new System.Drawing.Size(25, 150);


            ///Message that say value is not between 0.0 and 30.0 
            MessageBox.Show("Enter values between 0.0 y 30.0", "Value out of range", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
        }

我想在 textBox2 中输入一个十进制值。但是,当我按返回键删除 25.0 时,它返回此错误: mscorlib.dll 中发生了“System.FormatException”类型的未处理异常 附加信息:输入字符串的格式不正确。我想修复这个错误,用键盘输入值是空的,如果 textBox2 上的值超出,这个值将在 0.0 和 30.0 之间range 它应该显示一条消息,指出值不在 0.0 和 30.0 之间。请输入一个值是这个范围。

我也有这个

private void textBox2_MouseUp(object sender, MouseEventArgs e)
{
    MessageBox.Show("Enter values between 0.0 and 30.0");
}

当我用鼠标按下 textBox2 时,使用此代码会显示此消息。

代码的操作是移动和改变两个PictureBox的大小。

更改 PictureBox 的大小可以正常工作,我认为十进制值也可以正常工作,我输入 0.0 到 30.0 之间的值也可以正常工作,问题是当它是空值和负数时。

感谢您的帮助

【问题讨论】:

  • 你的问题需要多解释,我不太明白这个问题
  • @BlueTrin 你很幸运,至少你看到了问题,我什至看不到问题
  • @BlueTrin 我没有完成这个问题哈哈。所有问题都已完成并解释完毕。
  • @Steve 我还没有完成这个问题哈哈。所有问题都已完成并解释完毕。

标签: c# winforms textbox double string


【解决方案1】:

也许你想使用类似的东西:

if(!double.TryParse(textBox2.Text, out z))
    MessageBox.Show("The value cannot be parsed");

【讨论】:

  • 我不能投票给你,因为我没有声誉。非常感谢你帮助我。
【解决方案2】:

您需要将其转换为 DOUBLE

double strTxt = Convert.ToDouble(txtBox1.text);

【讨论】:

  • @Akemi_Chou 感谢您的回复 :)
猜你喜欢
  • 2021-12-20
  • 2011-10-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-06-03
  • 1970-01-01
  • 2012-09-04
相关资源
最近更新 更多