Skip to content

Access a form from other forms

H Ghasemi

Asked Jul 24, 2009, 5:40 AM EDT3 answers
Share
LinkedInX
Hi,
I have two forms. there is a listBox in form1 and I need to add to this listBox from FORM2.
It is not too hard, but I may need to add an item to another form's listBox.
I mean maybe I will have a third form witch contains a listBox and I must add the item form FORM2 into that listBox.
I hope I could explain curefully.
Please Help
Thanks

3 Answers

Know the answer? Post it. Somebody with the same question will find it here.

  • 0
    One way to approach this would be to write a public method in the form2 which contains the listbox you want to add to from form1s listbox. eg IN FORM2 public void DisplayNewItem(String newItem) { listbox2.Items.add(newItem.toString()); } Then from form1 you can create an instance of that form and what you call it you can access the DisplayNewItem method if its public. Eg. form2 frmSecondForm = new form2(); frmSecondForm.DisplayNewItem(listbox1.Items[0].ToString()) or wat ever change the 0 to the item u want to add hope this helps
    0
  • 0
    Thanks for your reply, but I think I could not explain carefully. I have several Forms. for example frm1, frm2, frm3 and frm4. In these forms I have a listbox. I have another form for example 'frmText' which has a TextBox and a Button. I must go from one of those forms into 'frmText' and after clicking the button in 'frmText', the text in TextBox must be added into the listbox. The main problem is it: It is not certain, that I come from which form. I mean maybe I call 'frmText' from frm1 or frm2 or so on. When I call formText from frm1 The TextBox contain must be added into the listbox that is in frm1. When I call formText from frm2 The TextBox in frmText contain must be added into the listbox that is in frm2. I hope I could explain good Thanks Again
    0
  • 0
    A quick and dirty way would be to maintain static properties of each form at Program scope. 

    Program
    {
        public static Form1 f1;
        public static Form2 f2;
        public static Form3 f3;
        public static Form4 f4;
    }

    and then assign those values on form load

    Form1
    {
       OnFormLoad()
       {
           Program.f1 = this;
       }
    }

    You can then access the form members across the whole application.  This opens you up to threading issues though, so beware.
    0