How to bind a List 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.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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

Method 2

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

Method 3

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); } );

Method 4

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;

Method 5

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") %>.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x