【问题标题】:Bind a list of users controls to gridview将用户控件列表绑定到 gridview
【发布时间】:2014-11-28 19:11:30
【问题描述】:

我拼命寻找却徒劳无功。我想将用户控件 (.ascx) 的 List(T) 绑定到 gridview。我在代码隐藏中初始化我的控件:

List<myControl> ctrls = new List<myControl>();
myControl ctr = LoadControl("~/Control.ascx") as myControl;
ctr.Name = ...
// ...
ctrls.Add(myControl); // add new control to the collection

之后,我将此列表绑定到 Gridview 控件:

this.GridView1.DataSource = ctrls;
this.gridView1.DataBind();

在条件为 If (!IsPostBack) 的 Page_Load 事件中。这不起作用:显示对象的表示。而当我将控件放在面板中时,一切正常。

【问题讨论】:

  • 为什么要将它们放在 GridView 中?那有什么目的?为什么不把它们放在一个面板中?
  • 按n个元素分页:/
  • 我想你在这里有一个XY question。
  • 构建一个分页器控件,或者只是在页面中构建一个分页器。您不需要 GridView 的所有开销。即使您想使用 GridView,您也会以错误的方式进行操作。您不会将其绑定到控件列表。您将其绑定到数据,并让模板系统为您创建自定义控件。如果你不需要多列,你应该使用中继器。
  • 使用面板分页的轨道?

标签: c# asp.net gridview


【解决方案1】:

不要为此使用 GridView。使用Repeater。并将其绑定到数据,而不是控件列表。示例:

<asp:Repeater runat="server" id="ControlsRepeater">
    <ItemTemplate>
       <uc:MyControl runat="server" />
    </ItemTemplate>
</asp:Repeater>

代码背后

protected void Page_Load(object sender, EventArgs e)
    {
    if(!IsPostBack)
        {
        var myData=GetData(); //should return some type of ICollection representing your data to bind to
        ControlsRepeater.DataSource=myData;
        ControlsRepeater.DataBind();
        }
    }

如果你想要分页,那么你应该利用lazy loading(如果你使用它,Entity Framework 会为你处理这个)和 Linq 函数.Take() and .Skip()。

【讨论】:

    猜你喜欢
    • 2010-10-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-29
    相关资源
    最近更新 更多