Search code examples
asp.netlinq-to-sqlasp.net-dynamic-data

Dynamic Data asp.net Foreign key relationship in DropdownList, how to customise?


I'm working on Asp.Net Dynamic Data project with linq to sql.

I've created a database that has one to one relationship between two tables specified using a foreign key.

i.e. I have a table Employee and table Department

Employee table
empid empname address departmentId 

Department table
departmentId departmentname

now Student table takes an departmentId as a foreign key

when I navigated to /Insert.aspx that it would display the a list of department_name in a dropdown list.

It does this - but it shows all the department_name into dropdownlist

How and where I could write linq query so that i can customize those department_name values

If suppose I want to only populate computers as a department_name in that dropdownlist how could I achieve this ?

Code: In FieldTemplate folder ForeignKey_Edit.ascx.cs

protected void Page_Load(object sender, EventArgs e)
    {
        if (DropDownList1.Items.Count == 0)
        {
            if (Mode == DataBoundControlMode.Insert || !Column.IsRequired)
            {
                DropDownList1.Items.Add(new ListItem("[Not Set]", ""));
            }
            PopulateListControl(DropDownList1);
        }

        SetUpValidator(RequiredFieldValidator1);
        SetUpValidator(DynamicValidator1);
    }

data dynamics is populating dropdownlist internally.

here before or after this statement PopulateListControl(DropDownList1);

what should I code so that i can populate only specific value..?


Solution

  • Instead of PopulateListControl(DropDownList1); try something like this

            if (ForeignKeyColumn.ParentTable.Name == "Departments")
            {
                List<Department> departments = // code to grab the correct Departments
    
                foreach (Department d in departments)
                {
                    DropDownList1.Items.Add(new ListItem(d.Name, d.Id.ToString()));
                }
            }