如何以不同于使用按钮的形式将列表添加到列表框中

How to add list into list box on a different form from using a button

我试图通过使用按钮和 for 循环以不同的形式添加到列表框,但是它说 "Clothes" 不包含列表框的定义,我将列表框设置为public 因为那是我在网上找到的,但没有解决问题。它就像它无法识别,即使我输入 Clothes dot 并且不在下拉菜单中。我也试过 F.CustomersList 但这也不起作用。

private  void LoadCity_Click(object sender, EventArgs e)       
{        
    Form F = new Clothes();

    if (F.ShowDialog() == DialogResult.OK)
    {
        for (int i = 0; i < _Mexico.Count; i++)
        {
            Clothes.CustomersList.Items.Add(_Mexico.ElementAt(i));
        }
    }             
}

为此,您必须在 Click_Event 中创建一个列表并将其设置为另一个表单的 CustomersList 属性。

private Form custForm;

private void LoadCity_Click(object sender, EventArgs e)   
{
    if(custForm == null)
    {
        custform = new Clothes(); //Clothes should be a Form
    }
    List cust = new List();
    for(int i = 0; i < _Mexico.Count; i++)
    {
        cust.add(_Mexico.ElementAt(i);
    }
    custform.CustomersList = cust;
}

属性 应该是这样的:

private List _CustomersList;
public List CustomersList
{
    get
    {
         return _CustomersList;
    }
    set
    {
        _CustomersList = value;
        //then do your stuff here
    }
}

除了在用列表关闭表单后将内容放入列表没有意义之外,您还必须从

更改表单的初始化
Form F = new Clothes()

Clothes F = new Clothes()

因为 System.Windows.Forms.Form 不包含您的 public 列表。然后您可以通过

访问您的列表框
F.CustomersList.Items.Add(_Mexico.ElementAt(i))

刚刚看到Rufus在他的评论中已经提到了,也许你得想多了你的设计。