当前位置: 代码迷 >> ASP.NET >> ,如何将泛型 Collection<T> 绑定到 GridView
  详细解决方案

,如何将泛型 Collection<T> 绑定到 GridView

热度:6540   发布时间:2013-02-25 00:00:00.0
请教高手,怎么将泛型 Collection<T> 绑定到 GridView
调用一个方法返回Collection <T> 的类型,绑定到GridView后却只能显示第一条的数据,怎样才能使GridView能显示Collection <T> 中全部的数据呢?

GridView1.DataSource   =   Collection <T> ;
GridView1.DataBind();

或者谁能说一下,DataBind的机制呢?


------解决方案--------------------------------------------------------
用objdatasource装起来试试。
------解决方案--------------------------------------------------------
protected void odsYcfswkList_Selected(object sender, ObjectDataSourceStatusEventArgs e)
{
IList <db.Ycfswk> list = e.ReturnValue as IList <db.Ycfswk> ;
if (list == null)
Pager1.Records = 0;
else
Pager1.Records = list.Count;
}
------解决方案--------------------------------------------------------
such as

public class Persion {
// ...
public string FirstName {
get { return _firstName; }
}

// ...
// here Company is another entity type
public Company Company {
get { return _company; }
}

}

ICollection persions;
//persions = new Persion[] { persion1, persion2 };
// or
persions = new ArrayList();
persions.Add(persion1);
persions.Add(persion2);
/* if you under .net 2.0, had better take as following:
* IList <Persion> perions = new List <Persion> ();
* persions.Add(persion1);
* persions.Add(persion2);
*/


GridView1.DataSource = persions;
GridView1.DataBind();

<asp:GridView ID= "GridView1 " runat= "server ">
<Columns>
<asp:BoundField DataField= "FirstName "> </asp:BoundColumn>
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID= "Label1 " Text= ' <%# Eval( "Company.Name ") %> ' runat= "server "> </asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>


Good Luck!
------解决方案--------------------------------------------------------
BTW, if your element in the collection is primary type such as int, double, string...
take as below:


ICollection <string> strColl = new Collection <string> ();
strColl[0]= "hello ";
strColl[1]= "world ";

GridView1.DataSource = strColl;
GridView1.DataBind();

<asp:GridView ID= "GridView1 " runat= "server ">
<Columns>
<asp:BoundField DataField= "FirstName "> </asp:BoundColumn>
<asp:TemplateField>
<ItemTemplate>
<%# Container.DataItem %>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>

Hope helpful!

------解决方案--------------------------------------------------------
sorry,
plz remove the line " <asp:BoundField DataField= "FirstName "> </asp:BoundColumn> " in the codes above.

------解决方案--------------------------------------------------------
T应该是个类,它的属性相当于数据库表的字段
  相关解决方案