Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 233
CodeClimber Avatar asked Feb 05 '09 11:02

CodeClimber


4 Answers

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

like image 100
Andrey Shchekin Avatar answered Nov 13 '22 00:11

Andrey Shchekin


<asp:TemplateField>
   <ItemTemplate>
       <%# Container.DataItem.ToString() %>
   </ItemTemplate>
</asp:TemplateField>
like image 42
terjetyl Avatar answered Nov 12 '22 23:11

terjetyl


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); } );
like image 3
Marc Gravell Avatar answered Nov 13 '22 00:11

Marc Gravell


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;
like image 2
M4N Avatar answered Nov 12 '22 23:11

M4N