【问题标题】:how do i fix this simple windows forms application我如何修复这个简单的 Windows 窗体应用程序
【发布时间】:2014-12-25 02:55:48
【问题描述】:

我是 C# 的新手,我正在尝试做一个 Windows 窗体应用程序,但遇到了一个问题。所以基本上我的程序做了什么,它从 .txt 文件中读取一个数字,并将其与用户在文本框中输入的数字相乘。然后当用户按下按钮时,它会在另一个文本框中告诉答案。所以我的问题是,当它尝试读取 .txt 文件并将其传输到 double 并乘以它时,出现问题并且程序崩溃。我在下面包含了我的按钮代码'

private void button1_Click(object sender, EventArgs e)
{
    double answer;
    double num;
    double Filename = double.Parse(File.ReadAllText(@"C:/temp/hinnat.txt"));
    num = double.Parse(textBox1.Text);
    answer = Filename * num;
    textBox2.Text = answer.ToString();
}

【问题讨论】:

  • 你得到什么异常?发布异常名称、消息、堆栈跟踪。
  • 文本文件的内容是什么?
  • 这可能是很多事情。该文件不存在。文件或 textbox1 包含无法解析为双精度的值。您需要提供您收到的错误信息,您可以得到进一步的帮助。
  • 无关紧要,但Filenamedouble可怕名称。

标签: c# string io textbox windows-forms-designer


【解决方案1】:

如果文本无效,请改用 TryParse

private void button1_Click(object sender, EventArgs e)
{
    double answer;
    double num;
    double Filename 
    if (double.TryParse(File.ReadAllText(@"C:/temp/hinnat.txt"), out Filename)
       && double.TryParse(textBox1.Text, out num))
    {
        answer = Filename * num;
        textBox2.Text = answer.ToString();
    }
}

【讨论】:

  • 这个解决方案摆脱了错误,但是程序拒绝在文本框上打印答案,基本上当我在文本框1上写数字时按钮什么也不做。此外,我的代码中的错误消息是“输入字符串的格式不正确。”
  • 哦,没关系这个解决方案有效。我不小心在 .txt 文件中的十进制数字中添加了一个点(我傻了)。无论如何,感谢大卫帮助我解决了我的问题。
【解决方案2】:

Double.ParseDouble.TryParse 方法取决于文化,即在某些文化中,小数分隔符是点 ('.'),如 10.5 ,而在其他文化中,小数点分隔符是逗号 (','),如 10,5。这就是为什么如果您不确定文本文件中可能有什么输入或应用程序的当前文化是什么,最好有一个自定义的 TryParse 方法,用点替换任何逗号并解析字符串使用不变文化加倍:

private static bool TryParse(string str, out double result)
{
    // Invariant culture uses dot ('.') as decimal separator, so replace any comma with dot
    if (str.IndexOf(',') != -1)
    {
        str = str.Replace(',', '.');
    }

    // Try parsing with the Invariant culture
    return Double.TryParse(str, NumberStyles.Any, CultureInfo.InvariantCulture, out result);
}

那么你可以这样称呼它:

string fileContent = File.ReadAllText(@"C:/temp/hinnat.txt");
double fileDouble;
if (TryParse(fileContent, out fileDouble))
{
    // Parsing was successfull
    // Your code here
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-03-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-01
    相关资源
    最近更新 更多