You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C#如何将文本文件字符串转为整数并显示到numericUpDown控件

问题根因

你当前的代码写反了赋值逻辑:num1.Value.ToString(Convert.ToInt32(InputFile.ReadLine())) 是把控件现有值转成指定格式的字符串,没有给控件的Value属性做任何赋值操作,自然不会有内容显示。另外NumericUpDown的Value是decimal类型,读取到的整数需要做类型转换后再赋值。

读取历史分数修正代码

以下代码兼容9个控件的批量读取,同时加了合法性校验避免转换报错:

try
{
    // 把9个分数控件统一放到数组里,减少重复代码
    NumericUpDown[] scoreControls = { num1, num2, num3, num4, num5, num6, num7, num8, num9 };
    // 一次性读取文件所有行,自动处理流的开启关闭,避免资源泄漏
    string[] allScoreLines = File.ReadAllLines("Course1.txt");

    for (int i = 0; i < scoreControls.Length && i < allScoreLines.Length; i++)
    {
        // 校验读取的内容是否为合法整数,避免格式错误导致崩溃
        if (int.TryParse(allScoreLines[i], out int validScore))
        {
            scoreControls[i].Value = (decimal)validScore;
        }
    }
}
catch (IOException)
{
    MessageBox.Show("加载Course1.txt文件时出错");
}

保存分数代码(覆盖原文件逻辑)

符合你直接删除旧数据写入新分数的要求:

try
{
    NumericUpDown[] scoreControls = { num1, num2, num3, num4, num5, num6, num7, num8, num9 };
    List<string> saveContent = new List<string>();
    foreach (var control in scoreControls)
    {
        saveContent.Add(control.Value.ToString());
    }
    // WriteAllLines默认直接覆盖原文件内容,无需手动删除旧文件
    File.WriteAllLines("Course1.txt", saveContent);
}
catch (IOException)
{
    MessageBox.Show("保存分数到Course1.txt时出错");
}

注意事项

  • 如果程序运行时找不到文件,建议用绝对路径定位文件,比如拼接程序运行目录:Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Course1.txt")
  • 可以提前给NumericUpDown控件设置Minimum和Maximum属性,限制输入分数的合理范围,避免保存非法值

内容的提问来源于stack exchange,提问作者Chad Chadington

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 10:36:06