1

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.

Honza Sedloň
  • 514
  • 4
  • 25
  • Is something actually selected in the `ListBox` when you click OK? – MikeH Oct 07 '15 at 16:25
  • Also, which object is null on that line? – MikeH Oct 07 '15 at 16:25
  • @MikeH I dont know which object is null, but it says this: An unhandled exception of type 'System.NullReferenceException' occurred in iTextSharp.exe. But yes, i have actually selected item – Honza Sedloň Oct 07 '15 at 16:27
  • When you have this exception: Hover over each of the items on that line (it will show you the current value of that item). One of those items will be null. – MikeH Oct 07 '15 at 16:28
  • @MikeH Yes, i found it. The error is throwing "udaje" – Honza Sedloň Oct 07 '15 at 16:36
  • Ok, the error is likely in the setter of `udaje`. Set a break point there and find out what is null. BTW, this would probably be a useful read for you:http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it – MikeH Oct 07 '15 at 16:38
  • What does your code look like in Form1, where you construct Form2? Are you sending "this" (which is the pointer to Form1) into your constructor for Form2 or are you sending in null or something else? – Keith Holloway Oct 07 '15 at 16:39
  • @MikeH But, i have used same approach in Form3 to Form2. Everything is good. In Form3 i take string text input and put it into Form2 as ListBox item. And then i take ListBox item, which was taken from Form3 as text and there is problem. Same aprroach used in Form3 and Form2 doesnt work in Form2 and Form1 – Honza Sedloň Oct 07 '15 at 16:52

1 Answers1

0

I just needed to modify from this

Form2 form = new Form2();

To this

Form2 form = new Form2(this);
Honza Sedloň
  • 514
  • 4
  • 25