Search code examples
c#winformstextboxlistbox

Take selected item from listbox in form2 and put it to Form1 to TextBox


I'm trying take take selectedItem from ListBox in Form2 and put it to TextBox in Form1, but my error is


Object reference not set to an instance of an object


I know what is null object, i know what is it doing and when does it doing, but i can't find my mistake.

My code in Form2, where I have my ListBox

private Form1 mainForm = null;
    public Form2(Form1 callingFrom)
    {
        mainForm = callingFrom as Form1;
        InitializeComponent();
    }
    private void okButton_Click(object sender, EventArgs e)
    {
        this.mainForm.udaje = bankovniUctyList.GetItemText(bankovniUctyList.SelectedItem);
        this.Close();
    }

My code in Form1, where I have my TextBox

 public string udaje
    {
        get { return predmetBanka.Text; }
        set { predmetBanka.Text = value; bankaTextBox.Text = predmetBanka.Text; }
    }

Debugger says, that problem is here

this.mainForm.udaje = bankovniUctyList.GetItemText(bankovniUctyList.SelectedItem);

I have no idea, why is it null.


Solution

  • I just needed to modify from this

    Form2 form = new Form2();
    

    To this

    Form2 form = new Form2(this);