How to bind List <Int> to gridview?

This can be a rather strange question, because usually people only associate complex types with a gridview. But I need to bind List of Int (same for strings). Usually, since the property to bind one uses the property name of the object, but when using Int or String, the value is exactly the object itself, and not the property.

What is the "name" to get the value of an object? I tried "Value", "(empty)," this "," item ", but no luck.

I mean gridview in web form.

Update

There is a related question, How to link a list to a GridView .

+7
list c # gridview
source share
5 answers

<BoundField DataField="!" /> BoundField.ThisExpression <BoundField DataField="!" /> can do the trick (since BoundField.ThisExpression is equal to “!”).

+9
source share
 <asp:TemplateField> <ItemTemplate> <%# Container.DataItem.ToString() %> </ItemTemplate> </asp:TemplateField> 
+4
source share

I expect you to have to put data in a wrapper class - for example:

 public class Wrapper<T> { public T Value {get;set;} public Wrapper() {} public Wrapper(T value) {Value = value;} } 

Then bind to List<Wrapper<T>> instead of (like Value ) - for example, using something like (C # 3.0):

 var wrapped = ints.ConvertAll( i => new Wrapper<int>(i)); 

or C # 2.0:

 List<Wrapper<int>> wrapped = ints.ConvertAll<Wrapper<int>>( delegate(int i) { return new Wrapper<int>(i); } ); 
+3
source share

This is basically the same idea as Mark, but simpler.

Creates an anonymous wrapper class that can be used as a grid data source, and then bind the column to the Value element:

 List<int> list = new List<int> { 1,2,3,4}; var wrapped = (from i in list select new { Value = i }).ToArray(); grid.DataSource = wrapped; 
+2
source share

If you need to write a property name for rendering, you must encapsulate an integer (or string) value in the class with a property that returns a value. In the grid, you need to write <%# Eval("PropertyName") %> .

-one
source share

All Articles