如何确定回发是否由用户控件引起
本文关键字:用户 控件 是否 何确定 | 更新日期: 2023-09-27 18:34:14
我尝试了帖子中的建议 哪个控件导致回发,但它在我的情况下不起作用。控件名称以用户控件名称为前缀。有没有办法获取对用户控件上动态添加的控件的引用?
试试这个:
if (IsPostBack)
{
var targetID = Request.Form["__EVENTTARGET"];
if (!String.IsNulOrEmpty(targetID)
{
var targetControl = this.Page.FindControl(targetID);
}
}
您可以让用户控件公开事件。您的 aspx 页代码隐藏应该有一个在此类事件上调用的方法。
public delegate void EventFiredHandler(object sender);
public class MyUserControl: UserControl
{
public event EventFiredHandler EventFired;
//Let all your button clicks in usercontrol share this event sink
void Button1_Click(object sender, EventArgs e)
{
if(EventFired != null)
{
EventFired(sender);
}
}
}
在 aspx 标记中,您可以编写如下内容:
<uc1:MyUserControl runat="server"
EventFired="UCControl_EventFired"></uc1:MyUserControl>
在后面的 aspx 代码中:
protected void UCControl_EventFired(object sender)
{
//Obtaining reference of control in usercontrol
// which caused event
Button btn = (Button) sender;
}
到目前为止,发布的所有答案都不正确。这个是。我在页面加载事件中使用这些函数来检查按钮单击等,并且根本不使用控制事件,因为它们发生得太晚了,而且您必须绑定数据两次。
// Returns true if postback is from current control or one of child controls of current control.
// Returns false if postback is from any other controls (siblings or parents of the siblings) or if there is no postback.
public bool IsPostBackFromCurrentControl()
{
return IsPostBackFromControlOrItsChildren(this);
}
// Returns true if postback is from the control or one of child controls of the control.
// Returns false if postback is from any other controls (siblings, parents of the siblings or parent of current control) or if there is no postback.
public bool IsPostBackFromControlOrItsChildren(Control ctl)
{
if (IsPostBack)
{
string eventTarget = Request["__EVENTTARGET"];
if (eventTarget.StartsWith(ctl.UniqueID) || eventTarget.StartsWith(ctl.ClientID))
return true;
else
return false;
}
return false;
}
// Returns true if postback is from the control.
// Returns false if postback is from any other controls (siblings, parents of the siblings or parent or child of current control) or if there is no postback.
public bool IsPostBackFromControl(Control ctl)
{
if (IsPostBack)
{
string eventTarget = Request["__EVENTTARGET"];
if (eventTarget == ctl.UniqueID || eventTarget == ctl.ClientID)
return true;
else
return false;
}
return false;
}
使用此帮助程序函数查看如何读取原始回发数据:
public void ShowAllPostBackData()
{
if (IsPostBack)
{
string[] keys = Request.Form.AllKeys;
Literal ctlAllPostbackData = new Literal();
ctlAllPostbackData.Text = "<div class='well well-lg' style='border:1px solid black;z-index:99999;position:absolute;'><h3>All postback data:</h3><br />";
for (int i = 0; i < keys.Length; i++)
{
ctlAllPostbackData.Text += "<b>" + keys[i] + "</b>: " + Request[keys[i]] + "<br />";
}
ctlAllPostbackData.Text += "</div>";
this.Controls.Add(ctlAllPostbackData);
}
}