Search code examples
c#asp.netdrop-down-menuselectedvalue

Dropdown SelectedValue changes unrelated properties


 drpDwnLstBillContact.SelectedValue = billContactId.ToString();
 drpDwnLstRegContact.SelectedValue = regContactId.ToString();
 drpDwnLstTechContact.SelectedValue = techContactId.ToString();

I am trying to set dropdowns' selectedvalue property, but I have a problem.

The values of variables are:

billContactId=786867;
regContactId=3487347;
techContactId=37463;

The problem is on the first line. billContactId is assigned to selectedvalue property of drpDwnLstBillContact, also on the second line regContactId is assigned to drpDwnLstRegContact's selectedvalue property. But when it is assigned to it the first dropdown's (drpDwnLstBillContact), selected value is also set to regContactId too. Why that second line of code effects the first line?


Solution

  • I found the problem and the solution.

    In the FillDropDowns method I have created only one ListItem and added it to each dropdown, so when I change the dropdowns selectedvalue property it changes the list item and all of dropdowns' listitem change too. Now I have created seperate ListItem objects for each dropdown and problem is solved.

    Old Code

     foreach (string[] contactData in data)
            {
                ListItem li = new ListItem(contactData[0], contactData[1]);
    
                drpDwnLstRegContact.Items.Add(li);
                drpDwnLstTechContact.Items.Add(li);
                drpDwnLstBillContact.Items.Add(li);
            }
    

    New Code

     foreach (string[] contactData in data)
            {
                ListItem li = new ListItem(contactData[0], contactData[1]);
                ListItem li1 = new ListItem(contactData[0], contactData[1]);
                ListItem li2 = new ListItem(contactData[0], contactData[1]);
                drpDwnLstRegContact.Items.Add(li);
                drpDwnLstTechContact.Items.Add(li1);
                drpDwnLstBillContact.Items.Add(li2);
            }