tags:

views:

1171

answers:

2

I have a case that keeps coming up where I'm using a ListView or similar control with a simple array such as string[].

Is there a way to use the DataKeyNames property when you are binding to simple collections?

A: 

Try using a Generic List with objects object. The example below is C# 3.0. Say you want a list of letters:

public class LettersInfo
{
    public String Letter { get; set; }
}

then make a list:

List<LettersInfo> list = new List<LettersInfo>();
list.add(new LettersInfo{ Letter = "A" });
list.add(new LettersInfo{ Letter = "B" });
list.add(new LettersInfo{ Letter = "C" });

then bind it to the listview

lv.DataKeyNames = "Letter";
lv.DataSource = list;
lv.DataBind();
craigmoliver
+1  A: 

You could do this with Linq:

string [] files = ...;

var list = from f in files
    select new { Letter = f };

// anonymous type created with member called Letter

lv.DataKeyNames = "Letter";
lv.DataSource = list;
lv.DataBind();
Keltex