1

Currently I have a drop downlist as follows:

<asp:DropDownList  ID="DropDownList1" runat="server"  AutoPostBack="True" 

    OnSelectedIndexChanged="SelectionHasChanged"
                DataSourceID="SqlDataSource1" DataTextField="Name" DataValueField="ID" 
                 Width="214px">
            /asp:DropDownList>

            asp:SqlDataSource ID="SqlDataSource1" runat="server" 
                ConnectionString="<%$ ConnectionStrings:MyDBConnectionString1 %>" 
                SelectCommand="SELECT [ID], Name], [Name] FROM [Names]">
            /asp:SqlDataSource>

There are two things I'm trying to get the list to do when selection is either updated or deleted: 1)Remove deleted contents from DropDownList 2)The first entry in the database is found in the field when the page is loaded, I would like it to either be blank or say "Select"

Currently I need to refress the page to refresh the dropdownlist of deleted items.

I have tried adding DropDownList1.DataBind(); in various methods (page_load, update, delete) and DropDownList1.DataSource = SqlDataSource1; (but I get a message to delete an object of (SqlDataSource1?)

I have added a tag/controll called EnableViewState="false", this refreshs the dropdownlist when I select another item, but when I delete an item I need the list to refresh right away.

Waqas
  • 6,812
  • 2
  • 33
  • 50
Nick
  • 13
  • 3

1 Answers1

1

1.In order to delete an item from your dropdown list, what you do is to loop through the ListItem of dropdown list compare the value field (DataValueField) of ListItem item with the selection that has changed or deleted, remove it from dropdown list if it matches. e.g.:

private void removeItem(string ID)
    {
        for (int i = 0; i < dropdownList.Items.Count; i++)
            if (dropdownList.Items[i].Value == ID)
            {
                dropdownList.Items.RemoveAt(i);
                break;
            }
    }

2.Just after binding your dropdownlist, in code behind, add a new ListItem at Index 0, it will solve your problem of displaying "Select" or Blank as a top most selection:

dropdownList.DataBind();
dropdownList.Items.Insert(0, new ListItem("Select"));
Waqas
  • 6,812
  • 2
  • 33
  • 50
  • Thanks for the help, I really appreciated it. Just to make sure I'm doing this correct I add the private void removeItem into my code behind file, and the dropdownlist.bind and . items.insert into my update and delete methods? Also, my ID is an int in the database how would I convert the string. When adding covert.int32(ID) it doesn't appear to work for me. – Nick Aug 18 '11 at 02:48
  • you don't need to call dropdownlist.Bind when you are deleting an item from dropdownlist.. and in order to converting an integer to string you could use .toString() method – Waqas Aug 18 '11 at 02:59