Ishan
Ishan

Reputation: 4028

Dropdownlist in ASP.net C#

I have two dropdownlist's.DropDownList2(not bound to a datasource) and DropDownList3(bound to a datasource)

On change on input in one dropdownlist some content in the other Dropdownlist should change. For that i had used the logic as.

Autopostback is enabled for both this controls.

   protected void DropDownList2_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (DropDownList2.SelectedItem.Text == "Stamp")
        {
            DropDownList3.Items.Remove(DropDownList3.Items.FindByText("STA"));
            DropDownList3.Items.Remove(DropDownList3.Items.FindByText("STM"));
        }


<asp:DropDownList ID="DropDownList3" runat="server" 
            DataSourceID="SqlDataSource1" DataTextField="skey" DataValueField="casecode" 
            AppendDataBoundItems="True" AutoPostBack="True">
            <asp:ListItem Selected="True" Value="S">Select</asp:ListItem>
        </asp:DropDownList>

Now the problem is when i select DropDownList2.SelectedItem.Text == "Reg" STA and STM are not present. I want STA and STM values back in the dropdownlist on selection of 'Reg'.

When i first load my page and select 'Reg' all the values in DropDownList3(including 'STA' and 'STM') are present and than when i select 'Stamp' the values 'STA' and 'STM' are lost(as shown in the code). Now again when i select 'Reg' this values are not there, i want this values to be present again.

What do i have to do?? Do i have to bind it again to database?

Is there any other logic for it to be used in a different way ?If anyone can help me

Upvotes: 0

Views: 1138

Answers (2)

sh_kamalh
sh_kamalh

Reputation: 3901

You can to bind DropDownList3 everytime DropDownList2 selected index change then only if the value is "Stamp" you remove the values "STA" and "STM" from DropDownList3

protected void DropDownList2_SelectedIndexChanged(object sender, EventArgs e)    
{   
   // Fill DropDownList3 data source and bind it again to restore all the items
   FillDataSource(); // This method gets all the data from DropDownList3
   DropDownList3.DataBind();

   if (DropDownList2.SelectedItem.Text == "Stamp")
   {
        DropDownList3.Items.Remove(DropDownList3.Items.FindByText("STA"));
        DropDownList3.Items.Remove(DropDownList3.Items.FindByText("STM"));        
   }
   ...

Upvotes: 1

Prescott
Prescott

Reputation: 7412

If you know the values of the dropdown items, you can add them in the else clause, if you don't know the value/text combination you'll have to rebind.

Upvotes: 0

Related Questions