简体   繁体   English

来自字段属性的DataTextField

[英]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. 然后,我有ASP.NET WebForms应用程序和带有ListBox控件的页面。

I want to set List<B> as DataSource of ListBox . 我想将List<B>设置为ListBox DataSource。

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? 所以,我的问题是:如何将DataTextField链接到列表中对象的属性?

Thank you! 谢谢!

You can make a property in the B class for the Name. 您可以在B类中为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"; 用它作为lbx.DataTextField = "Name";

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: 如果它不支持,则将A的嵌套属性包装到B的另一个只读属性中:

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

then: 然后:

lbx.DataTextField = "NameOfA"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM