csharp.tester
csharp.tester

Reputation: 19

c# add items in a listbox from annother class

I want to add items in the listbox in form1 from class "add", but as I did it it doesn't work. Please, help! My code:

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
    }
}

Upvotes: 0

Views: 1305

Answers (3)

Nevca
Nevca

Reputation: 204

Just call Add() in constructor:

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

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

Upvotes: 1

Slashy
Slashy

Reputation: 1881

Create a method in the Form1 class which will be called to update the listbox. This method would do the trick:

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

Then you could easily call the method from your class.

Good luck.

Upvotes: 0

Mohammad Chamanpara
Mohammad Chamanpara

Reputation: 2169

There are a couple of problems in your code.
Firstly you should assign a name to your listbox :

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

Then you should write tour code inside a function not in the class.

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

using this class :

ListBoxAdder.Add(listBox1, "first");

I hope it will help.

Upvotes: 1

Related Questions