【问题标题】:asp:DropDownList Linq-to-sql data source binding text field to relation-property valueasp:DropDownList Linq-to-sql 数据源绑定文本字段到关系属性值
【发布时间】:2016-06-22 10:47:42
【问题描述】:

所以我使用 Linq-to-sql 与我的 sql 服务器进行通信,我想用我的数据库中的数据填充一个 asp.net 下拉列表。问题是我希望用户可见的文本值绑定到关系属性。

我有一个 linq-to-sql 对象列表,每个对象都有一个一对多的关系子属性和父属性。 parent 属性简称为“parent”,它也是一个包含字符串类型名称属性的 linq-to-sql 对象。问题是我想将 DataTextField 绑定到 parent.name 属性。

下面的代码来自我的代码隐藏文件,该文件在 DropDownList 是我的下拉列表并且 Table.GetAll() 返回 linq-to-sql 对象列表时不起作用:

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        Bind_Drop_Down();
    }
}
protected void Bind_Drop_Down()
{
    List<linq-to-sql-class-name> objects = Table.GetAll();
    if (objects != null)
    {
        DropDownList.DataSource = objects;
        DropDownList.DataTextField = "parent.name";
        DropDownList.DataValueField = "id";
        DropDownList.DataBind();
    }
}

我认为这可以通过将原始查询放到我的数据库中,就在这段代码的正上方并使其创建一个带有新参数的新对象来解决,但我不希望这样。我想将原始查询保留在我的 Table 类中,它应该只返回正确的 linq-to-sql 对象。

执行上述代码时,我收到以下错误消息,其中 linq-to-sql-class-name 是实际名称的占位符:

DataBinding: 'linq-to-sql-class-name' does not contain a property with the name 'parent.name'

我的问题是:这可以做到吗?

编辑:

我添加了一些代码来验证该属性是否确实存在,我尝试打印列表中每个对象的 parent.name 属性,它实际上按预期打印了它。

protected void Bind_Drop_Down()
{
    List<linq-to-sql-class-name> objects = Table.GetAll();
    if (objects != null)
    {
        foreach(linq-to-sql-class-name oneObject in objects)
        {
            System.Diagnostics.Debug.WriteLine(oneObject.parent.name);
        }
        DropDownList.DataSource = objects;
        DropDownList.DataTextField = "parent.name";
        DropDownList.DataValueField = "id";
        DropDownList.DataBind();
    }
}

它在调试控制台中打印了这个:

name1 lastname1
name2 lastname2
...etc
...etc

【问题讨论】:

    标签: c# asp.net linq drop-down-menu webforms


    【解决方案1】:

    当然,我在发布此问题后立即找到了合适的解决方案:https://stackoverflow.com/a/5721761/3266294

    【讨论】:

      猜你喜欢
      • 2023-03-26
      • 2011-01-11
      • 1970-01-01
      • 2012-10-23
      • 2015-10-12
      • 1970-01-01
      • 1970-01-01
      • 2020-06-18
      • 1970-01-01
      相关资源
      最近更新 更多