DataTextField from field's property

943 views Asked by At

I have class something like

public class A
{
    public string name;
}

public class B
{
    public int Id;
    public A obj;
}

Then, I have ASP.NET WebForms application and page with ListBox control.

I want to set List<B> as DataSource of ListBox.

List<B> list = ...; //fill data
lbx.DataSource = list;
lbx.DataValueField = "Id";
lbx.DataTextField = A.name; //how can I do it?
lbx.DataBind();

So, my question is: how can I link DataTextField to property of object in list?

Thank you!

2

There are 2 answers

0
Ashish Charan On BEST ANSWER

You can make a property in the B class for the Name. For Example

public class B
{
public int Id;
public A obj;
public string Name{ get {return obj.name;}}
}

use it as lbx.DataTextField = "Name";

0
Rex On

Not sure whether the listbox control you are using supports Nested properties ( I knew some third party control does it), something like this:

lbx.DataTextField = "obj.name"

If it does not support, then wrap the nested property of A into another readonly property of B:

public class B
{
    public int Id;
    public A obj;
    public string NameOfA
    {
       Get{return obj.name;}
    }
}

then:

lbx.DataTextField = "NameOfA"