-1

I am attempting to add a string from frmAddSegment to the listbox in frmMain. frmMain is open when doing this process, just for some reason the string is not being added to the listbox.

I've checked the string I'm attempting to add the listbox by using a message box and it is working fine, it's just not getting to the lsitbox. The modifier property on the listbox has also been set to public

frmMain fmain = new frmMain();
    fmain.lstbxSegments.Items.Add(segmentPBMin.ToString()+":"+segmentPBMin.ToString()+"."+segmentPBMils);

I expected the listbox to contain a new item however it remains blank.

Ethan
  • 115
  • 9
  • 2
    You’re creating a new instance of the form, it won’t affect the one already existing. Provide a reference to the actual form to the other or use events. And add a method, don’t let other forms poke at another’s UI controls directly – Sami Kuhmonen Jun 20 '19 at 04:53
  • How do I refer to the already opened instance of the form? If I use ```frmMain``` instead of ```fmain``` in the second line I get an error which reads "An object reference is required for the non-static field, method or property frmMain.lstbxSegments" – Ethan Jun 20 '19 at 04:56
  • As I said, you have to give the reference to the existing form to the other one, for example in the constructor. – Sami Kuhmonen Jun 20 '19 at 05:09
  • 2
    Possible duplicate of [how to access listview of other form](https://stackoverflow.com/questions/15114352/how-to-access-listview-of-other-form) – Sami Kuhmonen Jun 20 '19 at 05:17
  • See also the notes here: [How to link 2 labels in 2 different forms](https://stackoverflow.com/a/54749745/7444103) and here: [How can I transfer text from a datagridview in one form to a private textbox in another form](https://stackoverflow.com/a/53473304/7444103). Or simpler, here [How can I get button's background color and send it to other form?](https://stackoverflow.com/a/50161950/7444103) – Jimi Jun 20 '19 at 07:36

1 Answers1

1

frmMain fmain = new frmMain();

You are creating a brand new instance of "frmMain", and adding your item to that instance rather than the one currently running. You should instead do:

the_Form_That_Is_Open_Right_Now.lstbxSegments.Items.Add(... your code here);

If you're having trouble finding where your form is created, you can hit Ctrl+F, make sure the filter is set to "Entire Solution", and search for new frmMain(). You might see something that looks like this:

Application.Run(new frmMain());

You can store that instance in a variable like so:

frmMain yourForm = new frmMain(); 
Application.Run(yourForm);
Bip901
  • 590
  • 6
  • 22