Grab user input from dynamic text box - c#

I have two buttons. One button that creates the Textbox and another that submits the information. I'm having trouble retrieving the users texts once the textbox has been created. Here is the code:
private void CreateTextBox(int j) //Creates the fields / cells
{
TextBox t = new TextBox();
t.ID = "Textbox" + j;
//t.Text = "Textbox" + j;
lstTextBox.Add(t);
var c = new TableCell();
c.Controls.Add(t);
r.Cells.Add(c);
table1.Rows.Add(r);
Session["test"] = lstTextBox;
}
protected void Button2_Click(object sender, EventArgs e)
{
string[] holder = new string[4];
for (int i = 0; i < holder.Length; i++)
{
holder[i] = "";
}
List<TextBox> lstTextBox = (Session["test"] as List<TextBox>);
if (lstTextBox.Count < Counter)
{
int i = lstTextBox.Count;
for (int j = 0; j < i; j++)
{
holder[j] = lstTextBox[j].Text;
}
SqlConnection conns = new SqlConnection(ConfigurationManager.ConnectionStrings["TestDBConnectionString1"].ConnectionString);
SqlCommand cmd = new SqlCommand("Insert into LoanerForm (field0, field1, field2, field3) Values (#field0, #field1, #field2, #field3)", conns);
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#field0", holder[0]);
cmd.Parameters.AddWithValue("#field1", holder[1]);
cmd.Parameters.AddWithValue("#field2", holder[2]);
cmd.Parameters.AddWithValue("#field3", holder[3]);
conns.Open();
cmd.ExecuteNonQuery();
conns.Close();
}
Counter = 0;
Button1.Visible = true; //Going to submit data to SQL
}
Thank you in advance!

Here is how you create TextBoxes dynamically. It keeps track of the number of textboxes in ViewState.
<asp:Button runat="server" ID="Button1" OnClick="Button1_Click"
Text="Create TextBoxes" />
<asp:Button runat="server" ID="Button2" OnClick="Button2_Click"
Text="Save TextBoxes to Database" />
<asp:PlaceHolder runat="server" ID="PlaceHolder1"></asp:PlaceHolder>
public int Counter
{
get { return Convert.ToInt32(ViewState["Counter"] ?? "0"); }
set { ViewState["Counter"] = value; }
}
protected void Page_Load(object sender, EventArgs e)
{
// Need to reload those textboxes on page back
// Otherwise, they will becomes null
int total = Counter;
for (int i = 0; i < total; i++)
{
var textBox = new TextBox
{
ID = "TextBox" + i,
Text = "TextBox" + i
};
PlaceHolder1.Controls.Add(textBox);
}
}
private void CreateTextBox(int id)
{
var textBox = new TextBox
{
ID = "TextBox" + id,
Text = "TextBox" + id
};
PlaceHolder1.Controls.Add(textBox);
}
protected void Button1_Click(object sender, EventArgs e)
{
CreateTextBox(Counter);
Counter = Counter + 1;
}
protected void Button2_Click(object sender, EventArgs e)
{
int total = Counter;
for (int i = 0; i < total; i++)
{
var textbox = PlaceHolder1.FindControl("TextBox" + i) as TextBox;
var text = textbox.Text;
// Do something with text
}
}

Don't store the TextBoxes in Session; rather, create them on the page.
The trick is creating them at the right time EVERY time (i.e. with each PostBack). Try loading them OnLoad() for the page (or CreateChildControls() if possible).
Once you do that, ASP.NET will automatically associate the input with the TextBox and you should be able to reference them as you normally would or via .FindControl() of the parent.

I think You used big program for generating dynamic textboxes and inserting into data base.For retriving text from dynamically generated textboxes,use the code below..
Request.Form["Textbox" + i.ToString()]
where "i" represents the number of textboxes you generated.
For more info.Please Check the below link.
how to insert value to sql db from dynamically generated textboxes asp.net

