0

I'm dynamicly creating listboxes in my program and i want to do something with them in another method but it gives me the NullReferenceException exception. What should i do? (i shortned the code a lot, so some things may be missing)

EDIT: i added the code for initializing the listbox and the textbox

    string tabTitle { get; set; }

    public void newTabButton_Click(object sender, EventArgs e)
    {
            TextBox textBoxJan = new TextBox();
            textBoxJan.KeyDown += new KeyEventHandler(textBoxJan_KeyDown);

            ListBox LBJan = new ListBox();

            tabControl1.TabPages.Add(tabPage);
            tabPage.Controls.Add(textBoxJan);
            tabPage.Controls.Add(LBJan);
    }

    public ListBox LBJan;
    public Label sumLabel;

    public void textBoxJan_KeyDown(object sender, KeyEventArgs e)
    {
        if (e.KeyCode == Keys.Enter)
        {
            if (sender is TextBox)
            {
                TextBox textBoxJan = (TextBox)sender;
                LBJan.Items.Add(textBoxJan.Text)
            }
        }
    }
Ziggster
  • 11
  • 2

2 Answers2

1

You are creating a new local ListBox every time you process the click event, so your global LBJan is always going to be null.

Either initialise the list box:

public ListBox LBJan = new ListBox();

or have a check for null in your event handler and only create it the once:

if (LBJan == null) LBJan = new ListBox();
ChrisF
  • 134,786
  • 31
  • 255
  • 325
0

You have not initialised the variable correctly:

 public void newTabButton_Click(object sender, EventArgs e)
    {
            TextBox textBoxJan = new TextBox();
            textBoxJan.KeyDown += new KeyEventHandler(textBoxJan_KeyDown);

            ListBox LBJan = new ListBox();
    }

    public ListBox LBJan;

LBJAN needs to be set in the newTabButton_click and not a new variable. it should be :

 public void newTabButton_Click(object sender, EventArgs e)
    {
            TextBox textBoxJan = new TextBox();
            textBoxJan.KeyDown += new KeyEventHandler(textBoxJan_KeyDown);

            this.LBJan = new ListBox();
    }

    public ListBox LBJan;

If you want to hold the data, then you can use the Tag method of textbox to hold the data. you can then retrive the object later on in the other events.

https://msdn.microsoft.com/en-us/library/system.windows.forms.control.tag(v=vs.110).aspx

Avneesh
  • 654
  • 4
  • 6
  • So i added the code for initializing but how i needed them – Ziggster May 07 '16 at 16:56
  • You have got problem that each textbox created is going to fire the same event. Hence set the textbox. Tag=LBJan;. Now in the key down event, you can get the LBJan object from Tag and add item to it. – Avneesh May 07 '16 at 17:01