c# 从另一个列表框中添加项目 class

c# add items in a listbox from annother class

我想在 class "add" 的 form1 中的列表框中添加项目,但我这样做时它不起作用。请帮忙! 我的代码:

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

        private void label2_Click(object sender, EventArgs e)
        {

        }
        private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
        }


    }
    pulic class Add 
    {
        listBox1.Items.Add("test"); //i want somthing that work like this, because so it doesn't work xD
    }
}

Form1 class 中创建一个方法,将调用该方法来更新列表框。 这种方法可以解决问题:

 public void UpdateList(string value)
 {
     listBox1.Items.Add(value);
 }

然后您可以轻松地从您的 class 调用该方法。

祝你好运。

您的代码中有几个问题。
首先,您应该为您的列表框指定一个名称:

<ListBox Name="listBox1" HorizontalAlignment="Left" Height="100" VerticalAlignment="Top" Width="100"/>  

那么你应该在一个函数里面写旅游代码而不是在 class.

    public static class ListBoxAdder
    {
        public static void Add(ListBox listbox, string newItem)
        {
            listbox.Items.Add(newItem);
        }
    }

使用这个 class :

ListBoxAdder.Add(listBox1, "first");

希望对您有所帮助。

只需在构造函数中调用Add():

namespace Server_Virtual_Server_Programm
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();

            listBox1.Items.Add("test");
        }
    }
}