Related

Database Records on Page Load - Dynamic Text Fields

I am working with dynamically created text fields. Most solutions I have found thus far have been related to retaining view state on postback, but I believe I have taken care of that issue. On postback, the values that are in the text fields are retained.
The issue I am having: I can't get the database values currently stored to load in the dynamic fields. I am currently calling loadUpdates() to try to do this, but unsure how to grab the data row, while also making sure I can continue to add new fields (or remove them). How can I achieve this?
"txtProjectsUpdate" is the text field, "hidFKID" is the foreign key to a parent table, and "hidUpdateID" is the hidden value of the primary key in the child table (the values I am attempting to load).
Markup:
<div>
<asp:Button ID="btnAddTextBox" runat="server" Text="Add" OnClick="btnAddTextBox_Click" />
<asp:Placeholder ID="placeHolderControls" runat="server"/>
</div>
<asp:TextBox runat = "server" ID = "hidUpdateID" />
<asp:HiddenField runat = "server" ID = "hidFKID" />
Code behind:
protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack)
{
for (var i = 0; i < TextBoxCount; i++)
AddTextBox(i);
}
if (!IsPostBack)
{
DataTable dt = new DataTable();
dt = selectDetails();
tryHidFKID(hidFKID, dt.Rows[0]["fkprjNumber"].ToString());
loadUpdates();
}
}
protected void btnAddTextBox_Click(object sender, EventArgs e)
{
AddTextBox(TextBoxCount);
TextBoxCount++;
}
private int TextBoxCount
{
get
{
var count = ViewState["txtBoxCount"];
return (count == null) ? 0 : (int)count;
}
set { ViewState["txtBoxCount"] = value; }
}
private void btnRemove_Click(object sender, EventArgs e)
{
var btnRemove = sender as Button;
if (btnRemove == null) return;
btnRemove.Parent.Visible = false;
}
private void AddTextBox(int index)
{
var panel = new Panel();
panel.Controls.Add(new TextBox
{
ID = string.Concat("txtProjectUpdates", index),
Rows = 5,
Columns = 130,
TextMode = TextBoxMode.MultiLine,
CssClass = "form-control",
MaxLength = 500
});
panel.Controls.Add(new TextBox
{
ID = string.Concat("hidUpdateID", index)
});
var btn = new Button { Text = "Remove" };
btn.Click += btnRemove_Click;
panel.Controls.Add(btn);
placeHolderControls.Controls.Add(panel);
}
protected void loadUpdates()
{
DataTable dt = dbClass.ExecuteDataTable
(
"spSelectRecords", <db>, new SqlParameter[1]
{
new SqlParameter ("#vFKPrjNumber", hidFKID.Value)
}
);
AddTextBox(TextBoxCount);
TextBoxCount++;
}
protected void tryHidFKID(HiddenField hidFKID, string txtSelected)
{
try
{
hidFKID.Value = txtSelected;
}
catch
{
hidFKID.Value = "";
}
}

how I save dynamically created Labels and Checkboxes values into sql server

