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.
<BoundField DataField="!" />
may do the trick (since BoundField.ThisExpression
equals "!").
<asp:TemplateField>
<ItemTemplate>
<%# Container.DataItem.ToString() %>
</ItemTemplate>
</asp:TemplateField>
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); } );
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With