如何从其他表单向列表框添加项目? [英] How to add items to a listbox from a different form?

查看:107
本文介绍了如何从其他表单向列表框添加项目?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从form2向form1的列表框中添加新项目.其背后的想法是根据form2活动最终列出不同的项目,每个项目彼此不同(或相同,无关紧要).假设我打开了form1(并且它有购物清单(列表框)),然后我打开了form2,然后单击将在"form1"中的列表中添加香蕉"的按钮.我该怎么做呢?我尝试了各种方法,例如在form1中添加"addToList(parameter)"方法,然后从form2调用它并传递参数,但是列表将保持为空,但是其他内容(例如消息框)将会弹出等.因此,任何想法解决这个问题?

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?

我在表格1中使用此方法将项目添加到列表中,并且可以正常工作:

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();
}

或者:

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

但是它仍然不起作用.尽管当我从form1(事件计划器,列表所在的位置)中使用它时,它的工作情况非常好.我什至将访问修改器更改为公开,所以不应该成为问题.

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.

推荐答案

您可以在Form2上使用公共方法,正如我在对问题的评论中提到的那样.这是一个简单的例子.

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();
    }
}

发件人2

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

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

这篇关于如何从其他表单向列表框添加项目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