Dynamically added TextBoxes empty on button click - c#

I'm adding TextBoxes dynamically and when I click a submit button and have a postback, I can't see the values entered into the TextBoxes, all are coming up emtpy. Here's the .aspx page...\
form id="form1" runat="server">
<asp:PlaceHolder ID="phFormContent" runat="server">
</asp:PlaceHolder>
<br /><br />
<asp:Button ID="btnAddForm" runat="server" Text="Add Form" OnClick="btnAddForm_Click" />
<asp:Button ID="btnSubmitForms" runat="server" Text="Submit Forms" OnClick="btnSubmit_Click" />
</form>
...here's how I add the TextBoxes to the form on clicking btnAddForm...
protected void btnAddForm_Click(object sender, EventArgs e)
{
// Create Labels
Label lblName = new Label();
lblName.Text = "NAME:";
Label lblNumber = new Label();
lblNumber.Text = "NUMBER:";
Label lblAddress = new Label();
lblAddress.Text = "ADDRESS:";
Label lblCompany = new Label();
lblCompany.Text = "COMPANY:";
// Create Text Boxes
TextBox txtName = new TextBox();
TextBox txtNumber = new TextBox();
TextBox txtAddress = new TextBox();
TextBox txtCompany = new TextBox();
// Create submit button
Button btnSubmit = new Button();
btnSubmit.Text = "SUBMIT";
// Create panel and add controls
Panel pnlForm = new Panel();
pnlForm.Controls.Add(lblName);
pnlForm.Controls.Add(txtName);
pnlForm.Controls.Add(new LiteralControl("<br /><br />"));
pnlForm.Controls.Add(lblNumber);
pnlForm.Controls.Add(txtNumber);
pnlForm.Controls.Add(new LiteralControl("<br /><br />"));
pnlForm.Controls.Add(lblAddress);
pnlForm.Controls.Add(txtAddress);
pnlForm.Controls.Add(new LiteralControl("<br /><br />"));
pnlForm.Controls.Add(lblCompany);
pnlForm.Controls.Add(txtCompany);
pnlForm.Controls.Add(new LiteralControl("<hr />"));
pnlForm.Controls.Add(new LiteralControl("<br /><br />"));
panels.Add(pnlForm);
foreach (Control panel in panels)
{
phFormContent.Controls.Add(panel);
}
}
...and here's how I try to extract the fields for each individual panel added...
private static void GetFormFields(Control panelControl)
{
ControlCollection controls = panelControl.Controls;
foreach (Control childControl in panelControl.Controls)
{
if (childControl.GetType().ToString() == "System.Web.UI.WebControls.TextBox")
{
TextBox txt = childControl as TextBox;
fields.Add(txt);
}
else
{
GetFormFields(childControl);
}
}
}
panels and fields are static List, each panel containing four fields. I pass GetFormFields an individual panel reference...
private static List<Control> panels = new List<Control>();
private static List<TextBox> fields = new List<TextBox>();

Try dynamically adding them on the Page_Init event. Typically this will ensure they persist through PostBack. If you can't do this, you'll have to look at preserving their data manually by storing in ViewState.

Looks like the text boxes are not being included in the VIEWSTATE for the page, so are lost on postback.
There's some detail about what happens in this scenario here :
http://msdn.microsoft.com/en-us/library/kyt0fzt1(v=VS.71).aspx

Related

After click on button how to retrieve dynamically textboxes value which is created in panel

**After creating a dynamic textboxes. once fill the value into textboxes. I am unable to retrieve the entered value from code behind. Please can you please help us. **
//Aspx controler//
<asp:panel id="pnlTextBoxes" runat="server" cssclass="Paneldetails">
//C# code//
TextBox txt = new TextBox();
txt.ID = results.data[i].name.ToString();
txt.CssClass = "tooltips";
txt.MaxLength = Convert.ToInt32(results.data[i].maxLength);
pnlTextBoxes.Controls.Add(txt);
///tried code to retrieve the textboxes values///
protected void btnAdd_Click(object sender, EventArgs e)
{
foreach (Control ctrl in pnlTextBoxes.Controls)
{
if (ctrl is TextBox)
{
DSF.name = ((TextBox)ctrl).ID;
DSF.value = ((TextBox)ctrl).Text;
summ.Add(DSF);
}
}

Avoid page refresh after ImageClickEventHandler fire

I have a ImageButton which will show Calendar after it is clicked. I want to stop page refresh when the ImageButton is clicked, but I've tried a couple of ways and none of them work. Is it possible to avoid page refresh and just show the calendar after the Image Button is clicked?
Here is my c# code
TableRow first = new TableRow();
TableCell four = new TableCell();
ImageButton btnDateToggle = new ImageButton();
btnDateToggle.ID = $"btnDateToggle_{j}";
btnDateToggle.ImageUrl = "images/icon2.gif";
btnDateToggle.Click += new ImageClickEventHandler(BtnDateToggle_Click);
Calendar dateddl = new Calendar();
dateddl.ID = $"dateddl_{j}"
dateddl.Width = 250;
dateddl.Visible = false;
dateddl.SelectionChanged += new EventHandler(Dateddl_SelectionChanged);
four.Controls.Add(btnDateToggle);
four.Controls.Add(dateddl);
first.Cells.Add(four);
tasksTable.Rows.Add(first);
ChildPane.ContentContainer.Controls.Add(tasksTable);
ChildAccordion.Panes.Add(ChildPane);
ParentPane.ContentContainer.Controls.Add(ChildAccordion);
MasterAccordion.Panes.Add(ParentPane);
MyContent.Controls.Add(MasterAccordion);
ChildPane and ParentPane are AccordionPane Object. ChildAccordion is an Accordion Object
protected void BtnDateToggle_Click(object sender, EventArgs e)
{
string btnDateToggleID = ((Control)sender).ID;
string index = btnDateToggleID.Substring(btnDateToggleID.IndexOf('_') + 1);
Calendar dateddl = (Calendar)FindControlRecursive(Page, $"dateddl_{index}");
dateddl.Visible = !dateddl.Visible;
}
protected void Dateddl_SelectionChanged(object sender, EventArgs e)
{
Calendar dateddl = (Calendar)sender;
string dateddlID = dateddl.ID;
string index = dateddlID.Substring(dateddlID.IndexOf('_') + 1);
TextBox textBox = (TextBox)FindControlRecursive(Page, $"txtDate_{index}");
dateddl.Visible = false;
textBox.Text = dateddl.SelectedDate.ToShortDateString();//.ToString("MM/dd/yyyy");
}
Here is my client side code (.aspx)
<asp:Content ID="Content1" runat="server">
<div>
<asp:Panel ID="MyContent" runat="server">
<ajaxToolkit:Accordion ID="MasterAccordion" runat="server"> </ajaxToolkit:Accordion>
</asp:Panel>
</div>

Dynamic checkboxes in updatepanel staying checked

Within a site using a MasterPage, I have a page which has an UpdatePanel. Inside that, there is a ListBox which contains a list of users. There is also a dynamically generated list of checkboxes, which should have different values checked based upon which user is selected.
It works great the first time you select a user. However, when you select a second user, the original values remain - you see the checkboxes of both users checked.
.aspx
<asp:Content ID="BodyContent" ContentPlaceHolderID="MainContent" runat="server">
<h1>Access Database Security Controls</h1>
<asp:UpdatePanel ID="SecurityControls" runat="server">
<ContentTemplate>
<asp:ListBox ID="AccessUsers" runat="server" Rows="15" SelectionMode="Single" OnSelectedIndexChanged="AccessUsers_SelectedIndexChanged" AutoPostBack="true"></asp:ListBox>
<asp:PlaceHolder ID="SecurityRoles" runat="server"></asp:PlaceHolder>
</ContentTemplate>
</asp:UpdatePanel>
</asp:Content>
code behind
protected void Page_Load(object sender, EventArgs e)
{
LoadAllRoles();
}
protected void LoadAllRoles()
{
for (int i = 0; i < 4; i++)
{
Label lbl = new Label();
lbl.ID = "lbl_" + i.ToString();
lbl.Text = i.ToString() + " lbl text here";
SecurityRoles.Controls.Add(lbl);
CheckBox cb = new CheckBox();
cb.ID = "cb_" + i.ToString();
SecurityRoles.Controls.Add(cb);
SecurityRoles.Controls.Add(new LiteralControl("<br />"));
}
}
protected void AccessUsers_SelectedIndexChanged(object sender, EventArgs e)
{
Control page = Page.Master.FindControl("MainContent");
Control up = page.FindControl("SecurityControls");
Control ph = up.FindControl("SecurityRoles");
CheckBox cbRole = (CheckBox)ph.FindControl("cb_" + AccessUsers.SelectedValue);
if (cbRole != null)
cbRole.Checked = true;
}
I've tried doing cb.Checked = false; when I am creating the checkboxs, but even on the partial postbacks, the SecurityRoles placeholder control starts out empty.
How do I get the checkboxes to clear?
You can try to uncheck all other check-boxes before you check one.
foreach (Control c in ph.Controls)
{
if(c is CheckBox)
{
((CheckBox)c).Checked=false;
}
}

Call a Function on Dynamically Generated ASP:Button in ASP.NET c#

I'm trying to call a function created in code through <asp:Button>'s on click event but its not working...
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection sqlcon = new SqlConnection(ConfigurationManager.ConnectionStrings["Con"].ToString());
ArrayList myArrayList = ConvertDataSetToArrayList();
Literal objliteral = new Literal();
StringBuilder objSBuilder = new StringBuilder();
// Display each item of ArrayList
foreach (Object row in myArrayList)
{
objSBuilder.Append("<div class='AppItem'>");
objSBuilder.Append("<label class='control-label span3'>" + ((DataRow)row)["PlanName"].ToString() + "</label>");
objSBuilder.Append("<label class='control-label span3'> Plan Description :" + ((DataRow)row)["PlanDesc"].ToString() + "</label>");
objSBuilder.Append("<label class='control-label span3'> Price :" + ((DataRow)row)["PlanCost"].ToString() + "</label>");
objSBuilder.Append("<label class='control-label span3'> Total Visitors :" + ((DataRow)row)["PlanVisitors"].ToString() + "</label>");
objSBuilder.Append("<div class='control-group'><asp:Button Text='AddtoCart' runat='server' id='" + ((DataRow)row)["PlanId"].ToString() + "' class='btn btn-small btn-success' onclick='AddPlanToCart();' /></div>");
//<asp:Button ID="ImageButton1" runat="server" Text="Upload" CssClass="btn btn-small btn-success" onclick="ImageButton1_Click" />
objSBuilder.Append("</div>");
}
objliteral.Text = objSBuilder.ToString();
PlanContent.Controls.Add(objliteral);
}
private void AddPlanToCart()
{
//This does not get called.
}
Click here to see code behind!
The problem here is that you're generating the code to run on the client-side, but including scripts and tags designed to be run through the asp.net processor:
objSBuilder.Append("<div class='control-group'><asp:Button Text='AddtoCart' runat='server' id='" + ((DataRow)row)["PlanId"].ToString() + "' class='btn btn-small btn-success' onclick='AddPlanToCart();' /></div>");
which produces HTML including [slightly reformatted]:
<div class='control-group'>
<asp:Button ... onclick='AddPlanToCart();' />
</div>
instead of the <button> control that you're obviously expecting.
Fixing this to work in the manner its written in would be a significant amount of work. Instead, I'd strongly recommend rewriting it to use an <asp:repeater> control instead.
Your onclick is attempting to call a javascript function AddPlanToCart(). You have a couple of options. Here's 2:
1) Create a javascript that does a postback with a specific query string. Check for the query string in page_load, if it exists then call the function.
2) Create an actual dynamic control. It should be created in Page_init if you want to track it's viewstate, not Page_load. Then Add an event handler for the button.
Button b2 = new Button();
b2.Text = "Add To Cart";
b2.Click += new EventHandler(AddPlanToCart);
When creating the button, you can also bind the click event, to a delegate like the following:
Button btn = new Button();
btn.Text = "Button text";
btn.AutoSize = true;
btn.Location = new Point(y, 0);
btn.Click += delegate(object sender, EventArgs e)
{
solution.Invoke();
};
In this case I am passing an Action<>, as a parameter within the method. When you click on the button, the delegate would be triggered. For instance, this button would be created, and when clicked, a messagebox would show:
Button btn = new Button();
btn.Text = "Button text";
btn.AutoSize = true;
btn.Location = new Point(y, 0);
btn.Click += delegate(object sender, EventArgs e)
{
MessageBox.Show("Clicked!");
};
For your scenario, try something within these lines:
int counter = 0;
// Display each item of ArrayList
foreach (Object row in myArrayList)
{
Control ctrl = new Control();
Label lbl = new Label();
lbl.Text = "Label " + counter.ToString();
Button btn = new Button();
btn.Text = "Button text " + counter.ToString();
btn.Click += delegate(object sender, EventArgs e)
{
Response.Write("<script>alert('Message for button " + counter.ToString() + "');</script>");
};
ctrl.Controls.Add(lbl);
ctrl.Controls.Add(btn);
counter++;
PlanContent.Controls.Add(ctrl);
}

