Closing a User Control from itself
-
Hi, Does anyone know how I can remove a user control from a panel it has been added too, by a button on itself. Like an x button. Cheers, Chris
try by using
Dispose()
method. Calin -
Hi, Does anyone know how I can remove a user control from a panel it has been added too, by a button on itself. Like an x button. Cheers, Chris
-
Hi, Does anyone know how I can remove a user control from a panel it has been added too, by a button on itself. Like an x button. Cheers, Chris
Hi Perhaps you can created a Delegate in the User Control that when fired, will call a method in the parent form that can then remove the User Control. I have not tried the code, but perhaps something like this: In the User Control:
//declare delegate
public event EventHandler RemoveSelf;private void btnRemoveSelf_Click(object sender, EventArgs e)
{
try
{
if (RemoveSelf != null)
{
RemoveSelf(this, e); //Fire event
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}In the parent form:
private void Form_ Load(object sender, EventArgs e)
{
try
{
//Add event handler to User Control
userControl1.UpdateData += new EventHandler(UC_ RemoveSelf);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}private void UC_RemoveSelf(object sender, EventArgs e)
{
try
{
//Code to remove User control
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}As I said I have not tried it, but let me know if it works. Regards. Kobus
-
Hi, Does anyone know how I can remove a user control from a panel it has been added too, by a button on itself. Like an x button. Cheers, Chris
If I where you I should use events and delegates. You make a delegate in your user control and when you click on the button you will call this. An event in the parents control will catch this call. Because it is an event, you can give the user control as parameter. So you can do something like this: -> loop through the panel -> if the name from the 'sender' (which you cast to a control) is one in the panel -> remove this one
-
Just guessing, In the so called 'x' button's clickl
Button btn = sender as Button; UserControl u = btn.Parent as UserControl ; Panel p = u.Parent as Panel ; p .Controls.Remove(u);
(Assuming, Button is in UserControl and UserControl is in the Panel)