Stephen M. Redd
Stephen M. Redd

Reputation: 5428

ListView - Can you set DataKeyNames when binding to a simple scalar array?

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?

Upvotes: 2

Views: 3792

Answers (2)

Keltex
Keltex

Reputation: 26426

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

Upvotes: 2

craigmoliver
craigmoliver

Reputation: 6562

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

Upvotes: 0

Related Questions