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

如何从Form1的ListBox获取选中Student对象到Form3更新其属性

解决WinForms中窗体间传递选中对象的问题

问题根源

你在Form3中创建了一个全新的Form1实例,这和当前正在运行的主窗体不是同一个对象,所以listBox.SelectedItem必然是空值,自然拿不到选中的Student对象。

解决方案

通过构造函数传递对象的方式,把Form1中选中的Student直接传给Form3,具体步骤如下:


1. 修改Form3,添加接收Student的构造函数

public partial class Form3 : Form
{
    private Student _currentStudent;

    // 新增构造函数,接收选中的Student对象
    public Form3(Student student)
    {
        InitializeComponent();
        _currentStudent = student;
    }

    private void Form3_Load(object sender, EventArgs e)
    {
        if (_currentStudent != null)
        {
            txtName.Text = _currentStudent.Name;
            // 把三项成绩绑定到对应的输入框
            txtScore1.Text = _currentStudent.Score1.ToString();
            txtScore2.Text = _currentStudent.Score2.ToString();
            txtScore3.Text = _currentStudent.Score3.ToString();
        }
    }

    // 保存按钮点击事件:更新成绩
    private void btnSave_Click(object sender, EventArgs e)
    {
        if (_currentStudent == null) return;

        // 解析输入的成绩并赋值(做合法性校验)
        if (int.TryParse(txtScore1.Text, out int score1))
            _currentStudent.Score1 = score1;
        if (int.TryParse(txtScore2.Text, out int score2))
            _currentStudent.Score2 = score2;
        if (int.TryParse(txtScore3.Text, out int score3))
            _currentStudent.Score3 = score3;

        this.DialogResult = DialogResult.OK;
        this.Close();
    }
}

2. 修改Form1的按钮点击事件,传递选中的Student

private void btnUpdate_Click(object sender, EventArgs e)
{
    // 先判断ListBox是否有选中的Student对象
    if (listBox.SelectedItem is Student selectedStudent)
    {
        using(Form3 frm = new Form3(selectedStudent))
        {
            DialogResult result = frm.ShowDialog();
            if (result == DialogResult.OK)
            {
                // 刷新ListBox显示,确保修改后的成绩能展示出来
                listBox.Refresh();
            }
        }           
    }
}

额外说明

  • 确保Student是引用类型(用class定义,不是struct),这样传递的是对象引用,Form3中修改后Form1的ListBox里的对象会自动同步更新。
  • 如果ListBox显示的内容没有更新,需要在Student类中重写ToString()方法,比如:
    public class Student
    {
        public string Name { get; set; }
        public int Score1 { get; set; }
        public int Score2 { get; set; }
        public int Score3 { get; set; }
    
        public override string ToString()
        {
            return $"{Name} - {Score1}/{Score2}/{Score3}";
        }
    }
    

内容的提问来源于stack exchange,提问作者Oo San

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 03:30:56