一个页面上有多个用户控件实例,但只有最后一个控件被引用
本文关键字:控件 实例 最后一个 引用 一个 用户 | 更新日期: 2023-09-27 17:58:11
我有一个UserControl
,它允许用户上传文件,并将它们显示在GridView
中。在父页面上,我有一个jQuery选项卡控件,我在其中动态添加了UserControl
的两个实例(在不同的选项卡上)。第二个实例运行良好,所以我知道控件运行良好。然而,当我尝试使用第一个实例上传文件时,第二个实例正在被引用。。。所以所有的属性值、控件名称等都指向第二个。
这就是我在父页面代码后面加载控件的方式:
protected void Page_Load(object sender, EventArgs e)
{
MyControl ucAttachments1 = (MyControl) Page.LoadControl("~/controls/mycontrol.ascx");
ucAttachments1.ID = "ucAttachments1";
ucAttachments1.Directory = "/uploads/documents";
ucAttachments1.DataChanged += new MyControl.DataChangedEventHandler(DoSomething);
phAttachments1.Controls.Add(ucAttachments1);
MyControl ucAttachments2 = (MyControl)Page.LoadControl("~/controls/mycontrol.ascx");
ucAttachments2.ID = "ucAttachments2";
ucAttachments2.Directory = "/uploads/drawings";
ucAttachments2.DataChanged += new MyControl.DataChangedEventHandler(DoSomething);
phAttachmetns2.Controls.Add(ucAttachments2);
}
在html:中
<div id="tabContainer">
<div id="files">
<asp:PlaceHolder id="phAttachments1" runat="server" />
</div>
<div id="drawings">
<asp:PlaceHolder id="phAttachments2" runat="server" />
</div>
</div>
用户控制代码的片段:
private string directory;
override protected void OnLoad(EventArgs e)
{
PopulateAttachmentGridview();
}
protected btnUpload_Click(object sender, EventArgs e)
{
UploadFile(directory);
}
public string Directory
{
get { return directory; }
set { directory = value; }
}
如何确保我的用户控件被正确引用?
检查呈现给客户端的实际html和javascript,以确保没有与从裂缝中滑出的控件相关的重复ID。
我认为这就是的问题
MyControl ucAttachments1 = (MyControl) Page.LoadControl("~/controls/mycontrol.ascx");
MyControl ucAttachments2 = (MyControl)Page.LoadControl("~/controls/mycontrol.ascx");
您正在将控件的同一实例引用到两个不同的变量。所以现在你有了同一个实例的两个不同的引用,现在因为你终于设置了"ucAttachments2"的属性,所以发生的事情是你的第二个控件属性被设置到该实例上。。因此,每当您尝试访问该实例(通过使用"ucAttachments1"或"ucAttacchments2")时,您都会获得第二个控件的属性。
尝试做:
MyControl ucAttachments1 = new MyControl();
ucAttachments1 = (MyControl) Page.LoadControl("~/controls/mycontrol.ascx");
ucAttachments1.ID = "ucAttachments1";
ucAttachments1.Directory = "/uploads/documents";
ucAttachments1.DataChanged += new MyControl.DataChangedEventHandler(DoSomething);
phAttachments1.Controls.Add(ucAttachments1);
MyControl ucAttachments2 = new MyControl();
ucAttachments2 = (MyControl) Page.LoadControl("~/controls/mycontrol.ascx");
ucAttachments2.ID = "ucAttachments2";
ucAttachments2.Directory = "/uploads/drawings";
ucAttachments2.DataChanged += new MyControl.DataChangedEventHandler(DoSomething);
phAttachmetns2.Controls.Add(ucAttachments2);