繁体   English   中英

C#从另一个类的列表框中添加项目

[英]c# add items in a listbox from annother 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
    }
}

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

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

然后,您应该在类中没有的函数中编写游览代码。

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

使用此类:

ListBoxAdder.Add(listBox1, "first");

希望对您有所帮助。

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

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

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

Form1类中创建一个方法,该方法将被调用以更新列表框。 此方法可以解决问题:

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

然后,您可以轻松地从类中调用该方法。

祝好运。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM