KoffeeKoder


  • FillService to Populate ListControls
    published on 6/4/2008 8:47:30 PM
  • The following code can be used to fill DropDownLists, ListBoxes or anything that inherits from the ListControl.

    public static void FillService<T>(T control, IEnumerable dataSource, string dataTextField,
    string dataValueField) where T : ListControl

    {
    FillService<T>(control, dataSource, dataTextField, dataValueField, String.Empty);
    }

    public static void FillService<T>(T control, IEnumerable dataSource, string dataTextField,
    string dataValueField,string defaultText) where T : ListControl
    {
    control.DataSource = dataSource;
    control.DataTextField = dataTextField;
    control.DataValueField = dataValueField;

    if (!String.IsNullOrEmpty(defaultText))
    {
    control.Items.Insert(0, new ListItem(defaultText, "0"));
    }

    control.DataBind();
    }

    And here is the usage:

    IVRRepository repository = new VRRepository();
    SiteHelper.FillService<DropDownList>(ddlCourses, repository.GetCoursesByDepartmentId(
    Int32.Parse(ddlDepartments.SelectedValue)), "Name", "CourseID","Select a course");

    IVRRepository repository = new VRRepository();
    SiteHelper.FillService<ListBox>(lbSections, repository.GetSectionsByCourseId(
    ddlCourses.SelectedValue.ToInt()), "SectionNo", "SectionID","Select a section");