Get GridView in Multiple UserControl from codebehind

冷暖自知 提交于 2019-12-02 21:35:15

问题


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>

Question How do I get gridview from multiple UserControl?


回答1:


Expose the gridview through a public property on your UserControl:

public GridView Grid
{
  get { return gvChannelUC; }
}

Then

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
...



回答2:


While you can recursively use FindControl to find it, a much better approach is to let the UserControl IpInterfaceUC decide how to bind data to the controls within it.

You could add a public method ShowData to you UserControl and pass the data to be displayed to it. It can then assign it to 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
}


来源:https://stackoverflow.com/questions/14150848/get-gridview-in-multiple-usercontrol-from-codebehind

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!