how I save dynamically created Labels and Checkboxes values into sql server
protected void EventDuration_DDL_SelectedIndexChanged(object sender, EventArgs e)
{
int n = Int32.Parse(EventDuration_DDL.SelectedItem.ToString());
for (int i = 0; i < n; i++)
{
Label NewLabel = new Label();
NewLabel.ID = "Label" + i;
var eventDate = Calendar1.SelectedDate.Date.AddDays(i);
NewLabel.Text = eventDate.ToLongDateString();
CheckBox newcheck = new CheckBox();
newcheck.ID = "CheckBox" + i;
this.Labeldiv.Controls.Add(new LiteralControl("<span class='h1size'>"));
this.Labeldiv.Controls.Add(NewLabel);
this.Labeldiv.Controls.Add(new LiteralControl("</span>"));
this.Labeldiv.Controls.Add(new LiteralControl("<div class='make-switch pull-right' data-on='info'>"));
this.Labeldiv.Controls.Add(newcheck);
this.Labeldiv.Controls.Add(new LiteralControl("</div>"));
this.Labeldiv.Controls.Add(new LiteralControl("<br/>"));
}
}
protected void Wizard1_FinishButtonClick(object sender, WizardNavigationEventArgs e)
{
con.Open();
SqlCommand cmd1 = new SqlCommand("insert into Event(EventName,StartDate,EventDuration,StartTime,EndTime,SlotDuration) output inserted.EventId values(#EventName,#StartDate,#EventDuration,#StartTime,#EndTime,#SlotDuration)", con);
cmd1.Parameters.AddWithValue("#EventName", EventName_TB.Text);
cmd1.Parameters.AddWithValue("#StartDate", StartDate_TB.Text);
cmd1.Parameters.AddWithValue("#EventDuration", EventDuration_DDL.Text);
cmd1.Parameters.AddWithValue("#StartTime", StartTime_DDL.Text);
cmd1.Parameters.AddWithValue("#EndTime", EndTime_DDL.Text);
cmd1.Parameters.AddWithValue("#SlotDuration", SlotDuration_DDL.Text);
Int32 id = (Int32)cmd1.ExecuteScalar();
var label = Labeldiv.FindControl("Label1") as Label;
var checkbox = Labeldiv.FindControl("CheckBox1") as CheckBox;
using (SqlCommand cmd2 = new SqlCommand("insert into EventDays(EventDay,EventStatus)values(#EventDay,#EventStatus)", con))
{
int n = Int32.Parse(EventDuration_DDL.SelectedItem.ToString());
for (int i = 0; i < n; i++)
{
var paramDay = cmd2.Parameters.Add("#EventDay", SqlDbType.DateTime);
var paramStatus = cmd2.Parameters.Add("#EventStatus", SqlDbType.Int);
paramDay.Value = label.Text;
paramStatus.Value = checkbox.Checked ? 1 : 0;
cmd2.ExecuteNonQuery();
}
}
con.Close();
}
I have created Labels and CheckBoxes dynamically in EventDuration_DDL_SelectedIndexChanged.
now I want to save these values into sql server in Wizard1_FinishButtonClick.
how I save dynamically created Labels and Checkboxes values into sql server
.
.
.
.
..
You have to recreate those dynamically created labels and check boxes for the button click as well, because when the user clicks the finish button, that causes a post back to the server and the page is recreated, but the dynamic label and check box logic is not executed, thus your database saving logic cannot "find" these controls.
I recommend moving your dynamic label and check box creation logic to a separate method that can be called by the EventDuration_DDL_SelectedIndexChanged() and Wizard1_FinishButtonClick(), like this:
private void BuildDynamicControls()
{
int n = Int32.Parse(EventDuration_DDL.SelectedItem.ToString());
for (int i = 0; i < n; i++)
{
Label NewLabel = new Label();
NewLabel.ID = "Label" + i;
var eventDate = Calendar1.SelectedDate.Date.AddDays(i);
NewLabel.Text = eventDate.ToLongDateString();
CheckBox newcheck = new CheckBox();
newcheck.ID = "CheckBox" + i;
this.Labeldiv.Controls.Add(new LiteralControl("<span class='h1size'>"));
this.Labeldiv.Controls.Add(NewLabel);
this.Labeldiv.Controls.Add(new LiteralControl("</span>"));
this.Labeldiv.Controls.Add(new LiteralControl("<div class='make-switch pull-right' data-on='info'>"));
this.Labeldiv.Controls.Add(newcheck);
this.Labeldiv.Controls.Add(new LiteralControl("</div>"));
this.Labeldiv.Controls.Add(new LiteralControl("<br/>"));
}
}
Now in your event handlers, you can call this method, like this:
protected void EventDuration_DDL_SelectedIndexChanged(object sender, EventArgs e)
{
BuildDynamicControls();
}
protected void Wizard1_FinishButtonClick(object sender, WizardNavigationEventArgs e)
{
BuildDynamicControls();
}
Alternatively, you can call BuildDynamicControls() in the Page_Load. This takes care of other buttons on the page destroying the values when they cause a post back, like this:
protected void Page_Load(object sender, EventArgs e)
{
// Do other page load logic here
BuildDynamicControls();
}
Note: If you go this route, then you will not need to call BuildDynamicControls() in the EventDuration_DDL_SelectedIndexChanged() or Wizard1_FinishButtonClick() methods, because the Page_Load happens before either of those events in the page life-cycle.

