views:

117

answers:

3

I have a list of objects that contain a composite key because of the legacy database that supports multi-tenancy. How can I then bind that list to a checkbox list in asp.net? We're currently using c# 3.5.

Here's the class:

public class SiteKey
{
    public int Id { get; set; }
    public int CustomerId { get; set; }
}
public class Order
{
    public SiteKey Key { get; set; }
    public string Name { get; set; }
}

My repository returns an IList<Order> that I want to then bind to a checkbox list. This code:

chkList.DataValueField = "Key";
chkList.DataTextField = "Name";

displays properly, but the value (chkList.Items[0].Value) coming back simply contains "MyAssemblyName.SiteKey" and not the key.

How can I effectively accomplish this?

Thanks!

A: 

Are you able to modify the Order class? Using SiteKey as the valuefield return Type (unless you override the ToString() method).

public class Order
{
    public SiteKey Key { get; set; }
    public int KeyId { get{return Key.Id;} }
    public string Name { get; set; }
}

chkList.DataValueField = "KeyId";
chkList.DataTextField = "Name";
o.k.w
+2  A: 

Override ToString() on SiteKey to return a concatenated string containing string representations of the properties that make up the primary key. You'll then have to parse the Value property of the item to retrieve the keys.

public class SiteKey
{
    public int Id { get; set; }
    public int CustomerId { get; set; }

    public override string ToString()
    {
        return Id.ToString() + "|" + CustomerId.ToString();
    }
}

and in the method that retrieves the key:

string[] siteKey = chkList.Items[0].Value.Split('|');
int id = int.Parse(siteKey[0]);
int customerId = int.Parse(siteKey[1]);
Jamie Ide
worked like a charm. many thanks!
Chris Conway
A: 

Jamie's suggestion is good, but instead of overriding ToString(), I would just project your IList<Order> into IEnumerable<ListItem> before binding:

ie:

var items = 
    from o in dataList // dataList being IList returned from repository
    select new ListItem(o.Name, 
                        String.Format("{0}|{1}", 
                                      o.Key.Id, o.Key.CustomerId));

// ... bind items to dropdown ...

I prefer this rather than overriding ToString(), as ToString() is generic and used everywhere and can therefore be a pain in the arse, whereas this is a local modification that doesn't affect anything else.

Sam