I have an aspx web application in which 1 aspx page and 1 web user controls exist. I added 4 instances of the user control in aspx page. There is a remove button in user control which is used to remove the control from the aspx page. If I click on remove button of the user control, how can I find that which user control's remove button is clicked from the aspx page. Please let me know the solution...
Thanks in advance :)
I would add an event to the User Control and capture that event in the code behind. Here's an example:
Default.aspx Web Form:
Register the user control:
<%@ Register TagPrefix="so" TagName="UserControl" Src="~/WebUserControl.ascx" %>
4 instances of the above control. Note we're handling the OnRemoving event defined below:
<so:UserControl ID="UserControl1" runat="server" Title="Control 1" OnRemoving="UserControl1_Removing" />
<so:UserControl ID="UserControl2" runat="server" Title="Control 2" OnRemoving="UserControl2_Removing" />
<so:UserControl ID="UserControl3" runat="server" Title="Control 3" OnRemoving="UserControl3_Removing" />
<so:UserControl ID="UserControl4" runat="server" Title="Control 4" OnRemoving="UserControl4_Removing" />
Default.aspx Code Behind:
In the code behind, I handle each of the control's OnRemoving events:
protected void UserControl1_Removing(object sender, EventArgs e)
{
WebUserControl ctrl = (WebUserControl)sender;
ctrl.Visible = false;
}
protected void UserControl2_Removing(object sender, EventArgs e)
{
WebUserControl ctrl = (WebUserControl)sender;
ctrl.Visible = false;
}
protected void UserControl3_Removing(object sender, EventArgs e)
{
WebUserControl ctrl = (WebUserControl)sender;
ctrl.Visible = false;
}
protected void UserControl4_Removing(object sender, EventArgs e)
{
WebUserControl ctrl = (WebUserControl)sender;
ctrl.Visible = false;
}
User Control Web Form:
The web user control includes a "remove" button:
<%@ Control Language="C#" AutoEventWireup="true" CodeFile="WebUserControl.ascx.cs" Inherits="WebUserControl" %>
<fieldset>
<legend><%=Title %></legend>
<asp:Button ID="Button_Remove" runat="server" Text="Remove" OnClick="Button_Remove_Click" />
</fieldset>
User Control Code Behind:
Finally, here's how to code the event for the user control:
public partial class WebUserControl : System.Web.UI.UserControl
{
// the event delegates may listen for
public event EventHandler Removing;
public string Title { get; set; }
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button_Remove_Click(object sender, EventArgs e)
{
// raise the event for attached delegates
if (Removing != null)
Removing(this, EventArgs.Empty);
}
}
Final Result:
The above example produces the following web page. When a remove button is clicked, that control disappears:
Good luck!!