How to add items to a listbox from a different form?

时光怂恿深爱的人放手 提交于 2019-12-11 04:37:52

问题


I am trying to add a new item to a listbox in form1 from form2. The idea behind it is to end up with a list of different items each being different from each other (or the same, doesnt matter) based on the form2 activity. Say I open form1 (and it has shopping list (listbox))and I open form2 and click button which would add "bannana" to the list in form1. How do I do this? I've tryed various ways such as adding "addToList(parameter)" method in the form1 and then calling it from form2 and passing parameters but the list would remain empty however other things such as message box would pop up etc. So any ideas how to solve this?

I am using this method in form one to add the items into the list and it works:

public void addToList()
{
    MessageBox.Show("Adding stuff to list");
    listEvent.Items.Add("New item 1");
    listEvent.Items.Add("new item 2");
    MessageBox.Show("Done adding");
    listEvent.Refresh();
}

Now when I try to call it from another class/form I use this:

public void changeForm()
{
    EventPlanner mainEventForm = new EventPlanner();
    mainEventForm.addToList();
}

Or:

private void btnAddEvent_Click(object sender, EventArgs e)
{
    EventPlanner mainEventForm = new EventPlanner();
    mainEventForm.addToList();
}

But it still doesnt work. Although when I use it from form1 (eventplanner, where the list is) it works perfectly fine. I even changed access modifyer to public so that shouldnt be the problem.


回答1:


You can use a public Method on Form2 as I mentioned in my comment to your question. Here is a simple example.

Form1

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        Form2 frm2 = new Form2();
        if (frm2.ShowDialog(this) == DialogResult.OK)
        {
            listBox1.Items.Add(frm2.getItem());
        }
        frm2.Close();
        frm2.Dispose();
    }
}

From2

public partial class Form2 : Form
{
    public Form2()
    {
        InitializeComponent();
        button1.DialogResult = DialogResult.OK;
        button2.DialogResult = DialogResult.Cancel;
    }

    public string getItem()
    {
        return textBox1.Text;
    }
}


来源:https://stackoverflow.com/questions/14076562/how-to-add-items-to-a-listbox-from-a-different-form

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!