user2613455
user2613455

Reputation: 53

How to Remove Dynamically Added Controls in wpf

I am not able to delete dynamically added controls in button click event. Let me know how to do this.

public void populateform(ArrayList list)
{
  int i = 1;
  int count = 0;

  foreach (string cartitems in list)
  {
    Label lbl = new Label();
    lbl.Name = "myLabel"+i;

    lbl.Content = cartitems.ToString();
    mystackpanel.Children.Add(lbl);
    i++;
    ++count;
    if (count % 3 == 0)
    {
      Button btndelete = new Button();
      btndelete.Content = "Delete";

      btndelete.Width = 120;
      btndelete.Height = 35;
      btndelete.Click += new RoutedEventHandler(btndelete_Click);

      mystackpanel.Children.Add(btndelete);                    
    }
  }
}

private void btndelete_Click(object sender, RoutedEventArgs e)
{
  Label lbl2 = (Label)this.mystackpanel.FindName("myLabel2");
  this.mystackpanel.Children.Remove(lbl2);               
}

Upvotes: 5

Views: 10730

Answers (2)

Clemens
Clemens

Reputation: 128136

From the Remarks section in FindName:

FindName operates within the current element's namescope. For details, see WPF XAML Namescopes.

In short, you have to call RegisterName in order to make FindName work for dynamically created elements.

lbl.Name = "myLabel" + i;
lbl.Content = cartitems;
mystackpanel.Children.Add(lbl);
mystackpanel.RegisterName(lbl.Name, lbl); // here

It might however be easier to find an element by name like shown below, without using FindName.

var element = mystackpanel.Children
    .OfType<FrameworkElement>()
    .FirstOrDefault(e => e.Name == "myLabel2")

Upvotes: 9

Butzke
Butzke

Reputation: 561

Label lbl = (Label)LogicalTreeHelper.FindLogicalNode(mystackpanel, "myLabelx");
mystackpanel.Children.Remove(lbl);

Upvotes: 4

Related Questions