|
Subject:
|
listitem
|
|
Posted By:
|
alyeng2000
|
Post Date:
|
12/31/2003 4:33:58 PM
|
i do the to scenarios but one only work all i do is i populate the dropdownlist control with some rows retrieved from a Database table(only two fields returned),BUT the problem seam to be with ListItem Class but why?
the follows are the two scenarios
scenario1: dim listItem1 as new listitem while datareader1.read listItem1.value=datareader1("ID") listItem1.Text=datareader1("Name") DropDownList.items.add(listItem1) loop
scenario2: while datareader1.read dim listItem1 as new listitem listItem1.value=datareader1("ID") listItem1.Text=datareader1("Name") DropDownList.items.add(listItem1) loop
but only scenario2 is the working one, do any one have an explaination
Ahmed Ali Software Developer
|
|
Reply By:
|
planoie
|
Reply Date:
|
1/1/2004 8:52:30 AM
|
When you have a declared object like your "listitem1" and you add this to another control, whether you add it to the other control's "controls" collection or an "items" collection the reference to the declared object doesn't go away. It doesn't "add and forget" the original object. If you take that same object and ".Add(...)" it to a different control, it leaves the first. If the first happens to be the same as the second, like in your scenario, it's still there, but it's not duplicated. I think this is due to the way the objects store references to other objects. You need to create a new instance of the control each time you need a new one.
One better way to do what you are doing is: dim listItem1 as listitem while datareader1.read listItem1 = new listitem listItem1.value=datareader1("ID") listItem1.Text=datareader1("Name") DropDownList.items.add(listItem1) loop
Alternatively you could do this: dim listItem1 as listitem while datareader1.read listItem1 = new listitem(datareader1("Name"), datareader1("ID")) DropDownList.items.add(listItem1) loop
Or: while datareader1.read DropDownList.items.add(new listitem(datareader1("Name"), datareader1("ID"))) loop
My recommendation is to drop the whole loop altogether and utilize the databinding capabilities of the control: DropDownList.DataSource = datareader1 DropDownList.DataTextField = "Name" DropDownList.DataValueField = "ID" DropDownList.DataBind()
Peter ------------------------------------------------------ Work smarter, not harder.
|
|
Reply By:
|
alyeng2000
|
Reply Date:
|
1/3/2004 9:13:14 AM
|
txs Peter the last Databinding Sol. is the best
Ahmed Ali Software Developer
|