简体   繁体   中英

Passing variables in C#

I'm new to C#. I thought I knew a bit of C# but clearly not.

As an example I'm using a very plain form with a button and a custom textbox. Clicking on the button should give me the content of the custom textbox, but I'm getting

Error CS0103 The name 'tb' does not exist in the current context

I have tried all possible options provided but with no luck.

When I use a static textbox (named tb ) from the toolbox then it works without any errors. Below is my code:

public Form1()
{
    InitializeComponent();
}

public void Form1_Load(object sender, EventArgs e)
{
    TextBox tb = new TextBox();

    tb.Dock = System.Windows.Forms.DockStyle.Fill;
    tb.Location = new System.Drawing.Point(600, 430);
    tb.Multiline = true;

    panel2.Controls.Add(tb);
}

public void button1_Click(object sender, EventArgs e)
{
    MessageBox.Show(tb.Text);
}

I have tried to search Google and Stack Overflow, but I'm not sure what to search for.

This is a problem of scope. You are declaring tb in your method, so outside the method it doesn't exist. You want to declare tb outside the method in the class itself:

TextBox tb;

public Form1()
{
    InitializeComponent();
}

public void Form1_Load(object sender, EventArgs e)
{
    tb = new TextBox();

    tb.Dock = System.Windows.Forms.DockStyle.Fill;
    tb.Location = new System.Drawing.Point(600, 430);
    tb.Multiline = true;

    panel2.Controls.Add(tb);
}

public void button1_Click(object sender, EventArgs e)
{
    MessageBox.Show(tb.Text);
}

Your tb variable is defined in the context of Form_Load() . Then it is added to the panel, then it goes out of scope. You need to find another way to get access to your text box... for example by making it a member variable of the class.

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