Creating, Using and Discarding Temporary Value not working
I am trying to assign a ViewState value in my application with a SelectedIndexChanged function. Once it's assigned the postback will use the value to change some data and then set the value to zero but I can't seem to get it to work correctly. The controls are all created dynamically on Page_Load.
Page Load
protected void Page_Load(object sender, EventArgs e)
{
CreateAttributeControls();
TempProductVariantId = 0;
}
Create Attribute Controls
public void CreateAttributeControls()
{
...
var ddlArtistArtworks = new DropDownList();
ddlArtistArtworks.ID = "ddlArtistArtworksTest";
divAttribute.Controls.Add(ddlArtistArtworks);
ddlArtistArtworks.Items.Clear();
ddlArtistArtworks.SelectedIndexChang开发者_StackOverflow中文版ed += new EventHandler(ArtistArtwork_SelectedIndexChange);
ddlArtistArtworks.AutoPostBack = true;
...
}
ArtistArtwork_SelectedIndexChange
protected void ArtistArtwork_SelectedIndexChange(object sender, EventArgs e)
{
DropDownList ddl = sender as DropDownList;
TempProductVariantId = int.Parse(ddl.SelectedValue);
}
TempProductVariantId ViewState Save
public int TempProductVariantId
{
get
{
if (ViewState["TempProductVariantId"] == null)
return 0;
else
return (int)ViewState["TempProductVariantId"];
}
set
{
ViewState["TempProductVariantId"] = value;
}
}
When I load the page everything is fine. I change the DropDownList's value, It posts back, and the value is not set. Change it again the value is set and continues to change as I change the value of the DropDownList
.
Any guidance on this would be greatly appreciated.
Note: I have tried changing when CreateAttributeControls()
is called. In OnPreRender
for example. I was given this to understand the lifecycle of the page Life Cycle
That's because you are essentially recreating the dropdown on every postback..
try this
public void CreateAttributeControls()
{
...
DropDownList ddlArtistArtworks;
if (!IsPostBack)
{
ddlArtistArtworks = new DropDownList();
ddlArtistArtworks.ID = "ddlArtistArtworksTest";
divAttribute.Controls.Add(ddlArtistArtworks);
ddlArtistArtworks.Items.Clear();
ddlArtistArtworks.AutoPostBack = true;
}
else
{
ddlArtistArtworks = (DropDownLise)divAttribute.FindControl("ddlArtistArtworksTest");
}
ddlArtistArtworks.SelectedIndexChanged += new EventHandler(ArtistArtwork_SelectedIndexChange);
...
}
For dynamically added controls, the event handler has to be linked up everytime so that has to be done outside the if-block, unconditionally.
精彩评论