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

如何将Form2的姓名与分数数据传入Form1的ListBox并正确显示?

问题解决:ListBox显示List类型而非具体分数的修复

问题根源

你看到的Jane Doe | Sysyems.collections.Generic.List’1[Int32]]是因为直接将List<int>对象拼接到字符串中,而List<T>的默认ToString()方法会返回其类型名称,而非遍历元素生成内容。

修复方案

核心是用string.Join()将分数列表中的元素以|分隔拼接成字符串,再与姓名组合成目标格式。

完整代码示例

假设你的Form2中已有存储分数的List<int>集合,以下是关键逻辑的实现:

// Form2的成员变量
private List<int> _scoreList = new List<int>();
private TextBox txtName;
private TextBox txtSingleScore;
private TextBox txtAllScores;
private Button btnAddScore;
private Button btnAccept;

// 添加分数按钮的点击事件
private void btnAddScore_Click(object sender, EventArgs e)
{
    // 验证输入的分数是否合法
    if (int.TryParse(txtSingleScore.Text, out int score) && score >= 0 && score <= 100)
    {
        _scoreList.Add(score);
        // 更新只读TextBox显示所有分数
        txtAllScores.Text = string.Join(" | ", _scoreList);
        txtSingleScore.Clear();
    }
    else
    {
        MessageBox.Show("请输入0-100范围内的整数分数");
    }
}

// 确认按钮的点击事件(AcceptButton逻辑)
private void btnAccept_Click(object sender, EventArgs e)
{
    string userName = txtName.Text.Trim();
    // 验证姓名和分数是否有效
    if (string.IsNullOrEmpty(userName) || _scoreList.Count == 0)
    {
        MessageBox.Show("请输入姓名并至少添加一个有效分数");
        return;
    }

    // 拼接姓名和分数为目标格式
    string scoresStr = string.Join(" | ", _scoreList);
    string finalItem = $"{userName} | {scoresStr}";

    // 将结果传入Form1的ListBox(这里假设Form1是Form2的所有者窗口)
    ((Form1)this.Owner).listBox1.Items.Add(finalItem);
    
    this.Close();
}

补充说明

  1. 如果你的Form2是通过ShowDialog()打开的,也可以通过公共属性暴露结果,在Form1中获取后添加到ListBox:
// Form2中添加公共属性
public string ResultString { get; private set; }

// 在btnAccept_Click中设置属性
this.ResultString = finalItem;
this.DialogResult = DialogResult.OK;

// Form1中调用Form2的逻辑
using (Form2 form2 = new Form2())
{
    if (form2.ShowDialog() == DialogResult.OK)
    {
        listBox1.Items.Add(form2.ResultString);
    }
}
  1. 始终保留输入验证逻辑,避免空姓名或非法分数导致的异常。

内容的提问来源于stack exchange,提问作者Ethan Long

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 11:21:07