Reputation: 49
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.
Upvotes: 1
Views: 260
Reputation: 11875
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.
Upvotes: 2
Reputation: 24661
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);
}
Upvotes: 4