ASP.net-Listbox not retaining selected values between postbacks
I have a Listbox getting populated when the page loads itself and also in postbacks. Some items are already selected in that listbox even when the page loads or postbacks. I have to select one or more items in that textbox in addition to the selected one.
Till this point, it works perfectly, but the problem is that when i click an "update" button to save the newly added items, then also the page postbacks and so the list box get populated again. This will loose the newly selected items and none of the newly selected items will be saved.
So what should i do in order not to loose the newly selected items when i click the "update" button.
Note:- I need to populate the listbox on postbacks also. So t开发者_Python百科he population of that listbox on postbacks cannot be discarded.
Kindly help me. I am new to ASP.net.
Thanks in Advance
You shouldn't need to re-populate the list if you have your view-state enabled.
To populate you should be doing something similar to this:
if(!IsPostBack){
// populate your list from database or whatever
}
This will only populate the list if the page is not a post-back, therefore (if viewstate is enabled) your selections will remain after you click update.
If you want to disable the viewstate, it is important to populate the DropDownList during the "Init" event of the Page LifeCycle not the "Load" event:
protected void Page_Init( object sender, EventArgs e ) {
DropDownList1.DataSource = ...;
DropDownList1.DataBind();
}
More information can you find in this excellent article: Truly understanding viewstate.
I hope this helps a bit.
精彩评论