所以我使用Linq-to-sql与我的sql server进行通信,我想用我的数据库中的数据填充asp.net下拉列表。问题是我希望用户可见的文本值绑定到关系属性。
我有一个linq-to-sql对象列表,每个对象都有一对多关系的child和parent属性。 parentproperty简称为#34; parent"它也是一个linq-to-sql对象,包含string类型的name属性。问题是我想将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