Last post Jan 12, 2015 01:10 PM by Bulldog248
Jan 12, 2015 11:38 AM|Bulldog248|LINK
I'm using Video Web Developer 2010 Express, VB. I'm having an issue with setting dropdownlist selecteditem text. I have multiple dropdown lists and dropdownlist1 is filled from a list based upon electrical component characteristics; different lists for
capacitors, resistors, etc.
In the code below, after dropdownlist1 has had items added to the list I "copy" the list to the remaining dropdownlists. No problem to this point.
For Each li As ListItem In DropDownList1.Items
Next, I'm trying to go through associated textboxes and if text in the textbox matches an item on the dropdownlist, set the selecteditem text in the individual dropdownlist to match.
For Each li1 As ListItem In DropDownList1.Items
If TextBox1.Text = li1.Text Then DropDownList1.SelectedItem.Text = TextBox1.Text
Next...2 through 10
For Each li10 As ListItem In DropDownList10.Items
If TextBox10.Text = li10.Text Then DropDownList10.SelectedItem.Text = TextBox10.Text
The problem is that the above sets all dropdownlists to the same text as is in textbox10. This has me totally confused as to why. I want dropdownlist1 selecteditem text to match textbox1 (if textbox1 matches
anything in dropdownlist1) and so on and so forth for all 10 textbox/dropdownlist pairs. Does anybody have any ideas what I'm missing?
Jan 12, 2015 12:09 PM|AidyF|LINK
This is down to the behavior of reference variables. You're adding the listitems from one collection to another, so both collections are referencing the same ListItem object, so when you change one, as there is only one copy of that object that is referenced
by multiple lists, it is changed in all lists. Rather than adding the ListItem itself, add a new instance that has the same data. In c# this would be
foreach(ListItem li in DropDownList1.Items)
DropDownList2.Items.Add(new ListItem(li.Text, li.Value));
// do rest of copies here
Jan 12, 2015 01:10 PM|Bulldog248|LINK
Thanks for both the solution and the explanation! It works like a charm now.