CodeClimber
CodeClimber

Reputation: 4191

How to bind a List<Int> to a gridview?

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

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

I'm referring to a gridview in a web form.

Update

There's a related Stack Overflow question, How to bind a List to a GridView.

Upvotes: 9

Views: 7708

Answers (5)

jaloplo
jaloplo

Reputation: 951

If you have to write a property name to be rendered, you have to encapsulate the integer (or string) value in a class with a property that returns the value. In the grid you only have to write <%# Eval("PropertyName") %>.

Upvotes: -1

Andrey Shchekin
Andrey Shchekin

Reputation: 21619

<BoundField DataField="!" /> may do the trick (since BoundField.ThisExpression equals "!").

Upvotes: 10

M4N
M4N

Reputation: 96596

This is basically the same idea as Marc's, but simpler.

It creates an anonymous wrapper class that you can use as the grid's datasource, and then bind the column to the "Value" member:

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

Upvotes: 2

terjetyl
terjetyl

Reputation: 9565

<asp:TemplateField>
   <ItemTemplate>
       <%# Container.DataItem.ToString() %>
   </ItemTemplate>
</asp:TemplateField>

Upvotes: 7

Marc Gravell
Marc Gravell

Reputation: 1064044

I expect you might have to put the data into 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 a List<Wrapper<T>> instead (as 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); } );

Upvotes: 3

Related Questions