CPK_2011 CPK_2011 - 3 months ago 26
ASP.NET (C#) Question

How to find the name of the UserControl

I have a UserControl repeated 2 times in a web page named FirstUserControl and LastUserControl.

When the user is changing the value of Textbox in FirstUserControl, how can we identify that the user is currently working on FirstUserControl. I mean how can I get the name of the UserControl as "FirstUserControl" in change event of the UserControl.

The following code is a sample. Need to identify UserControl.Name in this.

protected void txtAmount_TextChanged(object sender, EventArgs e)
{
string ControlName = UserControl.Name;

if(ControlName == "FirstUserControl")
Response.Write ("You are working on FirstUserControl")

if(ControlName == "LastUserControl")
Response.Write ("You are working on LastUserControl")
}

Answer

sender argument contains reference to an object, representing a YourUserControl that fired this event.

So, you should modify your code as follows to get Parent control (or whatever) of control:

protected void txtAmount_TextChanged(object sender, EventArgs e)
{
    Control control = (TextBox)sender;
    while (control as YourUserControl == null)
    {
        control = control.Parent;
    }

    string ControlName = ((YourUserControl)control).Name;

    if(ControlName == "FirstUserControl")
        Response.Write ("You are working on FirstUserControl")

    if(ControlName == "LastUserControl")
        Response.Write ("You are working on LastUserControl")
}

According to msdn:

Server-based ASP.NET Web Forms page and control events follow a standard .NET Framework pattern for event-handler methods.

All events pass two arguments: an object representing the object that raised the event, and an event object containing any event-specific information.