Search code examples
asp.netdrop-down-menurepeaterselectedindexchanged

ASP.net list of dropdownlists - similar to Access continuous form


What I'm looking for is a way to mimic the MS-Access style continuous form within asp.net. In one particular case, I want a control, bound to a datasource which returns a dropdownlist for each row, bound to the value within the datasource. Any change to any of the dropdownlists' would perform an update to the database instantly.

I have got halfway to achieving this using a repeater control, with the DropDownList.SelectedValue assigned within the Repeater.ItemDataBound event.

But now, supposing I add an OnSelectedIndexChanged event to the DropDownList - how would I then query the repeater to know which row I was on (to get the primary key value, for example)

I'm not sure this can be done easily.. so the question is what should I really be doing? I don't want to use a GridView that requires me to select a row to edit.. I just want to have the dropdownlists autopostback for any updates.

Hope that's clear?!

Cheers! :D


Solution

  • For examples sake, lets say we are binding to a custom class called Record

    public class Record
    {
        public int Id;
        public string Value;
    }
    

    If you put custom logic on the Repeater.OnItemCreated event you can attach the primary key to the id of the drop down list

    protected void Repeater_ItemCreated(object sender, RepeaterItemEventArgs e)
    {
        if (!(e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem))
            return;
    
        var dataItem = e.Item.DataItem as Record;
        if (dataItem == null) return;
    
        var dropdown = e.Item.FindControl("myDropDown") as DropDownList;
        if (dropdown == null) return;
    
        dropdown.ID = dropdown.ID + dataItem.Id;
    }
    

    Then on the SelectedIndexChange, you can pull the id off of the dropdown that fired the event.

    protected void SelectedIndexChanged(object sender, EventArgs e)
    {
        var dropdown = sender as DropDownList;
        if (dropdown == null) return;
    
        var stringId = dropdown.ID.Replace("myDropDown", "");
        int id;
        if (Int32.TryParse(stringId, out id))
        {
            updateRecord(id, dropdown.SelectedValue);
        }
    }
    

    It's very much an ugly hack, but it should allow you to do what you want.