views:

573

answers:

5

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

+2  A: 

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); } );
Marc Gravell
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 :)
CodeClimber
Quite a complicated solution in my opinion. Look at my answer for a simpler version of the same idea.
M4N
A: 
<asp:TemplateField>
   <ItemTemplate>
       <%# Container.DataItem.ToString() %>
   </ItemTemplate>
</asp:TemplateField>
TT
With GridView, when using the bind column, you just specify the name. This is good for repeater or with custom columns
CodeClimber
Could you use a TemplateField
TT
Actually Container will not workYou have to get <%# GetDataItem.ToString() %> which is a undocumented method that gets the DataItem
CodeClimber
A: 

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

jaloplo
but the Int doesn't have a PropertyName :)
CodeClimber
Yes, but you have to create a class like that:<code>class MyInt{public int myValue;public int MyValue{get{ return myValue; }}}</code>
jaloplo
+1  A: 

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;
M4N
Fine for 1-way binding, at least.
Marc Gravell
+4  A: 

<BoundField DataField="!" /> may do the trick.

(since BoundField.ThisExpression == "!")

Andrey Shchekin