简体   繁体   中英

Cannot append the list in dropdown selectedindexchange to later use in buttonclick event

I am building a webform in c#. I want to generate a list where i append every field(string variable) value into the list within a foreach loop in dropdownevent. But, I want to use the list later it in buttonclick event. Foreach loop is correctly configured and Field has correct value assigned because I get all the field values when i print label.Text=field .

However, when i try to append my List and use the list in buttonclick event, it is not working. I get an error 'Index was out of range. Must be non-negative and less than the size of the collection.

public List Paramlist = new List();

On button click event: testlabel.Text = Paramlist[0]

On dropdown selectedindexchange: (Within a foreach loop) Paramlist.Add(field)
label.Text = field (This works and prints field to label)

The value of a variable does not persist between different postbacks, and each event (dropdown changed and button clicked) is a separate postback. If you want to keep track of the values in the list as they change across different postbacks, it would be best to store the list somewhere like a file or database when you're done adding to it in the dropdown event. Then in the button click, you can pull that data back out from wherever it's stored and use it.

If it were a single value, I would suggest writing it to a hidden field on the page, which would then maintain its value on the next postback, but for a list that's probably not the ideal approach.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM