I want to retrieve a textbox value in a button click event, but as soon as the button is clicked, the postback fires and the value is empty. I have tried to create the textbox in a ( !isPostBack
) but that doesn't seem to work.
protected void Page_Load(object sender, EventArgs e)
{
Form.Controls.Add(t);
}
protected void Page_PreInit(object sender, EventArgs e)
{
predictionList = dc.getPredictions(Convert.ToInt32(Session["accountId"]));
fixtureList = dc.getFixtures();
t.CssClass = "panel panel-success table table-striped";
sortLists();
foreach (Fixture f in newList)
{
TableRow tr = new TableRow();
TableCell tc1= new TableCell();
TextBox tb1= new TextBox();
tb1.ID = "tb1";
tc1.Controls.Add(tb1);
tr.Cells.Add(tc1);
t.Rows.Add(tr);
}
}
Here I add the control, and here I want to process whatever is in the textbox:
protected void btSubmit_Click(object sender, EventArgs e)
{
foreach (TableRow r in t.Rows)
{
string textboxRead= ((TextBox)r.FindControl("tb1")).text;
int textboxInt = Convert.ToInt32(textboxRead);
}
}
Could it be that FindControl()
is not finding the textbox because it doesn't work recursively?
ie You have added the TextBox to a TableCell
, but you are performing your FindControl()
call on the TableRow
, not the TableCell
. So either call FindControl() from the Cell or use a recursive version.
For a recursive version of FindControl(), see: Better way to find control in ASP.NET
Try this:
TextBox tb1;
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
tb1 = ((TextBox)r.FindControl("tb1"));
}
}
protected void btSubmit_Click(object sender, EventArgs e)
{
string textboxRead = tb1.Text; // here you can get the tb1.Text
int textboxInt = Convert.ToInt32(textboxRead);
}
Hope this will help you.
protected void AddTextBox(object sender, EventArgs e)
{
int index = pnlTextBoxes.Controls.OfType<TextBox>().ToList().Count + 1;
this.CreateTextBox("txtDynamic" + index);
}
private void CreateTextBox(string id)
{
TextBox txt = new TextBox();
txt.ID = id;
pnlTextBoxes.Controls.Add(txt);
Literal lt = new Literal();
lt.Text = "<br />";
pnlTextBoxes.Controls.Add(lt);
}
see this link for details: http://www.aspsnippets.com/Articles/Get-Value-Text-of-dynamically-created-TextBox-in-ASPNet-using-C-and-VBNet.aspx
You need to give the ID's to all of your dynamically created controls. This is mandatory to prevent any ambiguity on post-back.
That includes tr
, tc1
, tb1
and maybe even t
controls.
Also, to find the value, use this snippet:
protected void btSubmit_Click(object sender, EventArgs e)
{
foreach (TableRow tr in t.Rows)
{
var tc1 = (TableCell)tr.FindControl("tc1");
var tb1 = (TextBox)tc1.FindControl("tb1");
int textboxInt = Convert.ToInt32(tb1.Text);
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.