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

WinForm开发:将文本框信息存入锯齿数组并在列表框展示的问题

解决方案:实现角色信息存储与列表框展示

首先,你当前的代码里有个关键问题:Arr是构造函数里的局部变量,窗体初始化完成后这个数组就会被销毁,根本没法持久保存用户输入的角色数据。咱们先把这个问题解决,再一步步实现存储和展示功能。

1. 重构数组为类成员变量

把数组移到窗体类的级别,同时加一个变量记录当前已添加的角色数量(防止数组越界):

public partial class Form1 : Form
{
    // 类级别成员变量,全程保存角色数据
    private string[][] _characterArray;
    // 记录已添加的角色数,初始为0
    private int _currentCharCount = 0;

    public Form1()
    {
        InitializeComponent();
        // 初始化锯齿数组:3行对应姓名/力量/敏捷,每行最多存20条数据
        _characterArray = new string[3][];
        _characterArray[0] = new string[20]; // 第一行存姓名
        _characterArray[1] = new string[20]; // 第二行存力量
        _characterArray[2] = new string[20]; // 第三行存敏捷
    }
}

2. 实现添加按钮的点击逻辑

假设你有三个文本框(txtName、txtStrength、txtDexterity)和一个添加按钮(btnAdd),双击按钮生成点击事件,填入以下代码:

private void btnAdd_Click(object sender, EventArgs e)
{
    // 第一步:验证输入是否为空
    if (string.IsNullOrWhiteSpace(txtName.Text) || 
        string.IsNullOrWhiteSpace(txtStrength.Text) || 
        string.IsNullOrWhiteSpace(txtDexterity.Text))
    {
        MessageBox.Show("请填写完整的角色信息!");
        return;
    }

    // 第二步:检查数组是否还有剩余空间
    if (_currentCharCount >= 20)
    {
        MessageBox.Show("角色数量已达上限(最多20个)!");
        return;
    }

    // 第三步:把输入值存入锯齿数组
    _characterArray[0][_currentCharCount] = txtName.Text.Trim();
    _characterArray[1][_currentCharCount] = txtStrength.Text.Trim();
    _characterArray[2][_currentCharCount] = txtDexterity.Text.Trim();

    // 第四步:更新列表框显示
    RefreshCharacterList();

    // 第五步:清空文本框,方便下一次输入
    txtName.Clear();
    txtStrength.Clear();
    txtDexterity.Clear();

    // 第六步:角色计数+1
    _currentCharCount++;
}

3. 编写列表框刷新方法

单独写一个方法来更新列表框内容,把每个角色的三个属性组合成易读的字符串:

private void RefreshCharacterList()
{
    // 先清空列表框,避免重复添加
    listBoxCharacters.Items.Clear();

    // 遍历所有已添加的角色
    for (int i = 0; i < _currentCharCount; i++)
    {
        string name = _characterArray[0][i];
        string strength = _characterArray[1][i];
        string dexterity = _characterArray[2][i];
        // 格式化显示文本,让用户一眼看懂
        string displayText = $"角色{i+1}:{name} | 力量:{strength} | 敏捷:{dexterity}";
        listBoxCharacters.Items.Add(displayText);
    }
}

额外优化建议

  • 增强输入验证:可以给Strength和Dexterity添加数字验证,用int.TryParse判断用户输入的是否是有效整数,避免非法数据存入。
  • 优化数据结构:锯齿数组虽然能实现需求,但用自定义类+列表会更易读易维护。比如创建一个Character类:
public class Character
{
    public string Name { get; set; }
    public int Strength { get; set; }
    public int Dexterity { get; set; }
}

然后用List<Character> _characters = new List<Character>();替代锯齿数组,添加角色时直接_characters.Add(new Character { Name = txtName.Text, ... }),展示时遍历列表即可。

内容的提问来源于stack exchange,提问作者Jace Yatrakos

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 10:51:22