I’m trying to get Text from a dynamically craeted server textbox.
I’m just checking by getting the text into another textbox I placed in the aspx file, but all I get is always an empty string..
(I also tried another method that is enclosed in remark, but it doesn’t work either)
Here’s the code behind:
public partial class Product_list : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
create_table();
}
protected void create_table()
{
DBServices db1=new DBServices();
List<Product> list1 = db1.ReadProducts();
int id_number=1;
int id_numer2 = 7;
int id_number3 = 13;
Table tbl = new Table();
tbl.ID = "tbl1";
this.Controls.Add(tbl);
foreach (Product p1 in list1)
{
TableRow rw = new TableRow();
rw.ID = Convert.ToString(id_numer2);
TableCell cell1 = new TableCell();
cell1.Text = p1.Name;
TableCell cell2 = new TableCell();
Image img = new Image();
img.ImageUrl = p1.ImagePath;
img.Height = 50;
img.Width = 50;
cell2.Controls.Add(img);
TableCell cell3 = new TableCell();
cell3.ID = Convert.ToString(id_number3);
TextBox textbox1 = new TextBox();
textbox1.ID = Convert.ToString(id_number);
cell3.Controls.Add(textbox1);
rw.Controls.Add(cell1);
rw.Controls.Add(cell2);
rw.Controls.Add(cell3);
tbl.Controls.Add(rw);
id_number++;
id_numer2++;
id_number3++;
}
}
void save_list()
{
List<Product> Items_list = new List<Product>();
//TextBox aControl =Page.FindControl("1") as TextBox;
/var tbl1 = this.Page.FindControl("tbl1") as Table;
var tr = tbl1.FindControl("7") as TableRow;
var td = tr.FindControl("13") as TableCell;
var txt = td.FindControl("1") as TextBox;
txt1.Value = txt.Text;
}
protected void Button1_Click(object sender, EventArgs e)
{
save_list();
}
}
and here is the aspx code:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Product_list.aspx.cs" Inherits="Product_list" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script runat=server>
public override void VerifyRenderingInServerForm(Control control)
{
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div id="header">
<h1>Items List</h1>
</div>
<div id="prod_table" runat="server"></div>
<div>
<input type="text" runat="server" id="txt1" />
<asp:Button ID="Button1" runat="server" Text="Button"
onclick="Button1_Click" />
</div>
</form>
</body>
</html>
You should understand that you recreate your table on every post to the server. So, you cannot rely on data from your dynamic table, because it would be lost after each posting. My suggestion is to keep this value in permanent input control with a type “hidden”. Then on button click event just get this value and assign it to a textbox.