Given multiple dynamically created textboxes, I want to get the text filled by the user.
I used a Panel and the creation works. The control for the textbox is not found.
ASPX
<div>
<asp:Panel ID="Panel1" runat="server"></asp:Panel>
</div>
<div>
<asp:Button ID="Button1" runat="server" Text="Adauga autor" OnClick="Button1_Click" />
</div>
Create Textboxes
protected void Button1_Click(object sender, EventArgs e)
{
int rowCount = Convert.ToInt32(Session["clicks"]);
rowCount++;
Session["clicks"] = rowCount;
for (int i = 1; i <= rowCount; i++)
{
TextBox TxtBoxA = new TextBox();
Label lblA = new Label();
TxtBoxA.ID = "TextBoxA" + i.ToString();
lblA.ID = "LabelA" + i.ToString();
lblA.Text = "Label" + i.ToString() + ": ";
Panel1.Controls.Add(lblA);
Panel1.Controls.Add(TxtBoxA);
Panel1.Controls.Add(new LiteralControl("<br />"));
}
}
Get Text
int rowCount = Convert.ToInt32(Session["clicks"]);
for (int i = 1; i <= rowCount; i++)
{
string item = "TextBoxA" + i.ToString();
Control foundControl = FindControl(item, Page.Controls);
TextBox TB = (TextBox)foundControl;
string txt = TB.Text;
}
+
public static Control FindControl(string controlId, ControlCollection controls)
{
foreach (Control control in controls)
{
if (control.ID == controlId)
return control;
if (control.HasControls())
{
Control nestedControl = FindControl(controlId, control.Controls);
if (nestedControl != null)
return nestedControl;
}
}
return null;
}
The Textbox Control is null. What am I doing wrong?
You have to recreate all controls in Page_Load at the latest. Button1_Click is too late. So recreate Session["clicks"] in Page_Init/Page_Load and create the single new control in the Button-Click-handler.
Some code:
protected void Page_Init(Object sender, EventArgs e)
{
RecreateControls();
}
private void RecreateControls()
{
int rowCount = Convert.ToInt32(Session["clicks"]);
CreateControls(rowCount);
}
private void AddControl()
{
int rowCount = Convert.ToInt32(Session["clicks"]);
CreateControls(1);
Session["clicks"] = rowCount++;
}
private void CreateControls(int count)
{
for (int i = 1; i <= count; i++)
{
TextBox TxtBoxA = new TextBox();
Label lblA = new Label();
TxtBoxA.ID = "TextBoxA" + i.ToString();
lblA.ID = "LabelA" + i.ToString();
lblA.Text = "Label" + i.ToString() + ": ";
Panel1.Controls.Add(lblA);
Panel1.Controls.Add(TxtBoxA);
Panel1.Controls.Add(new LiteralControl("<br />"));
}
}
protected void Button1_Click(object sender, EventArgs e)
{
AddControl();
}
Related
I have created Label controls dynamically on button click:
protected void createDynamicLabels_Click(object sender, EventArgs e)
{
int n = 5;
for (int i = 0; i < n; i++)
{
Label MyLabel = new Label();
MyLabel.ID = "lb" + i.ToString();
MyLabel.Text = "Labell: " + i.ToString();
MyLabel.Style["Clear"] = "Both";
MyLabel.Style["Float"] = "Left";
MyLabel.Style["margin-left"] = "100px";
Panel1.Controls.Add(MyLabel);
}
}
When I tried to read back fro another button I see Label Control returned null
Label str = (Label)Panel1.FindControl("lb" + i.ToString());
not sure what went wrong here
protected void bReadDynValue_Click(object sender, EventArgs e)
{
int n = 5;
for (int i = 0; i < n; i++)
{
Label str = (Label)Panel1.FindControl("lb" + i.ToString());
lbGetText.Text = str.Text;
}
}
this is the issue of every time page load event. ASP.net fire every time page load event when any button is click.
suppose in this example..
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
createDynamicLabels();
}
private void createDynamicLabels()
{
int n = 5;
for (int i = 0; i < n; i++)
{
Label MyLabel = new Label();
MyLabel.ID = "lb" + i.ToString();
MyLabel.Text = "Labell: " + i.ToString();
MyLabel.Style["Clear"] = "Both";
MyLabel.Style["Float"] = "Left";
MyLabel.Style["margin-left"] = "100px";
Panel1.Controls.Add(MyLabel);
}
}
protected void bReadDynValue_Click(object sender, EventArgs e)
{
int n = 5;
for (int i = 0; i < n; i++)
{
Label str = (Label)Panel1.FindControl("lb" + i.ToString());
lbGetText.Text = str.Text;
}
}
when Button trigger Page doesn't have any label because it is made on runtime. and Page doesn't find particular label. if you tried above code it is run properly.
protected void Page_Load(object sender, EventArgs e)
{
createDynamicLabels();
}
private void createDynamicLabels()
{
int n = 5;
for (int i = 0; i < n; i++)
{
Label MyLabel = new Label();
MyLabel.ID = "lb" + i.ToString();
MyLabel.Text = "Labell: " + i.ToString();
MyLabel.Style["Clear"] = "Both";
MyLabel.Style["Float"] = "Left";
MyLabel.Style["margin-left"] = "100px";
Panel1.Controls.Add(MyLabel);
}
}
protected void bReadDynValue_Click(object sender, EventArgs e)
{
int n = 5;
for (int i = 0; i < n; i++)
{
Label str = (Label)Panel1.FindControl("lb" + i.ToString());
lbGetText.Text = str.Text;
}
}
in this Example code find label every time because every time it can make labels for this page.
Dynamically created labels exists only until the next postback occurs. When you click on another button to retrieve their values a postback occurs and values become null.
For saving labels state after postback you have to use some hidden field.
If the text / value of the labes does not change it is enough to generate them on every postback (as mck already mentioned). If you need to retrieve changes made on the client side, you should create the controls in the OnInit event instead of the PageLoad and use inputs / texboxes instead of labels.
Another option (which I would recommend) would be to use a asp:Repeater to generate the Labels.
Here is my code to create dynamical textboxes..I want to insert those values to database
I need to insert the dynamically created textbox values to database.how can i do that..i am new to asp.net
Markup:
<div>
<asp:Panel ID="Panel1" runat="server" Width="300px" />
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
</div>
Code-behind:
protected void Page_load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
//Remove the session when first time page loads.
Session.Remove("clicks");
}
}
protected void Button1_Click(object sender, EventArgs e)
{
int rowCount = 0;
//initialize a session.
rowCount = Convert.ToInt32(Session["clicks"]);
rowCount++;
//In each button clic save the numbers into the session.
Session["clicks"] = rowCount;
//Create the textboxes and labels each time the button is clicked.
for (int i = 0; i < rowCount; i++)
{
TextBox TxtBoxU = new TextBox();
Label lblU = new Label();
TxtBoxU.ID = "TextBoxU" + i.ToString();
lblU.ID = "LabelU" + i.ToString();
lblU.Text = "Category Name " + (i + 1).ToString() + " : ";
//Add the labels and textboxes to the Panel.
Panel1.Controls.Add(lblU);
Panel1.Controls.Add(TxtBoxU);
}
}
I think you are not able to acces the value of textbox, through this you can easily access the value.
and I hompe thant u know how to insert data into data base.
for (int i = 0; i < rowCount; i++)
{
string OptionID = "TextBoxU" + i;
TextBox tb = (TextBox)Panel1.FindControl(OptionID);
/******** USe the tb.Text value to get
the value and then store it into Database**********/
}
as suggested in the title i have in which i can insert how many textboxes i want to add to a placeholder. i can add the textboxes just fine the problem is i cant get the values inserted on those dynamically added textboxes. here's my code
the purpose of this piece of code is to whenever the textbox in which i can introduce the number of textboxes i want. it creates and adds them to the placeholder in my page.
public void txtExtra_TextChanged(object sender, EventArgs e)
{
for (a = 1; a <= int.Parse(txtExtra.Text); a++)
{
TextBox txt = new TextBox();
txt.ID = "txtquestion" + a;
pholder.Controls.Add(txt);
}
}
this is the code of the button that will submit and response.write the values inserted in all those textboxes.
protected void btnConfirm_Click(object sender, EventArgs e)
{
foreach (Control ctr in pholder.Controls)
{
if (ctr is TextBox)
{
string value = ((TextBox)ctr).Text;
Response.Write(value);
}
}
}
i've been searching online and i've been getting answers that this code is fine and it should work but it doesnt. if you guys see anything wrong or have any suggestion that can solve my problem i'd really appreciate it
You are almost there.
Problem
You need to reload those dynamically created textboxes on post back. Otherwise, they will become null, and you won't be able to find it.
In order to do that, you need to save those dynamically TextBoxes Ids in persistent location such as View State or Session State.
Screen Shot
ASPX
Number of TextBoxes: <asp:TextBox runat="server" ID="CounterTextBox"
OnTextChanged="CounterTextBox_TextChanged" AutoPostBack="True" /><br/>
<asp:PlaceHolder runat="server" ID="TextBoxPlaceHolder" /><br/>
<asp:Button runat="server" ID="ConfirmButton" Text="Confirm"
OnClick="ConfirmButton_Click" /><br/>
Result: <asp:Literal runat="server" ID="ResultLiteral"/>
Code Behind
private List<string> TextBoxIdCollection
{
get
{
var collection = ViewState["TextBoxIdCollection"] as List<string>;
return collection ?? new List<string>();
}
set { ViewState["TextBoxIdCollection"] = value; }
}
protected void Page_Load(object sender, EventArgs e)
{
foreach (string textboxId in TextBoxIdCollection)
{
var textbox = new TextBox {ID = textboxId};
TextBoxPlaceHolder.Controls.Add(textbox);
}
}
protected void CounterTextBox_TextChanged(object sender, EventArgs e)
{
var collection = new List<string>();
int total;
if (Int32.TryParse(CounterTextBox.Text, out total))
{
for (int i = 1; i <= total; i++)
{
var textbox = new TextBox { ID = "QuestionTextBox" + i };
// Collect this textbox id
collection.Add(textbox.ID);
TextBoxPlaceHolder.Controls.Add(textbox);
}
TextBoxIdCollection= collection;
}
}
protected void ConfirmButton_Click(object sender, EventArgs e)
{
foreach (Control ctr in TextBoxPlaceHolder.Controls)
{
if (ctr is TextBox)
{
string value = ((TextBox)ctr).Text;
ResultLiteral.Text += value;
}
}
}
You are actually creating textboxes with property Text set to default = ""; So you need set txt.Text property for example:
public void txtExtra_TextChanged(object sender, EventArgs e)
{
for (int a = 1; a <= int.Parse(txtExtra.Text); a++)
{
TextBox txt = new TextBox();
txt.ID = "txtquestion" + a;
txt.Text = "Some text"; // Set some text here
pholder.Controls.Add(txt);
}
}
EDIT:
After that you can store your values into the list:
private static List<string> values = new List<string>();
protected void btnConfirm_Click(object sender, EventArgs e)
{
foreach (Control ctr in pholder.Controls)
{
if (ctr is TextBox)
{
string value = ((TextBox)ctr).Text;
values.Add(value); // add values here
}
}
}
EDIT:
Here is your values:
EDIT:
For super mega better understanding:
Create one more textbox txtOutput then add button GetDataFromTextBoxesAndPutItBelow and create an event for that button `Click'. Event code:
protected void btnGetData_Click(object sender, EventArgs e)
{
for (int i = 0; i < values.Count; i++)
txtOutput.Text += "Value from txtquestion1: " + values[i] + " ";
}
Screenshot looks:
for (int i = 0; i < dataTable.Rows.Count; i++)
{
int comment_id = Convert.ToInt32(dataTable.Rows[i]["comment_id"]);
string created_by_name = dataTable.Rows[i]["created_by_name"].ToString();
string created_at = dataTable.Rows[i]["created_at"].ToString();
string comment = dataTable.Rows[i]["comment"].ToString();
HtmlGenericControl divComment = new HtmlGenericControl("div"); //This is root object of comment.Other objects like textbox,button,etc added into this object.
//divComment.Attributes.Add("class", "div_post_display");
divComment.Attributes.Add("id", comment_id.ToString());
/* Comment by */
HtmlGenericControl lblCommentBy = new HtmlGenericControl("label");
//lblCommentBy.Attributes.Add("class", "divauthor");
lblCommentBy.InnerText = "" + created_by_name + " (" + created_at + ")";
/* Comment body */
HtmlGenericControl pComment = new HtmlGenericControl("p");
//lblCommentBy.Attributes.Add("class", "divauthor");
pComment.InnerText = comment;
divComment.Controls.Add(lblCommentBy);
divComment.Controls.Add(pComment);
if (Session["user_id"] != null)
{
if (Session["user_level"].ToString() == "1") //Admin can reply for comment
{
/* Reply Form */
TextBox txtReply = new TextBox(); //Create object dynamacaly
txtReply.ID = "txtReply_"+comment_id;
txtReply.Attributes.Add("class", "form-control"); //Add css class
txtReply.Width = 400;
divComment.Controls.Add(txtReply); //Add obj to root object(div)
Button btnReply = new Button(); //Create object dynamacaly
btnReply.Text = "Reply"; //Set button text
btnReply.Attributes.Add("class", "btn btn-sm btn-success"); //Add css class
btnReply.Click += btnReply_Click;
btnReply.CommandArgument = comment_id.ToString();
divComment.Controls.Add(btnReply); //Add obj to root object(div)
HtmlGenericControl br = new HtmlGenericControl("br"); //Create object dynamacaly
divComment.Controls.Add(br); //new line
}
}
pnlShowComments.Controls.Add(divComment);
}
I created some TextBox dynamically using the code below and I entered some text in this TextBox. Now I want to read this control's ID while adding the text into a database. How can I get the ID of this TextBox on the click of a Button.
for (int i = 0; i < dv_count; i++)
{
TextBox txt_box = new TextBox();
txt_box.Text = "";
txt_box.ID = "s" + i;
placeholder1.Controls.Add(txt_box);
}
protected void btn_act_proceed_Click(object sender, EventArgs e)
{
int count = placeholder1.Controls.Count; //always return 0
if (count > 0)
{
int dv_count = count / 2;
for (int i = 0; i < dv_count; i++)
{
TextBox lbl_type = (TextBox )placeholder1.FindControl("s" + i);
}
}
}
Try this
In your Aspx Page
<div runat="server" id="plcholder">
</div>
<asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" />
now in code behind
protected void Page_Load(object sender, EventArgs e)
{
populate();
}
public void populate()
{
for (int i = 0; i < 3; i++)
{
TextBox tb = new TextBox();
tb.ID = "s" + i;
tb.Text = "Hello" + i;
plcholder.Controls.Add(tb);
}
}
protected void Button1_Click(object sender, EventArgs e)
{
int cont = plcholder.Controls.Count;
for (int i = 0; i < cont-1; i++)
{
TextBox tx = (TextBox)plcholder.FindControl("s" + i);
Response.Write(tx.Text);
}
}
Control will be lost during postback. So on preinit you need to create the controls again.
Or you can keep your controls in session and get it back from postback.
A good link http://www.codeproject.com/Articles/3684/Retaining-State-for-Dynamically-Created-Controls-i
http://www.codeproject.com/Articles/502251/How-to-create-controls-dynamically-in-ASP-NET-and
I don't see you adding controls to the placeholder in first place. try this
for (int i = 0; i < dv_count; i++)
{
TextBox txt_box = new TextBox();
txt_box.Text = "";
txt_box.ID = "s" + i;
placeholder1.Controls.Add(txt_box);
}
TextBox lbl_type = (TextBox)placeholder1.FindControl("s" + i);
guys i am creating dynamic TextBoxes everytime a button is clicked. but once i have as many text boxes as i want.. i want to save these value Database Table.. Please guide how to save it into DB
public void addmoreCustom_Click(object sender, EventArgs e)
{
if (ViewState["addmoreEdu"] != null)
{
myCount = (int)ViewState["addmoreEdu"];
}
myCount++;
ViewState["addmoreEdu"] = myCount;
//dynamicTextBoxes = new TextBox[myCount];
for (int i = 0; i < myCount; i++)
{
TextBox txtboxcustom = new TextBox();
Literal newlit = new Literal();
newlit.Text = "<br /><br />";
txtboxcustom.ID = "txtBoxcustom" + i.ToString();
myPlaceHolder.Controls.Add(txtboxcustom);
myPlaceHolder.Controls.Add(newlit);
dynamicTextBoxes = new TextBox[i];
}
}
You have to recreate the dynamical controls in Page_Load at the latest, otherwise the ViewState is not loaded correctly. You can however add a new dynamical control in an event handler(which happens after page_load in the page's lifefycle).
So addmoreCustom_Click is too late for the recreation of all already created controls, but it's not tool late to add a new control or to read the Text.
So something like this should work(untested):
public void Page_Load(object sender, EventArgs e)
{
if (ViewState["addmoreEdu"] != null)
{
myCount = (int)ViewState["addmoreEdu"];
}
addControls(myCount);
}
public void addmoreCustom_Click(object sender, EventArgs e)
{
if (ViewState["addmoreEdu"] != null)
{
myCount = (int)ViewState["addmoreEdu"];
}
myCount++;
ViewState["addmoreEdu"] = myCount;
addControls(1);
}
private void addControls(int count)
{
int txtCount = myPlaceHolder.Controls.OfType<TextBox>().Count();
for (int i = 0; i < count; i++)
{
TextBox txtboxcustom = new TextBox();
Literal newlit = new Literal();
newlit.Text = "<br /><br />";
txtboxcustom.ID = "txtBoxcustom" + txtCount.ToString();
myPlaceHolder.Controls.Add(txtboxcustom);
myPlaceHolder.Controls.Add(newlit);
}
}
Just enumerate the PlaceHolder-Controls to find your TextBoxes or use Linq:
private void saveData()
{
foreach (TextBox txt in myPlaceHolder.Controls.OfType<TextBox>())
{
string text = txt.Text;
// ...
}
}
Quick and dirty way would be to just iterate the Form collection looking for proper values:
if (Page.IsPostBack)
{
string name = "txtBoxcustom";
foreach (string key in Request.Form.Keys)
{
int index = key.IndexOf(name);
if (index >= 0)
{
int num = Int32.Parse(key.Substring(index + name.Length));
string value = Request.Form[key];
//store value of txtBoxcustom with that number to database...
}
}
}
To get values of dynamically created controls on postback you need to recreate those controls on Page_Init event
Then view state of those controls will be loaded and you will get controls and there values.
public void Page_Init(object sender, EventArgs e)
{
addControls(myCount);
}
I hope this will resolve your problem
Happy coding