1

I'm sure I've got something wrong here but nobody in my team can explain what it is. My goal is to be able to populate a listView item from a button click in another form however a null reference exception is thrown when passing the variables to form1 (System.NullReferenceException: 'Object reference not set to an instance of an object.')

here is my code: Form1:

    AddRec addRec = new AddRec();
    public AddRec AddRec { get; set; }
    public static string viewItem1, viewItem2, viewItem3 = "";

    public void YesClick()
    {
        ListViewItem lvi = new ListViewItem(viewItem1);
        lvi.SubItems.Add(viewItem2);
        lvi.SubItems.Add(viewItem3);
        listView1.Items.Add(lvi);
    }

Form2(AddRec):

    private void btnAdd_Click(object sender, EventArgs e)
    {
        name = txtNameF.Text.ToLower() + " " + txtNameS.Text.ToLower();
        if (name != "")
        {
            num = txtNum.Text;
            mobileNum = txtModNo.Text;

            Form1.viewItem1 = name;
            Form1.viewItem2 = num;
            Form1.viewItem3 = mobileNum;
            Form1.YesClick();

            txtNameF.Text = "";
            txtNameS.Text = "";
            txtNum.Text = "";
            txtModNo.Text = "";
        }
        else
        {
            MessageBox.Show("Fields Required", "Warning");
        }
    }

The idea is that the add button on AddRec populates a listView in Form1 with the text from text boxes in AddRec. The exception is thrown on the Form1.YesClick()

Jake Doe
  • 77
  • 1
  • 8
  • Well, `YesClick()` is not a static method and needs `Form1` object reference! `viewItem1` etc are static and come with the class memory. So, to answer, just make `YesClick()` static and it will work. – praty Oct 13 '17 at 09:36
  • Not quite clear from you code but, `ListViewItem` has a `Subitems` collection check if this is null rather than adding to it directly ( `lvi.SubItems.Add(viewItem2);`) – Milen Oct 13 '17 at 09:37
  • Changing the YesClick() function to static makes listView1 unreadable to the function so cannot add to the listview. Any additional info is very much appreciated :) – Jake Doe Oct 13 '17 at 10:31

1 Answers1

0

You cannot call Form1 like that. You need to call the "opened Form1" before populating or changing it's properties. Try this:

Form1 frm = Application.OpenForms.OfType<Form1>().Take(1).FirstOrDefault();
if (frm != null)
{
  //Populate all your properties here:
  frm.viewItem1 = name;
}
Willy David Jr
  • 6,916
  • 3
  • 34
  • 45