ASP Text box ID assignment using a for loop.?

I am a noob and i've been trying to figure out how we may assign an ID to asp:TextBox tags on creation in ASP.NET using c#.
Example:
I need to create a thread that may have multiple textboxes.
When a user clicks on a button, a text box must be generated with an ID say, txt01. On being clicked the second time, the ID of the generated text box must be txt02 and so on..depending on the number of clicks.
Thanks in Advance.
Remember last ID in some variable, for example int lastID, then in button's onClick method when creating the new TextBox assign its ID="txt"+lastID;.
You have to persist the lastID during page postbacks, you can store it in a ViewState.
Take and placeholder in your aspx page: eg: <asp:PlaceHolder runat="server" ID="pholder" />
and in code behind:
TextBox txtMyText = new TextBox();
tb1.ID = YourDynamicId;
pholder.Controls.Add(txtMyText);
You can save current id in ViewState and get the same id and assign incremented id to your dynamic textbox.
Try This:
int i = 1;
if (ViewState["i"] == null)
{
ViewState["i"] = i;
}
else
i = (int)ViewState["i"];
PlaceHolder1.Controls.Clear();
for (int j = 1; j <= i; j++)
{
TextBox TextBox = new TextBox();
TextBox.ID = "TextBox" + j.ToString();
PlaceHolder1.Controls.Add(TextBox);
}
ViewState["i"] = i + 1;
add this on your .aspx page
<asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder>
Hope This help.
I think this is what you are looking for -
You will notice that I have used Page_Init because if you create/add the controls in Page_Load then FindControl will return null in PostBack. And also any data you entered in the dynamically added controls will not persist during Postbacks.
But Page_Init is called before ViewState or PostBack data is loaded. Therefore, you can not use ViewState or any other controls to keep the control count. So I have used Session to keep the count.
Try it out and let me know what you think.
ASPX Page
<form id="form1" runat="server">
<asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder>
<asp:Button ID="btnCreate" runat="server" Text="Create" OnClick="btnCreate_Click" />
<asp:Button ID="btnRead" runat="server" Text="Read" OnClick="btnRead_Click" />
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
</form>
Code Behind
protected int NumberOfControls
{
get { return Convert.ToInt32(Session["noCon"]); }
set { Session["noCon"] = value.ToString(); }
}
private void Page_Init(object sender, System.EventArgs e)
{
if (!Page.IsPostBack)
//Initiate the counter of dynamically added controls
this.NumberOfControls = 0;
else
//Controls must be repeatedly be created on postback
this.createControls();
}
private void Page_Load(object sender, System.EventArgs e)
{
}
protected void btnCreate_Click(object sender, EventArgs e)
{
TextBox tbx = new TextBox();
tbx.ID = "txtData"+NumberOfControls;
NumberOfControls++;
PlaceHolder1.Controls.Add(tbx);
}
protected void btnRead_Click(object sender, EventArgs e)
{
int count = this.NumberOfControls;
for (int i = 0; i < count; i++)
{
TextBox tx = (TextBox)PlaceHolder1.FindControl("txtData" + i.ToString());
//Add the Controls to the container of your choice
Label1.Text += tx.Text + ",";
}
}
private void createControls()
{
int count = this.NumberOfControls;
for (int i = 0; i < count; i++)
{
TextBox tx = new TextBox();
tx.ID = "txtData" + i.ToString();
//Add the Controls to the container of your choice
PlaceHolder1.Controls.Add(tx);
}
}
store the id in a ViewState something like this
First initialise a count variable similiar to this.
in your class write this
protected int replyCount //declare the variable
{
get { return (int)ViewState["replyCount"]; }
set { ViewState["replyCount"] = value; }
}
In your page Load write this to initialise the replyCount if its not a postback;
protected void Page_Load(object sender, EventArgs e)
{
if(!page.IsPostBack)
{
replyCount = 0; //initialise the variable
}
}
then while creating dynamic textboxes
protected void Button_Click(Object sender, EventArgs e)
{
TextBox tb = new TextBox();
tb.id = "tb" + replycount; //use the variable
replycount++; // and after using increment it.
form.controls.add(tb); // assuming your form name is "form"
}
Thats it you should do.

