所以我正在使用Linq-to-sql与我的sql服务器通信,我想用数据库中的数据填充asp.net下拉列表。问题是我希望用户可见的文本值绑定到关系属性。
我有一个linq-to-sql对象的列表,每个对象都有一对多关系的子代和父代属性。parentproperty简称为“ parent”,它也是一个linq-to-sql对象,其中包含string类型的name属性。问题是我想将DataTextField绑定到parent.name属性。
下面的代码来自我的代码隐藏文件,当DropDownList是我的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
当然,发布此问题后,我立即找到了合适的解决方案:https : //stackoverflow.com/a/5721761/3266294
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句