ASP Text box ID assignment using a for loop.? - c#

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.

Related

C# - How to add and delete multiple controls dynamically on button click

I am trying to code a survey application which requires text boxes to be added and removed dynamically. I managed to create text boxes dynamically on button click but I'm trying to find out how to removed the text boxes dynamically. Currently the delete functions works well only if I remove text boxes starting from the last. When I try deleting any text boxes in the middle followed by a delete of the last text box, a blank text box is created instead. I'm new to programming and am unsure if this is the best method to use. Also, I would like to find out if it is possible to nest text boxes(allow users to add options to their multi choice questions) to created text boxes and retrieve values inside later.
Code behind:
public partial class Dynamic_Form : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
for (int i = 0; i < TotalNumberAdded; ++i)
{
AddQuestion(i + 1);
}
}
protected int TotalNumberAdded
{
get { return (int)(ViewState["TotalNumberAdded"] ?? 0); }
set { ViewState["TotalNumberAdded"] = value; }
}
protected void btn_add_Click(object sender, EventArgs e)
{
TotalNumberAdded++;
AddQuestion(TotalNumberAdded);
}
private void AddQuestion(int controlNumber)
{
Panel newquestion = new Panel();
newquestion.ID = "Panel_" + controlNumber;
TextBox questionbox = new TextBox();
questionbox.ID = "Question_" + controlNumber;
questionbox.Text = "Question";
Button BtnDelete = new Button();
BtnDelete.ID = "BtnDelete_" + controlNumber;
BtnDelete.Text = "Delete"+ controlNumber;
BtnDelete.Click += delete_Click;
DropDownList DDLType = new DropDownList();
DDLType.ID = "DDLType_" + controlNumber;
DDLType.Items.Insert(0, new ListItem("TextField", ""));
DDLType.Items.Insert(1, new ListItem("Multiple Choice", ""));
//add controls
questions.Controls.Add(newquestion);
newquestion.Controls.Add(questionbox);
newquestion.Controls.Add(DDLType);
newquestion.Controls.Add(BtnDelete);
}
private void delete_Click(object sender,EventArgs e)
{
Button btn = (Button)sender;
Control control = btn.Parent;
if (questions.Controls.Contains(control))
{
questions.Controls.Remove(control);
control.Dispose();
TotalNumberAdded--;
Response.Write("Number of Questions:" + TotalNumberAdded);
}
}
}
Html file:
<body>
<form id="form1" runat="server">
<div>
<h1>Test Form</h1>
<asp:Button ID="btn_add" runat="server" Text="Add" OnClick="btn_add_Click" />
</div>
<div id="questions" runat="server">
</div>
</form></body>
.
#Aaron Yong, You can do these scenarios from client side using jQuery or javascript too. I have given below code to achieve what you want from server side.
private void delete_Click(object sender,EventArgs e)
{
Button btn = (Button)sender;
Control control = btn.Parent;
if (questions.Controls.Contains(control))
{
TotalNumberAdded--;
questions.Controls.Clear();
for (int i = 0; i < TotalNumberAdded; ++i)
{
AddQuestion(i + 1);
}
Response.Write("Number of Questions:" + TotalNumberAdded);
}
}
You want to recreate controls again, i have added for loop and removed some code in delete click event, then you will achieve.
As i have given above answer, you can also remove below code from previous answered.
questions.Controls.Remove(control);
control.Dispose();
You will get exact answer

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 = "";
}
}

Grab user input from dynamic text box

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

Request.Form giving extra values from Dynamic Textboxes