Read all rows and cell values dynamic table asp.net

I found the tutorial to create a dynamic table and add rows:
http://geekswithblogs.net/dotNETvinz/archive/2009/06/29/faq-dynamically-adding-rows-in-asp-table-on-button-click.aspx
How can I read all rows in the table, and then the values ​​of the textbox in the cells? The values ​​are entered in a table in a database (SQL Server).
Can I continue to use C# and asp.net or do I have to use Javascript?
I hope someone will give me help.
This is the code:
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Dynamic Adding of Rows in ASP Table Demo</title>
</head>
<body>
<form id="form1" runat="server">
<asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Add New Row" />
</form>
</body>
</html>
CODE BEHIND:
public partial class _Default1 : System.Web.UI.Page
{
//A global variable that will hold the current number of Rows
//We set the values to 1 so that it will generate a default Row when the page loads
private int numOfRows = 1;
protected void Page_Load(object sender, EventArgs e)
{
//Generate the Rows on Initial Load
if (!Page.IsPostBack)
{
GenerateTable(numOfRows);
}
}
protected void Button1_Click(object sender, EventArgs e)
{
if (ViewState["RowsCount"] != null)
{
numOfRows = Convert.ToInt32(ViewState["RowsCount"].ToString());
GenerateTable(numOfRows);
}
}
private void SetPreviousData(int rowsCount, int colsCount)
{
Table table = (Table)Page.FindControl("Table1");
if (table != null)
{
for (int i = 0; i < rowsCount; i++)
{
for (int j = 0; j < colsCount; j++)
{
//Extracting the Dynamic Controls from the Table
TextBox tb = (TextBox)table.Rows[i].Cells[j].FindControl("TextBoxRow_" + i + "Col_" + j);
//Use Request objects for getting the previous data of the dynamic textbox
tb.Text = Request.Form["TextBoxRow_" + i + "Col_" + j];
}
}
}
}
private void GenerateTable(int rowsCount)
{
//Creat the Table and Add it to the Page
Table table = new Table();
table.ID = "Table1";
Page.Form.Controls.Add(table);
//The number of Columns to be generated
const int colsCount = 3;//You can changed the value of 3 based on you requirements
// Now iterate through the table and add your controls
for (int i = 0; i < rowsCount; i++)
{
TableRow row = new TableRow();
for (int j = 0; j < colsCount; j++)
{
TableCell cell = new TableCell();
TextBox tb = new TextBox();
// Set a unique ID for each TextBox added
tb.ID = "TextBoxRow_" + i + "Col_" + j;
// Add the control to the TableCell
cell.Controls.Add(tb);
// Add the TableCell to the TableRow
row.Cells.Add(cell);
}
// And finally, add the TableRow to the Table
table.Rows.Add(row);
}
//Set Previous Data on PostBacks
SetPreviousData(rowsCount, colsCount);
//Sore the current Rows Count in ViewState
rowsCount++;
ViewState["RowsCount"] = rowsCount;
}
}
Since you're creating the table dynamically, you can't reference it like controls that are statically embedded on the page. To get a reference to the Table object you'll need to find it in the Page's ControlCollection and cast it out, just like in the example:
Table table = (Table)Page.FindControl("Table1");
The Table class contains a table row collection which you will then need to loop over. Each row in the row collection has a collection of cells, each of which will contain child controls (see: Controls property) which will be your textboxes.
Hi if you take look at SetPreviousData this function is trying to read previous textbox value but there is some thing wrong with it i have done following changes and it works fine
first of all the following code in SetPreviousData
Table table = (Table)Page.FindControl("Table1");
is always returning NULL because this function is not a recursive function and your table may be inside a container in your page so add following function to your code
private Control FindControlRecursive(Control root, string id)
{
if (root.ID == id)
{
return root;
}
foreach (Control c in root.Controls)
{
Control t = FindControlRecursive(c, id);
if (t != null)
{
return t;
}
}
return null;
}
and change the code
Table table = (Table)Page.FindControl("Table1");
to
Table table = FindControlRecursive(Page , "Table1") as Table;
in next step change the following code in SetPreviousData
tb.Text = Request.Form["TextBoxRow_" + i + "Col_" + j];
to
tb.Text = Request.Form[tb.UniqueID];
set break points and see the results if it's tough to you let me know to provide you a function which returns table data in a datatable
I think you must bind your table again at the Page_load event.For example if you are binding the table at View_Click button event,you have to call this method in Page_load event as View_Click(null,null).
<script type="text/javascript">
var StringToSend='';
function fncTextChanged(newvalueadded) {
if (StringToSend != '')
StringToSend = StringToSend + ';' + newvalueadded;
else
StringToSend = newvalueadded;
//alert(StringToSend); -- For Testing all values
// now store the value of StringToSend into hidden field ---- HFTEXTVALUES to access it from server side.
}
</script>
<asp:Button ID="Save" runat="server" onclick="SaveTextBoxValues_Click" Text="save" />
<asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Add New Row" />
<asp:HiddenField ID="hfTextValues" runat="server" Visible="false" Value="" />
Server Side :
protected void Page_Load(object sender, EventArgs e)
{
//Generate the Rows on Initial Load
if (!Page.IsPostBack)
{
GenerateTable(numOfRows);
}
}
protected void Button1_Click(object sender, EventArgs e)
{
if (ViewState["RowsCount"] != null)
{
numOfRows = Convert.ToInt32(ViewState["RowsCount"].ToString());
GenerateTable(numOfRows);
}
}
protected void SaveTextBoxValues_Click(object sender, EventArgs e)
{
string AllTextBoxValues = hfTextValues.Value;
string[] EachTextBoxValue = AllTextBoxValues.Split('~');
//here you would get all values, EachTextBoxValue[0] gives value of first textbox and so on.
}
private void GenerateTable(int rowsCount)
{
//Creat the Table and Add it to the Page
Table table = new Table();
table.ID = "Table1";
Page.Form.Controls.Add(table);
//The number of Columns to be generated
const int colsCount = 3;//You can changed the value of 3 based on you requirements
// Now iterate through the table and add your controls
for (int i = 0; i < rowsCount; i++)
{
TableRow row = new TableRow();
for (int j = 0; j < colsCount; j++)
{
TableCell cell = new TableCell();
TextBox tb = new TextBox();
HiddenField hf = new HiddenField();
// Set a unique ID for each TextBox added
tb.ID = "tb" + i + j;
hf.ID = "hf" + i + j;
tb.Attributes.Add("onblur", "fncTextChanged(this.value);");
// Add the control to the TableCell
cell.Controls.Add(tb);
// Add the TableCell to the TableRow
row.Cells.Add(cell);
}
// And finally, add the TableRow to the Table
table.Rows.Add(row);
}
}
Let me know if you have any questions.
One more thing, if you wish to store the values and retrieve them later, the code would be modified accordingly.
reference for a dynamic table doesn't work well , blame microsoft ,
I use this :
Save inside a session List[YourObjectData] and every time you get into Page_Load , fill it the table
here is solution for number 2 :
somewhere inside Default.aspx
<div class="specialTable">
<asp:Table ID="Table1" runat="server" />
</div>
Code behind:
protected void Page_Load(object sender, EventArgs e)
{
FillDynamicTable();
if (!IsPostBack)
{
}
}
private void FillDynamicTable()
{
Table1.Rows.Clear(); // Count=0 but anyways
if (Session["Table1"] == null) return;
foreach (var data in Session["Table1"] as List<MyObject>)
{
AddRow(data);
}
}
private void AddRow(MyObject data)
{
var row = new TableRow { Height = 50 };
var cell = new TableCell();
var label = new Label { Text = data.something, Width = 150 };
cell.Controls.Add(label);
row.Cells.Add(cell);
Table1.Rows.Add(row);
}

