I am stuck with a problem which I have reduced to code below . I have two buttons on an aspx page.
Both the buttons have runat="server" property and are inside <form runat="server" > tag
btnGetData
protected void btnGetData_Click(object sender, EventArgs e)
{
headlines = masg.Split('*');
//Response.Write(headlines.Length);
cb = new CheckBox[headlines.Length];
for (int i = 0; i < headlines.Length; i++)
{
cb[i] = new CheckBox();
cb[i].Text = headlines[i];
Literal br = new Literal();
br.Text = "<br/>";
Form.Controls.Add(cb[i]);
Form.Controls.Add(br);
}
}
On clicking Get Data button , multiple checkboxes are generated with associated text .
I click on some of the checkboxes and then click on Show button which IF WORKS CORRECTLY should combine selected checboxes text into single string and display it.
btnShow
protected void btnShow_Click(object sender, EventArgs e)
{
for (int i = 0; i < headlines.Length; i++)
{
if (cb[i].Checked)
newmsg += cb[i].Text + '*';
}
Response.Write("<BR><BR><BR>" + newmsg);
}
But once I click on GetData button , the checkboxes are lost as they don’t persist . I read about SESSION variables but can’t figure out how to apply them .
I have declared below variables as global so that they can be accessed throughout the page.
CheckBox[] cb;
string[] headlines;
string masg;
Please help with code .Please provide me with inputs in code. I will refine my question if I am not able to make something clear.
You need to recreate dynamically created controls on every postback(in
Page_InitorPage_Load) due to the statelessness of HTTP. You need to know what you have to recreate. Therefore you can save the number of already createdCheckBoxesin aViewStatevariable.You only need to assign the same IDs as before and add them in
Page_Loadat the latest. If you know the number of controls to create you can derive the ID from the counter variable by appending it to the control-id.Recommandable readings:
Or you use one of the builtin Data-Bound Control like Repeater that do this automatically. You only have to set their
DataSourceand callDataBind().Here are answers of me on similar questions with implementation details: