How do I fetch textbox value from dynamically created textbox

U

utterberg

Can anyone help me with this problem?
I dynamically creates several textboxes using a placeholder. This works
fine. But is there a way for me to loop through theese textboxes and
retrive its value when clicking a button?

The code I'm working with:

aspx-page
<form id="Form1" method="post" runat="server">
<asp:placeHolder ID="EDCTextBoxes" Runat="server" />
<asp:button ID="btnSave" Runat="server" />
</form>

code behind
private void DCP_Init(object sender, EventArgs e) {
CreateTextBoxes();
}
private void CreateTextBoxes(){
this.EDCTextBoxes.Controls.Add(new TextBox());
IterateThroughChildren(this);
}

private void IterateThroughChildren(Control parent){

foreach (Control c in parent.Controls){
if(c.GetType().ToString().Equals("System.Web.UI.WebControls.TextBox")
&& c.ID == null){
((TextBox) c).CssClass = "txtCountryIncrease";
((TextBox) c).ID = UniqueID;
}

if (c.Controls.Count > 0){
IterateThroughChildren(c);
}
}
}

private void btnSave_Click(object sender, EventArgs e){

}

I'm a bit of a newbe at this so please explain to me like you would a
two year old infant :)

Thanks in advance!
 
O

Octavio Hernandez

Hi,

You can do it with a loop similar to the one you've used in
IterateThroughChildren():

foreach (Control c in parent.Controls)
{
if (c is TextBox) // simpler that what you've done there
{
string name = c.ID;
string value = (c as TextBox).Text; // the cast is essential !!
// do something with name & value
}
}

With the cast, you indicate the compiler that you know that the Control
referenced by 'c' is a TextBox and not any other kind of control.

Regards - Octavio
 
U

utterberg

Much obliged!

It works like a charm. Maybe I've should have figured that one out my
self.

Thanks again!
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top