Click here to Skip to main content
15,885,365 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,

I want to remove user control from it's parent by code inside the user control

,then if the parent is StackPanel i use:

C#
(this.Parent as StackPanel).Children.Remove(this);


but the parent is not for StackPanel only, so i have to make type of conversion of "as" to be dynamic, by using this code

C#
 Type parentType = this.Parent.GetType();
(this.Parent as parentType ).Children.Remove(this);


but this is error :
Error	15	The type or namespace name 'parentType' could not be found (are you missing a using directive or an assembly reference?)


so, is it any solution to close/dispose/remove the usercontrol from it's code self?


Thank you.
Posted

C#
StackPanel panel = this.Parent as StackPanel;
if (panel != null) {
   panel.Children.Remove(this);
}

should do it.
 
Share this answer
 
Comments
Irvan Munadi 19-Dec-13 5:34am    
It's only work if the parent of usercontrol is StackPanel.
i want it to be dynamic, without hardcode the entire Object that could have children.
Given your hierarchy, you will have to write a conversion operator.

check below sample code:

Class 1:
public class obj1
{
public string a;

public void test1()
{
}
}


Class 2:
public class obj2
{
public string b;

public void test2()
{
}

public static explicit operator obj2(obj1 b)
{
return new obj2
{
b = b.a
};
}
}

CONVERSION:
obj1 o1 = new obj1();
o1.a = "new_text";
obj2 o2 = (obj2)o1; //converting object of type obj1 to obj2



Check if you are able to typecast "this.Parent" to ParentType
 
Share this answer
 
v2
Comments
Irvan Munadi 19-Dec-13 5:39am    
My point is i have to store the obj2 type and convert some object to that type
this same as

Type parentType = this.Parent.GetType();
((parentType)this.Parent).Children.Remove(this);

and also generate same error

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