Reputation: 55
I've just recently started with C# and I know this has been kind of asked here before but all with complex examples which i could not really grasp yet. So here is my simple example.
I'm trying to add a string to a ListBox from an added class. It compiles fine but the "TEST" doesn't get added to the ListBox
Form1.cs
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
ListBoxAdder myAdder = new ListBoxAdder();
myAdder.Testing();
}
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
}
}
}
ListBoxAdder.cs
namespace WindowsFormsApplication1
{
class ListBoxAdder : Form1
{
public void Testing()
{
listBox1.Items.Add("TEST");
}
}
}
I assume nothing is happening because of creating another instance of "ListBoxAdder"? But I couldn't make it static because I wouldn't make Testing() static or I would have no access to listBox1
.
Upvotes: 0
Views: 194
Reputation: 5884
namespace WindowsFormsApplication1
{
class ListBoxAdder
{
ListBox listBox;
public ListBoxAdder (ListBox listBox)
{
this.listBox = listBox;
}
public void Testing()
{
listBox.Items.Add("TEST");
}
}
}
And:
private void button1_Click(object sender, EventArgs e)
{
ListBoxAdder myAdder = new ListBoxAdder(listBox1); // pass ListBox instance here
myAdder.Testing();
}
Upvotes: 1