Form Calling Objects in Other Forms

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

I have a form (formA). This form used to following code on FormA to load a
new form(FormB).

formB f = new formB();
f.ShowDialog();

However: on formB, I am unable to access any object (ListBox) created on
FormA. I have the listbox set to internal, however: I cannot seem to be
able to access the selected value of the listbox. I am using the following
code:

int iVerseID;
VerseGroupUtility.frmMain fMain;
fMain = (frmMain)this.Parent;
iVerseID = (int)fMain.lbGroups.SelectedValue;

I keep getting a System.NullReferenceException error, however: I am 100%
positive that there is a value selected and it has a value.

Would anyone be able to provide some information for what I am missing or
doing wrong?

Thanks
Andy
 
HI andy,

you need to first declare a static variable in the Form1 class like the
following.

public class Form1 : System.Windows.Forms.Form
{

public static Form1 myform1 = null;
//all other codes
............
................

}

write a method to return the listbox value

public string getListBoxValue()
{
return listBox1.Text.ToString();
}


assuming that you are opening form2 in a button click event in Form1, write
the following code in form1


private void btnOpenForm2_Click(object sender, System.EventArgs e)
{
myform1 = this;
Form2 objForm2 = new Form2();
objForm2.Show();
}


now you can access and check the listbox in form1. I have written this in
FormLoad of Form2


private void Form2_Load(object sender, System.EventArgs e)
{
MessageBox.Show(Form1.myform1.getListBoxValue());
}

happy programming!!
pradeep_TP
 
Hi Andy,

The Parent property (Control) is for children in a container control and
does not work for windows forms unless they are MDIChildren.

Overload the constructor in formB to accept a FormA reference and store
this reference for later use.

formB f = new formB(this);

....

private FormA parentReference;

public formB(FormA Aref)
{
this.parentReference = Aref)
}

....

iVerseID = parentReference.lbGroups.SelectedValue;
 
Back
Top