Dynamic textfields does not retain data on postback

I created a webform that allows the user to dynamically add more textboxes. Right now, as the button is clicked to add another field, it postbacks to itself. The controls are added in the Pre_Init. However when the page reconstructs itself the textbox names are different each time so the data is not being retained on each postback.
protected void Page_PreInit(object sender, EventArgs e)
{
MasterPage master = this.Master; //had to do this so that controls could be added.
createNewTextField("initEnumValue",true);
RecreateControls("enumValue", "newRow");
}
private int FindOccurence(string substr)
{
string reqstr = Request.Form.ToString();
return ((reqstr.Length - reqstr.Replace(substr, "").Length) / substr.Length);
}
private void RecreateControls(string ctrlPrefix, string ctrlType)
{
string[] ctrls = Request.Form.ToString().Split('&');
int cnt = FindOccurence(ctrlPrefix);
//Response.Write(cnt.ToString() + "<br>");
if (cnt > 0)
{
for (int k = 1; k <= cnt; k++)
{
for (int i = 0; i < ctrls.Length; i++)
{
if (ctrls[i].Contains(ctrlPrefix + k.ToString()) && !ctrls[i].Contains("EVENTTARGET"))
{
string ctrlID = ctrls[i].Split('=')[0];
if (ctrlType == "newRow")
{
createNewTextField(ctrlID,false);
}
break;
}
}
}
}
}
protected void addEnum_Click(object sender, ImageClickEventArgs e)
{
int cnt = FindOccurence("enumValue");
createNewTextField("enumValue" + Convert.ToString(cnt + 1),false);
// Response.Write(cnt.ToString() + "<br>");
}
private void createNewTextField(string ID, bool button)
{
Response.Write(ID + "<br/>"); //this is where I'm getting different names each time there is a postback
if (ID != "initEnumValue") //create new line starting with the second tb.
{
LiteralControl newLine = new LiteralControl();
newLine.Text = "<br />";
this.plhEnum.Controls.Add(newLine);
}
TextBox newTb = new TextBox();
newTb.ID = ID;
this.plhEnum.Controls.Add(newTb);
if (button) //create the button only on the first one.
{
LiteralControl space = new LiteralControl();
space.Text = " ";
this.plhEnum.Controls.Add(space);
ImageButton imgbutton = new ImageButton();
imgbutton.ID = "addEnum";
imgbutton.ImageUrl = "~/images/add.png";
imgbutton.Click += new ImageClickEventHandler(addEnum_Click);
imgbutton.CausesValidation = false;
this.plhEnum.Controls.Add(imgbutton);
}
//endEnumRow();
//this.plhEnum.Controls.Add(newTb);
}
I have tried this solution How can I get data from dynamic generated controls in ASP .NET MVC?

Categories

Resources