首页 > 解决方案 > 努力添加到 ListBox

问题描述

所以我正在为我在大学的作业制作这个小程序,我发现很难在我的表格中添加到我的列表中。这是我的代码:

public partial class WorkOutBeam : Form
{
    Check checkLib;
    public BindingList<ListBox> list;

    public WorkOutBeam()
    {
        InitializeComponent();
    }

    public void StartForm(object sender, EventArgs e)
    {
        list = new BindingList<ListBox>();
        listBox1.DataSource = list;
    }

    private void NewForce_Click(object sender, EventArgs e)
    {
        NewForceName forceItem = new NewForceName();
        forceItem.Show();
    }

    public void AddToForceList(string name)
    {
        list.Items.Add(name);
    }
}

下面的 NewForceName 类:

    public partial class NewForceName : Form
{
    public WorkOutBeam workOutBeam;
    public NewForceName()
    {
        InitializeComponent();
    }

    private void OkButton_Click(object sender, EventArgs e)
    {
        if (NewForceNames.Text != "")
        {
            ReferToLibs();
            workOutBeam.AddToForceList(NewForceNames.Text);
            Close();
        }
    }

    private void ReferToLibs()
    {
        workOutBeam = new WorkOutBeam();
    }

    private void NewForceName_Load(object sender, EventArgs e)
    {

    }
}

所以我对我的程序说,“给我一个新的力量”。当它这样做时,它会初始化一种新形式的“NewForceName”。我在一个文本框中输入并单击“确定”,这将启动一个公共方法,如下所示:

该列表是一个绑定列表,它将列表框作为数据源。但是该程序告诉我,由于受保护,Items 部分无法访问,但我不知道如何将其添加为公共。我尝试查看我的 listBox 的属性,但无济于事。

标签: c#listbox

解决方案


试一试:

public partial class WorkOutBeam : Form
{
    Check checkLib;
    // public BindingList<ListBox> list; // get rid of this for now

    public WorkOutBeam()
    {
        InitializeComponent();
    }

    /*public void StartForm(object sender, EventArgs e)
    {
        list = new BindingList<ListBox>();
        listBox1.DataSource = list;
    }*/

    private void NewForce_Click(object sender, EventArgs e)
    {
        NewForceName forceItem = new NewForceName(this); // pass a reference to this 
                                                         // instance of WorkoutBeam
        forceItem.Show();
    }

    public void AddToForceList(string name)
    {
        // we should do some more things here, but let's keep it simple for now
        listBox1.Items.Add(name);
    }
}

public partial class NewForceName : Form
{
    public WorkOutBeam workOutBeam;
    public NewForceName( WorkoutBeam beam ) // we take a WorkoutBeam instance as CTOR param!
    {
        InitializeComponent();
        workoutBeam = beam;
    }

    private void OkButton_Click(object sender, EventArgs e)
    {
        if (!string.IsNullOrEmpty(NewForceNames.Text))
        {
            workOutBeam.AddToForceList(NewForceNames.Text);
            Close();
        }
    }

    // DO NOT create new WorkoutBeams every time. Use the original.
    /*private void ReferToLibs()
    {
        workOutBeam = new WorkOutBeam();
    }*/
}

免责声明:我没有解决此代码中的每一个问题。这足以让它按预期“工作”。


推荐阅读