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

C# WinForms跨类解析List中TextBox值始终为0或NaN

问题根源与解决方案

核心问题

你遇到的解析值始终为0或NaN的问题,本质是Class2中获取到的TextBox并非界面上用户输入的实例:

  • CustomTextBox的TextBoxCon()方法每次调用都会创建一批全新的TextBox对象,而非返回已经添加到Panel里的那些。
  • 界面上的TextBox是在ConPanel的AddTextBox方法中创建并添加的,但Class2调用GetTextBoxCon()时,又重新生成了一批空的TextBox,解析它们的Text自然只能得到默认值(空字符串解析为0,无效内容解析为NaN)。

修复步骤

1. 让CustomTextBox保存已创建的TextBox实例

在CustomTextBox类中添加私有字段存储创建好的TextBox列表,避免每次调用都新建:

// 在CustomTextBox类中添加私有字段
private List<System.Windows.Forms.TextBox> _txtBoxCon;

public List<System.Windows.Forms.TextBox> GetTextBoxCon()
{
    // 复用已创建的列表,而非每次调用都新建
    return _txtBoxCon ?? TextBoxCon();
}

public List<System.Windows.Forms.TextBox> TextBoxCon()
{
    // 仅当列表未初始化时才创建新实例
    if (_txtBoxCon != null)
        return _txtBoxCon;

    _txtBoxCon = new List<System.Windows.Forms.TextBox>();

    System.Windows.Forms.TextBox txtConD = DefaultTextBox();
    txtConD.Location = p1;
    txtConD.Tag = 0;

    System.Windows.Forms.TextBox txtCon_d = DefaultTextBox();
    txtCon_d.Location = p2;
    txtCon_d.Tag = 1;

    _txtBoxCon.Add(txtConD);
    _txtBoxCon.Add(txtCon_d);

    // n more textboxes...            

    foreach (var textBox in _txtBoxCon)
    {
        textBox.TextChanged += ConTextBox_TextChanged;
    }
    
    return _txtBoxCon;
}

2. 安全解析用户输入(避免OverflowException)

不要直接用double.Parse,改用double.TryParse做安全校验,防止无效输入导致异常:

public void ConeCalculation()
{
    CustomTextBox ctb = CustomTextBox.Vent();
    List<System.Windows.Forms.TextBox> txtBoxCon = ctb.GetTextBoxCon();

    double pre_dimLarge = 0;
    double dimSmall = 0;
    bool isValid = true;

    // 校验并解析第一个TextBox
    if (!double.TryParse(txtBoxCon[0].Text, out pre_dimLarge))
    {
        isValid = false;
        MessageBox.Show("请输入有效的大尺寸数值");
    }

    // 校验并解析第二个TextBox
    if (!double.TryParse(txtBoxCon[1].Text, out dimSmall))
    {
        isValid = false;
        MessageBox.Show("请输入有效的小尺寸数值");
    }

    if (isValid)
    {
        string message = $"pre_dimLarge: {pre_dimLarge}\n\n dimSmall: {dimSmall}";
        MessageBox.Show(message, "已验证数值");
    }
}

3. 简化单例模式(可选优化)

你的Vent()单例写法可以简化为更简洁的形式:

public static CustomTextBox inst { get; } = new CustomTextBox();
public static CustomTextBox Vent() => inst;

为什么之前的尝试无效?

  • 把List设为静态:你之前可能是在方法内部声明静态List,但每次调用方法还是会覆盖或新建,没有真正复用界面上的实例。
  • 替换为Dictionary:核心问题不是集合类型,而是集合里的TextBox实例不是界面上的那个,所以换集合类型没用。

内容的提问来源于stack exchange,提问作者NICOLAS LEON NARINO

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 09:12:47