从代码隐藏中获取多用户控制中的GridView

时间:2013-01-04 03:52:04

标签: c# asp.net html code-behind

IpInterfaceUC UserControl:

<div id="dvChannel" runat="server" style="height: 205px; width: 550px; overflow: auto;
        margin-left: 5px;">
        <asp:GridView ID="gvChannelUC">
</div>

CodeBehind for Init

int indexInterface=0;
foreach (DataRow row in dtDevicesListByRole.Rows)
{
                    ctrIpInterfaceUC = (Test2.SetupGroup.Ipservice.IpInterfaceUC)LoadControl("IpInterfaceUC.ascx");
                    Control ctr = (Control)ctrIpInterfaceUC;
                    ctr.ID = "device_"+ip+"_"+port+"$"+indexInterface;
                    phDevices.Controls.Add(ctr);//PlaceHolder for add many UserControl
}

Html Show

<div id="dvChannel">
<div id="device_192.168.2.19_3331_0_pnlChannelUC">
  <div id="device_192.168.2.19_3331_0_dvChannel">
    <table id="device_192.168.2.19_3331_0_gvChannelUC">
    </table>
  </div>
</div>
<div id="dvChannel">
<div id="device_192.168.2.19_3331_1_pnlChannelUC">
  <div id="device_192.168.2.19_3331_1_dvChannel">
    <table id="device_192.168.2.19_3331_1_gvChannelUC">
    </table>
  </div>
</div>

问题 如何从多个UserControl获取gridview?

2 个答案:

答案 0 :(得分:1)

通过UserControl上的公共属性公开gridview:

public GridView Grid
{
  get { return gvChannelUC; }
}

然后

List<string, string> Grids = new List<string, string>(); // <UCId, GridId>
...
ctrIpInterfaceUC = (Test2.SetupGroup.Ipservice.IpInterfaceUC)LoadControl("IpInterfaceUC.ascx");
string Id = "device_"+ip+"_"+port+"$"+indexInterface;

GridView ctrGridView = ctrIpInterfaceUC.Grid;
Grids.Add(Id, ctrGridView.ClientID);

Control ctr = (Control)ctrIpInterfaceUC;
ctr.ID = Id
phDevices.Controls.Add(ctr);//PlaceHolder for add many UserControl
...

答案 1 :(得分:0)

虽然您可以递归使用FindControl来查找它,但更好的方法是让UserControl IpInterfaceUC决定如何将数据绑定到其中的控件。

您可以向UserControl添加公共方法ShowData,并将要显示的数据传递给它。然后,它可以将其分配给gvChannelUC

int indexInterface=0;
foreach (DataRow row in dtDevicesListByRole.Rows)
{
    var ctrIpInterfaceUC = (Test2.SetupGroup.Ipservice.IpInterfaceUC)LoadControl("IpInterfaceUC.ascx");
    ctrIpInterfaceUC.ShowData(myRows);
    ctrIpInterfaceUC.ID = "device_"+ip+"_"+port+"$"+indexInterface;
    phDevices.Controls.Add(ctrIpInterfaceUC);//PlaceHolder for add many UserControl
}