在一个页面上有多个usercontrol实例,但只引用了最后一个控件

时间:2011-06-01 03:56:13

标签: c# jquery asp.net

我有一个UserControl,允许用户上传文件,并在GridView中显示这些文件。在父页面上,我有一个jQuery选项卡控件,我动态添加了UserControl的2个实例(在不同的选项卡上)。第二个实例工作正常,所以我知道控件工作。但是,当我尝试使用第一个实例上传文件时,第二个实例被引用...所以所有属性值,控件名称等都指向第二个实例。

这就是我在父代页面代码隐藏中加载控件的方式:

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; }
}

如何确保正确引用我的用户控件?

2 个答案:

答案 0 :(得分:1)

检查呈现给客户端的实际html和javascript,以确保没有与控件滑动相关的重复ID。

答案 1 :(得分:1)

我认为这是问题

MyControl ucAttachments1 = (MyControl) Page.LoadControl("~/controls/mycontrol.ascx");

MyControl ucAttachments2 = (MyControl)Page.LoadControl("~/controls/mycontrol.ascx");

您正在将同一控件实例引用到两个不同的变量中。所以现在你有两个不同的同一个实例的引用,现在,因为你最后设置了“ucAttachments2”的属性,所以发生的事情是你的第二个控件属性被设置到实例上。因此每当你尝试访问该实例时(通过使用“ucAttachments1”或“ucAttachments2”,您将获得第二个控件的属性。

尝试做:

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);