hello everyone..
i am trying to make a windows form application in c# using visual studio 2008.
in this i have added 1 button. on form load i am adding one label at run time.
now i want to delete that label on click of button1. here is my code--->
private void Form1_Load(object sender, EventArgs e)
{
Label lb = new Label();
lb.Text = "hello";
lb.AutoSize = true;
lb.Visible = true;
lb.name = "l1";
lb.Location = new Point(100, 200);
this.Controls.Add(lb);
}
private void button1_Click(object sender, EventArgs e)
{
this.Controls.RemoveByKey(lb);
}
but i am getting a compilation error that " name lb does not exist in the current context"
what is going wrong.. please HELP...!!!
Deleting a programatically added label in c# win app.
2 Answers
Know the answer? Post it. Somebody with the same question will find it here.


praful nanda7 reputationPosted Jun 15, 2014, 10:48 PM EDT
if you create the object inside the event the scope of that object remains upto that method only. so take the
line
Label lb=new Label() outside the form load event
Piyush chhabra59 reputationPosted Jun 15, 2014, 11:17 PM EDT