So I am using Linq-to-sql to communicate with my sql server and i want to populate a asp.net dropdown list with data from my database. The problem is I want the text value that is visible to the user to bind to a relation-property.
I have a list of linq-to-sql objects and each of those objects has a one-to-many relation child and parent property. The parentproperty is simply called "parent" which is also a linq-to-sql object that contains a name property of type string. The problem is I want to bind DataTextField to the parent.name property.
The code below is from my code-behind file which does not work at the moment where DropDownList is my dropdownlist and Table.GetAll() returns a list of linq-to-sql objects:
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();
}
}
I think this can be solved by putting the raw query to my database right above this code and make it so that it creates a new object with new parameters but I do not want this. I want to keep the raw queries in my Table class which should only return proper linq-to-sql objects.
I get the following error message when executing the above code where linq-to-sql-class-name is a placeholder for the actual name:
DataBinding: 'linq-to-sql-class-name' does not contain a property with the name 'parent.name'
My question is: can this be done?
EDIT:
I added some code to verify the property actually exists, I tried printing the parent.name property of each object in the list and it actually printed it as expected.
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();
}
}
It printed this in the debug console:
name1 lastname1
name2 lastname2
...etc
...etc