This might be quite a strange question since usually people bind to gridview only complex types. But I need to bind a List of Int (the same is for strings). Usually, as 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.
Any idea of which is the "name" to get value of the object? I tried "Value", "" (empty), "this", "item" but no luck.
I'm referring to a gridview in web form
Thank you
Simone
-
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 (asValue) - 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); } );CodeClimber : That was my first approach, but I remember that once I used a specific name to get the value. I guess I've to digg into reflector :)M4N : Quite a complicated solution in my opinion. Look at my answer for a simpler version of the same idea. -
<asp:TemplateField> <ItemTemplate> <%# Container.DataItem.ToString() %> </ItemTemplate> </asp:TemplateField>CodeClimber : With GridView, when using the bind column, you just specify the name. This is good for repeater or with custom columnsTT : Could you use a TemplateFieldCodeClimber : Actually Container will not work You have to get <%# GetDataItem.ToString() %> which is a undocumented method that gets the DataItem -
if you have to write a property name to be render, you have to encapsulate the int (or string) value in a class with a property that returns the value. In the grid you only have to write <%# Eval("PropertyName") %>.
CodeClimber : but the Int doesn't have a PropertyName :)jaloplo : Yes, but you have to create a class like that:class MyInt { public int myValue; public int MyValue { get{ return myValue; } } } -
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;Marc Gravell : Fine for 1-way binding, at least. -
<BoundField DataField="!" />may do the trick.(since BoundField.ThisExpression == "!")
0 comments:
Post a Comment