I have been pulling my hair out for the past few days writing an ASP.NET C# page that dynamically adds controls (textboxes, ddlists, etc) to a form depending on values stored in a database. The problem I am having is figuring out how to get the data from the controls once the user clicks the submit button. I have settled on attaching an event to each dynamically generated textbox for when the text of each textbox changes. Here is my code:
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
GenerateReportForm();
}
protected void GenerateReportForm()
{
//query db for number of textboxes and properties, store results in ReportsDataSet textBoxConrols -- code omitted for simplicity
foreach (ReportsDataSet.TextBoxRow tbRow in textBoxControls)
{
Label tempLabel = new Label();
tempLabel.Text = tbRow.Label;
tempLabel.ID = "tbl" + tbRow.ID.ToString();
TextBox tempTextBox = new TextBox();
tempTextBox.ID = tbRow.EMfield.ToString();
tempTextBox.TextChanged += new EventHandler(TextBox_TextChanged);
form1.Controls.Add(tempLabel);
form1.Controls.Add(tempTextBox);
form1.Controls.Add(new LiteralControl("<br>"));
}
protected void TextBox_TextChanged(object sender, EventArgs e)
{
TextBox tempTextBox = (TextBox)sender;
Session.Add(tempTextBox.ID.ToString(), tempTextBox.Text.ToString()); //store text into persistent session variable
}
I don't understand why the TextBox_TextChanged function is not being called after clicking the form's submit button. Instead, the code for the submit button click handler is run. Shouldn't the textbox text changed handler run first? My Page_Load method contains no code.
I would really appreciate anyone's input on this, it has been killing me the past couple days. Suggestions for a better way to grab dynamically created controls (user input) data would also be work, just need to get the text in those textboxes one way or another! Thanks!
There are 2 ways to populate the control. one is through server side event and the other through client side event. By just seeing your code it seems it is done in server side
it will work fine. But on TextChanged event,if you want to populate someother control with the value from this Textbox, then dont put it in a session instead display it in the targeted control i.e,Textboxintsance.Text
Other way around is using the client side event. on keypress event of the textbox, take the value from the current control and assign it to the required control
Code would like this
temptextbox.Attributes["On
in the client side
function KeyPress_TextChanged(curre
{
var currenttextboxidIns= document.getElementId(curr
var toreplacecontrolIns= document.getElementId(tore
toreplacecontrolIns = currenttextboxidIns;
return false;
}
Is this you are looking for???