简体   繁体   中英

Create an object when a form loads in windows forms

I am going to write a project to present an AVL tree like this: pic

I have two classes: AVLTree & TreePresantation. The problem is I can't use methods of my classes within a Button_Click

  private void Form1_Load(object sender, EventArgs e)
    {
        AVLTree avltree = new AVLTree();
        TreePresantation treePresantation = new TreePresantation(avltree);
    }

    private void BtnPut_Click(object sender, EventArgs e)
    {
        if ((txtPutKey.Text == null) || (txtPutValue.Text == null))
        {
            txtMessage.Text = "Key or Value cannot be empty!";
        }
        else
        {
            treepresantation.Put(Convert.ToInt32(txtPutKey.Text), txtPutValue.Text);
        }
    }

"treepresantation" in btnPut_Click is red under-lined and the error is: Error CS0103 The name 'treepresantation' does not exist in the current context

can anyone help me?

I can't seem to find a duplicate even if it seems there should be one so here it goes.

Your variables are not in the same scope as where you call them so you can't call them.

Here is one way to fix your problem:

public YourClass {

    private AVLTree avltree;
    private TreePresantation treePresantation;

    private void Form1_Load(object sender, EventArgs e)
    {
        avltree = new AVLTree();
        treePresantation = new TreePresantation(avltree);
    }

    private void BtnPut_Click(object sender, EventArgs e)
    {
        if ((txtPutKey.Text == null) || (txtPutValue.Text == null))
        {
            txtMessage.Text = "Key or Value cannot be empty!";
        }
        else
        {
            treepresantation.Put(Convert.ToInt32(txtPutKey.Text), txtPutValue.Text);
        }
    }
}

But as Thomas pointed out you should find a C# tutorial to understand the basics.

Hope this helps.

EDIT

If you don't need to access avltree somewhere else than in Form1_Load you can remove it from your local class properties.

public class Form1
{
    private TreePresantation treePresantation = null;

    private void Form1_Load(object sender, EventArgs e)
    {
        AVLTree avltree = new AVLTree();
        treePresantation = new TreePresantation(avltree);
    }

    private void BtnPut_Click(object sender, EventArgs e)
    {
        if ((txtPutKey.Text == null) || (txtPutValue.Text == null))
        {
            txtMessage.Text = "Key or Value cannot be empty!";
        }
        else
        {
            treepresantation.Put(Convert.ToInt32(txtPutKey.Text), txtPutValue.Text);
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM