Click here to Skip to main content
15,891,905 members
Please Sign up or sign in to vote.
1.22/5 (3 votes)
See more:
hello friends

this code works
XML
<Grid Name="Layout">
    <TextBlock Name="tbPrueba" Text="Prueba" HorizontalAlignment="Left" VerticalAlignment="Top" Margin="50,20,0,0"/>
    <Button Name="buEliminar" Content="Eliminar" HorizontalAlignment="Left" VerticalAlignment="Top"
            Width="75" Margin="50,56,0,0" Click="buEliminar_Click"/>
</Grid>


C#
private void buEliminar_Click(object sender, RoutedEventArgs e)
{
    UIElement Hijo = Layout.FindName("tbPrueba") as UIElement;
    Layout.Children.Remove(Hijo);
}


but when I add the control from code, this does not work

C#
TextBlock MyTextBlock = new TextBlock()
{
    Name = "tbPrueba",
    Text = "Prueba",
    HorizontalAlignment = HorizontalAlignment.Left,
    VerticalAlignment = VerticalAlignment.Top,
    Margin = new Thickness(50, 20, 0, 0),
};
Layout.Children.Add(MyTextBlock);


...

C#
        private void buEliminar_Click(object sender, RoutedEventArgs e)
        {
// Not work why ?
            UIElement Hijo = Layout.FindName("tbPrueba") as UIElement;
            Layout.Children.Remove(Hijo);
        }

please tell me what's going on
Posted

1 solution

Possibility 1:
C#
private void buEliminar_Click(object sender, RoutedEventArgs e)
{
 UIElement Hijo = (UIElement)LogicalTreeHelper.FindLogicalNode(Layout, "tbPrueba");
 //UIElement Hijo = Layout.FindName("tbPrueba") as UIElement;
 Layout.Children.Remove(Hijo);
}


Details:
http://msdn.microsoft.com/en-us/library/system.windows.logicaltreehelper.findlogicalnode.aspx[^]

Possibility 2:
C#
TextBlock MyTextBlock = new TextBlock()
     {
       Name = "tbPrueba",
       Text = "Prueba",
       HorizontalAlignment = HorizontalAlignment.Left,
       VerticalAlignment = VerticalAlignment.Top,
       Margin = new Thickness(50, 20, 0, 0),
     };
     Layout.Children.Add(MyTextBlock);
     this.RegisterName("tbPrueba", MyTextBlock);



C#
private void buEliminar_Click(object sender, RoutedEventArgs e)
{
 //UIElement Hijo = (UIElement)LogicalTreeHelper.FindLogicalNode(Layout, "tbPrueba");
 UIElement Hijo = Layout.FindName("tbPrueba") as UIElement;
 Layout.Children.Remove(Hijo);
}



There is something written about that:
http://stackoverflow.com/questions/1755377/why-cant-i-access-a-textbox-by-name-with-findname[^]
 
Share this answer
 
v2
Comments
Cesitar Ps 12-Aug-13 13:14pm    
thank you very much my friend, this works

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900