Jam
Jam

Reputation: 339

Why is the control's in panel gets overwrite everytime?

Everytime the button's click event get fired, the label (or any other control) in panel gets overwrite by the new one! Here is the button event.

protected void Button3_Click(object sender, EventArgs e)
{
    Label lbl = new Label();
    lbl.ID = "name";
    lbl.Text = Profession.SelectedItem.ToString();
    Panel1.Controls.Add( lbl);
}

It everytime remove the previous label and add new label with the selected item in DropDownList

Upvotes: 1

Views: 231

Answers (2)

Mohsin
Mohsin

Reputation: 732

Look at the scope of your Label. You are creating a new instance of Label on every click. Take this on class level

Label lbl = new Label();

Upvotes: 0

M. Nasir Javaid
M. Nasir Javaid

Reputation: 5990

Label is getting initialized on every click that is the problem

protected void Button3_Click(object sender, EventArgs e)
{
    Label lbl = new Label();//here on every click new label initialized
    lbl.ID = "name";
    lbl.Text = Profession.SelectedItem.ToString();
    Panel1.Controls.Add(lbl);
}

Replace above code by

Label lbl = new Label();
protected void Button3_Click(object sender, EventArgs e)
{        
    lbl.ID = "name";
    lbl.Text = Profession.SelectedItem.ToString();
    if(!Panel1.Controls.Contains(lbl)) //Check here if label already added
         Panel1.Controls.Add(lbl);
}

Upvotes: 1

Related Questions