i am working with dynamic TextBoxes and then Getting their Values in code behind file. I am creating these boxes using Javascript. my asp.net page code is
<script type="text/javascript">
$(document).ready(function () {
var counter = 1;
$("#addButton").click(function () {
if (counter > 10) {
alert("Only 10 textboxes allow");
return false;
}
var newTextBoxDiv = $(document.createElement('div'))
.attr("id", 'TextBoxDiv' + counter);
newTextBoxDiv.html('<input type="text" name="textbox' + counter +
'" id="textbox' + counter + '" value="" >');
newTextBoxDiv.appendTo("#TextBoxesGroup");
counter++;
return false;
});
});
</script>
</head>
<body>
<form id="form2" runat="server">
<h1>jQuery add / remove textbox example</h1>
<asp:TextBox runat="server" ID="txt1" type='text' name="textname" />
<asp:Panel runat="server" ID='TextBoxesGroup'>
</asp:Panel>
<asp:LinkButton ID="addButton" runat="server">Add TextBox</asp:LinkButton>
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
</form>
<asp:Label ID="Label1" runat="server" Text=""></asp:Label>
</body>
i have one Textbox shown on the page, which should shows only one values when no dynamic Textbox is created. My C# code is
protected void Button1_Click(object sender, EventArgs e)
{
string name = txt1.Text + ",";
if (TextBoxesGroup.Controls.Count > 0)
{
for (int i = 1; i <= TextBoxesGroup.Controls.Count; i++)
{
name += Request.Form["textbox" + i] + ",";
}
}
Label1.Text = name;
}
on asp:button click it should display all the values separated by (,). but it is only showing top 2 values, one of which is asp:Textbox and second is dynamic Textbox,, i want the values of all the Textboxes created dynamically, and when no dynamic textbox is added it should only show the value from asp:textBox... Thanks in Advance
Html input elements created through javascript on the client, are not going to be in TextBoxesGroup.Controls on the server.
Changes in the client DOM structure have no effect on the Page's Control tree. The only thing affected will be the content of HttpRequest during postback. One way to know how many dynamically created input elements contributed to Request.Form data is to pass this information as part of the request. This is why you will have to go with the hidden field suggestion. The hidden field value will bring back the count of client-side inputs. You have to set it in javascript every time you create a new input, read it in server-side code, convert to integer and use in your for loop.
Add
<asp:HiddenField runat="server" ID="txtDynamicCount" value="0" />
to the the markup inside form tag.
In javascript click event after counter++; line add
$("#txtDynamicCount").val(counter);
In Button1_Click:
int count;
if (!int.TryParse(txtDynamicCount.Value, out count))
count = 0;
for (int i = 1; i <= count; i++)
{
...
}
The important difference from the other answer is that textboxes (input elements) will not persist between form submits.
You cannot populate server controls in client side. Instead, you want to populate them from server. Here is the sample -
<asp:PlaceHolder runat="server" ID="PlaceHolder1"></asp:PlaceHolder>
<asp:LinkButton ID="addButton" runat="server" OnClick="btnAdd_Click">Add TextBox</asp:LinkButton>
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" /><br/>
Posted Results: <asp:Label ID="Label1" runat="server" Text=""></asp:Label>
private List<int> _controlIds;
private List<int> ControlIds
{
get
{
if (_controlIds == null)
{
if (ViewState["ControlIds"] != null)
_controlIds = (List<int>)ViewState["ControlIds"];
else
_controlIds = new List<int>();
}
return _controlIds;
}
set { ViewState["ControlIds"] = value; }
}
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
foreach (int id in ControlIds)
{
var textbox = new TextBox();
textbox.ID = id.ToString();
PlaceHolder1.Controls.Add(textbox);
}
}
}
protected void btnAdd_Click(object sender, EventArgs e)
{
var reqs = ControlIds;
int id = ControlIds.Count + 1;
reqs.Add(id);
ControlIds = reqs;
var textbox = new TextBox();
textbox.ID = id.ToString();
PlaceHolder1.Controls.Add(textbox);
}
protected void Button1_Click(object sender, EventArgs e)
{
var ids = ControlIds;
foreach (var id in ids)
{
var textbox = (TextBox)PlaceHolder1.FindControl(id.ToString());
Label1.Text += textbox.Text + ", ";
}
}

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);
}

Categories

Resources