Postback not maintaining selected values
I have a page with several dynamically generated DropDownLists. The DDs load and display the correct values on page load. However, when I try to retrieve the values at post back, the DDs all seem to be maintaining the values they had at page load.
All are created in Page_Load; No test for IsPostBack; Processing is handled in code below:
void btnSubmit_Click(object sender, EventArgs e)
{
System.IO.StreamWriter sw = new System.IO.StreamWriter(Server.MapPath("\\") + "\\Logs\\Permissions.log",false);
string szMask = hMask.Value.ToString();
sw.WriteLine("\t\t\t\t\t\t\t" + szMask);
foreach (Control c in Page.Controls)
LoopControls(c, szMask, sw);
sw.Close();
}
private void LoopControls(Control Page, string szMask, System.IO.StreamWriter sw)
{
foreach (Control c in Page.Controls)
{
if (c is DropDownList)
{
string szId = c.ID;
if (szId.StartsWith("ddlPerm"))
{
string[] szSplit = szId.Split(':');
int iMaskPosition = Convert.ToInt32(szSplit[1].ToString());
int iSecurityPermissionID = Convert.ToInt32(szSplit[2].ToString());
DropDownList dd = (DropDownList)c;
string szPermission = dd.SelectedValue.ToString();
if (szMask.Substring(iMaskPosition, 1) != szPermission)
{
sw.WriteLine("NE");
if (iMaskPosition == 0)
szMask = szPermission + szMask.Substring(1);
else
szMask = szMask.Substring(0, iMaskPosition) + szPermission + szMask.Substring(iMaskPosition);
}
sw.WriteLine(szId + "\t\t" + iMaskPosition.ToString() + "\t" + iSecurityPermissionID.ToString() + "\t" + szPermission + "\t\t" + szMask);
}
}
else
{
if (c.Controls.Count > 0)
{
LoopControls(c, szMask, sw);
}
}
}
}
This is really bugging me. Any help would开发者_C百科 be greatly appreciated.
Thanks, jb
Normally, this problem can be solved by
if (!IsPostback){
// bind all your dropdownlist here
}
Otherwise the selected values will be lost after rebinding.
ViewState is maintained between the Init and Load events. By creating and populating your controls during Load, you're basically coming in after ViewState has already been handled. Create your controls during Init and you should notice your postback values sticking.
For more information regarding what happens between and at each particular stage of the life cycle, consult the information at this link: http://msdn.microsoft.com/en-us/library/ms178472.aspx
The problem may be, as you said No test for IsPostBack
. You're likely overwriting the values and state each time.
Instead, test for IsPostback and don't write them out if it's true.
All are created in Page_Load; No test for IsPostBack; Processing is handled in code
If you aren't testing for IsPostBack then on every page load the dropdowns are being recreated.
You need to test for IsPostBack and only create the dropdowns when it's not a PostBack. AKA - On the first load.
精彩评论