Mehrdad
Mehrdad

Reputation: 184

Keeping selected item from dropdown box after page refresh in asp web form

I have a aspx page that has several drop down list. So when the users forget to input some values i have to show an error to user, but every DDL are initialized again, and the users information are lost, how can I avoid this ?

When the users forget to input values i return them to current url

url1=www.spadsystem.com
Response.Redirect(Url1);

I heard that we can avoid this problem by using something like absolute i am not sure.

Upvotes: 1

Views: 3551

Answers (4)

Alexander Bell
Alexander Bell

Reputation: 7918

Use SessionState object to store the SelectedIndex property of ComboBox (e.g. Cmb), then apply it in Page_Load() event.

Example 1: Store value in Session

int _idx = Cmb.SelectedIndex;
Session["idx"] = _idx.ToString();

Example 2: Read from Session and apply to ComboBox:

if(!IsPostBack) {
     Cmb.SelectedIndex = (int)(Session["idx"]);
}

More details at: http://msdn.microsoft.com/en-us/library/vstudio/ms178581%28v=vs.100%29.aspx

Rgds,

Upvotes: 1

wazz
wazz

Reputation: 5078

agree with use RequiredFieldValidator. and, controls should hold their values if view state is on for the control (check properties).

Upvotes: 0

Anup Sharma
Anup Sharma

Reputation: 2083

First of all do not redirect the user when its not required.

Secondly use RequiredFieldValidator for your Fields. It will prevent the postback when your users forget to input any value.

And thirdly, if you are Binding dropdownlists programetically, do that in

If(!IsPostBack)
{
   //Your ddl initialization here
}

This will ensure you get the selected values from DropDownLists

Upvotes: 0

Reg Edit
Reg Edit

Reputation: 6924

Avoid redirecting to another page and back to show the error, and ensure you initialize the lists if IsPostBack is false. Then, the ASP.NET Viewstate will take care of it all for you and keep all the selected values.

Upvotes: 0

Related Questions