Event does not fired when i create a button programatically

I was create a button dynamically with event handler. But the event not fired. Please help me to do this. My partial code is here.
Button btn = new Button();
btn.ID = "btn" + i;
btn.Text = "Add New";
Panel1.Controls.Add(btn);
btn.Click += new EventHandler(this.GreetingBtn_Click);
Panel1.Controls.Add(new LiteralControl("<br /><br />"));
void GreetingBtn_Click(Object sender, EventArgs e)
{
create();
}
I want to access the create() function when i click the button.
Without knowing much about your code, I'm guessing you're not creating the control in the appopriate stage of the page life cycle of ASP.NET
what you need is PreInit, as described here:
Raised after the start stage is complete and before the initialization stage begins.
Use this event for the following:
Create or re-create dynamic controls.
if you are adding this dynamic button on page load, make sure its under
if (!IsPostBack)
{
//add button here
}
always make your code of creating one time control that will made should be in side !ispostback because they are not need to be created again and again
if (!IsPostBack)
{
//Your code should be their enter code here
}
List<string> myControls = new List<string>();
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
myControls = new List<string>();
ViewState["myControls"] = myControls;
}
}
protected void override void LoadViewState(object savedState)
{
base.LoadViewState(savedState);
myControls = (List<string>)ViewState["myControls"];
foreach(string controlID in myControls){
//method to create your buttons goes here.
createButtons(controlID);
}
}
public void createButtons(string btnID){
Button btn = new Button();
btn.ID = btnID;
btn.Text = "Add New";
btn.Click += new RoutedEventHandler(this.GreetingBtn_Click);
Panel1.Controls.Add(btn);
Panel1.Controls.Add(new LiteralControl("<br /><br />"));
}
void GreetingBtn_Click(Object sender, RoutedEventArgs e){
create();
}
Give this code a try. When adding controls dynamically in asp.net you have to recreate the controls in the postback. The easiest way to do this is using the viewstate as I showed above.
Common signs of not doing this correctly are: control disappears when you click it or event just doesn't fire at all. Hope this helps someone!
Move btn.Click += new EventHandler(this.GreetingBtn_Click); line one level up i.e. before adding to parent And try Routed events.
Button btn = new Button();
btn.ID = "btn" + i;
btn.Text = "Add New";
btn.Click += new RoutedEventHandler(this.GreetingBtn_Click);
Panel1.Controls.Add(btn);
Panel1.Controls.Add(new LiteralControl("<br /><br />"));
void GreetingBtn_Click(Object sender, RoutedEventArgs e)
{
create();
}

Categories