• 0

[C#]Accessing Object in another form


Question

Hi

I have a Main form (form1.cs) and when I click a label on that form a method should be called.

this works and currently displays a MessageBox. However, if there is too much data a message box is no use as it is not scrollable.

So I thought I would create another form when i click the label the same method gets called but instead o

Form child = new Form2();

child.visable = true;

this shows the form as expected

I now want to add a listbox (to use to display the output as this is scrollable)

However I don?t know how to reference that listbox from the main form

I get an error stating

  Quote
The name 'listbox1' does not exist in the current context

How can I make this work?

Thanks

Link to comment
https://www.neowin.net/forum/topic/561097-caccessing-object-in-another-form/
Share on other sites

2 answers to this question

Recommended Posts

  • 0

Could you not declare Form2 to take a string in its constructor, which internally populates the listbox:

public class Form2 : Form
{
		public Form2(string Message)
		{
			   listbox1.Items.Add(Message);
		}
}

Then you call the above as follows:

string displayText = "Text to display";
Form2 child = new Form2(displayText);
child.Show();

You should see your message in the list box.

--- OR ---

You could have a public property on Form2 which returns the listbox:

public class Form2 : Form
{
		 public Form2()
		 {
				mListBox1 = new ListBox();
		 }

		 public ListBox ListBox
		{
				 get { return mListBox1; }
		}

		 private ListBox mListBox1;
}

Then on Form1 (your main form), you can access it as follows:

Form2 child = new Form2();
child.ListBox.Items.Add("Stuffdd");
child.ListBox.Items.Add("Moref To Add");
child.Show();

Hope this helps :)

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.