Reputation: 6057
I have a RadioButtonList which is dynamically created.
I have enabled AutoPostBack as I want to create some more controls dynamically when the selected value changes.
When I try and retrieve the selected value in the Page_Load it seems to return the previously selected value not the currently selected value.
protected void Page_Load(object sender, EventArgs e)
{
draw_site_select();
if (!IsPostBack)
{
Response.Write(((RadioButtonList)Panel1.FindControl("rbl_site")).SelectedValue);
}
}
void draw_site_select()
{
using (Circles_DatabaseDataContext db = new Circles_DatabaseDataContext())
{
var sites = from r in db.circle_sites select r;
RadioButtonList rbl = new RadioButtonList();
rbl.ID = "rbl_site";
rbl.DataSource = sites;
rbl.DataValueField = "circle_site_id";
rbl.DataTextField = "circle_site_name";
rbl.DataBind();
rbl.RepeatDirection = RepeatDirection.Horizontal;
rbl.AutoPostBack = true;
Panel1.Controls.Add(rbl);
}
}
As a workaround I added an event handler to the RadioButtonList
void rb_CheckedChanged(object sender, EventArgs e)
{
Response.Write(((RadioButtonList)sender).SelectedValue);
}
This works BUT I then have to handle retreiving of the value when another object causes the postback.
I have come up with the following code;
protected void Page_Load(object sender, EventArgs e)
{
draw_site_select();
if (!IsPostBack && !Request.Params["__EVENTTARGET"].ToString().Contains("rbl_site"))
{
Response.Write(((RadioButtonList)Panel1.FindControl("rbl_site")).SelectedValue);
}
}
But it all feels like a bit of a workaround. Could someone explain what's happening here and how I probably SHOULD be tackling the problem?
Upvotes: 1
Views: 205
Reputation: 2042
Each time a request goes to the server, the page life cycle events run. One of the steps is to read view state data and reinitialize controls with view state data. Since http is stateless, that's the way asp.net keeps state. Since you create your controls dynamically, their values are not added to the view state so next time you make a request, the values you set for the dynamically created controls are lost. You should create your dynamic controls in Page's Init event, in order for them to be caught by view state.
Upvotes: 1
Reputation: 77934
That's cause in your page_load
event you are not considering postback, whereas your radiobuttonlist value change present in postback. Remove the if (!IsPostBack)
condition check in page_load
event and see
protected void Page_Load(object sender, EventArgs e)
{
Response.Write(((RadioButtonList)Panel1.FindControl("rbl_site")).SelectedValue);
}
Upvotes: 0