I have a problem. I have an aspx page with one ContentPlaceHolder. In that ContentPlaceHolder i have one div and one button, like following:
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<div id="divCustomCustomers" runat="server" >
</div>
<asp:Button runat="server" ID="btnInsert" Text="Insert" OnClick="btnInsert_OnClick" />
</asp:Content>
On the PageLoad i am dynamically adding a textbox control to the divCustomCustomers like following:
private void AddControls(string currentCustomer)
{
var customTable = new Table();
customTable.ID = "tableCustomCustomer_" + currentCustomer;
var customTrHeaders = new TableRow();
customTrHeaders.Cells.Add(new TableCell() { Text = "TextId" });
customTable.Controls.Add(customTrHeaders);
var customTableCells = new TableRow();
var tableCellTextId = new TableCell();
var textBoxTextId = new TextBox() { ID = "tbTextId_" + currentCustomer };
tableCellTextId.Controls.Add(textBoxTextId);
customTableCells.Cells.Add(tableCellTextId);
customTable.Controls.Add(customTableCells);
divCustomCustomers.Controls.Add(customTable);
}
Then i enter some random text in that textbox (var textBoxTextId = new TextBox() { ID = "tbTextId_" + currentCustomer };).
When i then click my button and call the funtcion btnInsert_OnClick, i can not seem to get the text of the textbox. And after the postback the textbox has dissappeared. I have tried to fetch the textbox in following ways:
protected void btnInsert_OnClick(object sender, EventArgs e)
{
string currentCustomer = "sameCustomerAsWhenCreated";
var control = divCustomCustomers.FindControl("tbTextId_" + currentCustomer) as TextBox;
var control2 = divCustomCustomers.FindControl("ContentPlaceHolder1_tbTextId_" + currentCustomer) as TextBox;
var control3 = this.FindControl("tbTextId_" + currentCustomer) as TextBox;
var control4 = this.FindControl("ContentPlaceHolder1_tbTextId_" + currentCustomer) as TextBox;
}
I have also tried to use a FindControl method i read about:
protected void btnInsert_OnClick(object sender, EventArgs e)
{
string currentCustomer = "sameCustomerAsWhenCreated";
var control = FindControl(this.Controls, "tbTextId_" + currentCustomer);
}
private Control FindControl(ControlCollection controlCollection, string name)
{
foreach (Control control in controlCollection)
{
if (control.ID.ToLower() == name.ToLower() || control.ClientID.ToLower() == name.ToLower())
{
return control;
}
if (control.Controls.Count > 0)
{
Control result = FindControl(control.Controls, name);
if (result != null)
{
return result;
}
}
}
return null;
}
But nothing works, i can not get the control and use the text. Can you guys help me? Please!