Search code examples
c#asp.netdatatextfield

DataTextField from field's property


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!


Solution

  • 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";