0

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.

5
  • Arent you showing your form? myAdder.Show()? Commented Mar 2, 2017 at 18:20
  • 1
    Why not pass listbox1 to the Testing function? That way you will not have to inherit from Form1. Commented Mar 2, 2017 at 18:21
  • Name your controls better. And I assume you have a listbox on both forms. They are separate entities and have nothing to do with each other. Why do you need a separate class/form for this? Commented Mar 2, 2017 at 18:22
  • You don't need to make it static, but you do need to pass a reference to the actual control. Your assumption at the end is correct, you are instantiating a new copy of ListBoxAdder which hasn't been placed anywhere. Commented Mar 2, 2017 at 18:27
  • You should create instance of ListBoxAdder at the form level and call method on it in button_Click. Creating new instance in every button click will not help you. Commented Mar 2, 2017 at 18:32

1 Answer 1

1
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();
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.