I am new to programming and have a problem . I have two buttons on an aspx page.
Both the buttons have runat="server" property and are inside <form runat="server" > tag
aspx code
<form id="form1" runat="server">
<asp:Button ID="btnGetData" runat="server" onclick="btnGetData_Click" />
<asp:Button ID="btnShow" Text="Send" runat="server" onclick="btnShow_Click" />
</form>
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 as HTTP is statless. I read about Viewstate but it is not recommended when large amount of data is involved as results in significant processing delay.
Alternate is to use Session. Is there any use of IsPostBack page property here ?
Please guide how to implement Session to pass selected checkboxes from one button (GetData) click to other ie Show button.
What you’ve run into is a fairly common problem, so might I recommend you use a repeater. Example:
And in code:
Please note this is proof of concept, and hasn’t been tested to be functioning. The basics here is that during a postback, all of your controls are reset based on the aspx page and any logic you’ve written for that post. You should never dynamically add controls in the postback, and should only really do so using a placeholder in order to minimize risk of your ViewState becoming corrupt/invalid.