Jump to content
Search In
  • More options...
Find results that contain...
Find results in...

C# NullReferenceException Problem

Hey!

 

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?

 

       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(LBJan);
            tabPage.Controls.Add(textBoxJan);
    }

    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)
            }
        }
    }

 

Link to post
Share on other sites

You have a public variable of type ListBox, LBJan that you never instantiate and you are attempting to access a property of it in a method (textBoxJan_KeyDown) that will be called multiple times. Your code is a mess.

The single biggest problem in communication is the illusion that it has taken place.

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×