如何找到用户控件的名称
How to find the name of the UserControl
我在名为 FirstUserControl 和 LastUserControl 的网页中重复了 2 次 UserControl。
当用户在FirstUserControl中改变Textbox的值时,我们如何识别用户当前正在FirstUserControl上工作。我的意思是如何在 UserControl 的更改事件中将 UserControl 的名称设为 "FirstUserControl"。
以下代码是示例。需要在此识别UserControl.Name
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")
}
sender
参数包含对对象的引用,表示触发此事件的 YourUserControl
。
因此,您应该按如下方式修改代码以获得控件的父控件(或其他):
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")
}
根据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.
我在名为 FirstUserControl 和 LastUserControl 的网页中重复了 2 次 UserControl。
当用户在FirstUserControl中改变Textbox的值时,我们如何识别用户当前正在FirstUserControl上工作。我的意思是如何在 UserControl 的更改事件中将 UserControl 的名称设为 "FirstUserControl"。
以下代码是示例。需要在此识别UserControl.Name
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")
}
sender
参数包含对对象的引用,表示触发此事件的 YourUserControl
。
因此,您应该按如下方式修改代码以获得控件的父控件(或其他):
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")
}
根据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.