Hello,
You first have to be sure that your gridview will be recreated after each postback. If you press the update button, it causes a post back and the dynamically created Textboxes will be lost. So let's say we have this dummy data table:
DataTable DummyDT()
{
DataTable dt = new DataTable();
dt.Columns.Add("FirstValue", Type.GetType("System.Int32"));
dt.Columns.Add("SecondValue", Type.GetType("System.Int32"));
dt.Columns.Add("Result", Type.GetType("System.Int32"));
dt.Columns.Add("Placeholder1", Type.GetType("System.Int32"));
dt.Columns.Add("Placeholder2", Type.GetType("System.Int32"));
dt.Columns.Add("Placeholder3", Type.GetType("System.Int32"));
for (int i = 0; i <= 10; i++)
{
DataRow dr;
dr = dt.NewRow();
dr["FirstValue"] = i;
dr["SecondValue"] = i * i;
dr["Result"] = i + i * i;
dr["Placeholder1"] = 0;
dr["Placeholder2"] = 0;
dr["Placeholder3"] = 0;
dt.Rows.Add(dr);
}
return dt;
}
You'll have to rebind it to your Gridview after each postback:
protected void Page_Load(object sender, EventArgs e)
{
gridUptMark.DataSource = DummyDT();
gridUptMark.DataBind();
}
(You will not have this problem with SQLDatasource, ObjectDataSource and so on..)
Assured this, you can create your textbox in the rowdatabound event, but you'll get an error in your code because you are creating textboxes with the same ID, so here's the fix:
tbox.ID = "txt" + i;
Finally, you can retreive your values. But your code had some problems here too, here's a fix:
protected void Update_Click(object sender, EventArgs e)
{
string test;
for (int i = 0; i < gridUptMark.Rows.Count; i++)
{
for (int j = 3; j < gridUptMark.Rows[i].Cells.Count; j++)
{
TableCell cell = (TableCell)gridUptMark.Rows[i].Cells[j];
test = ((TextBox)cell.FindControl("txt" + j)).Text;
Response.Write(test);
}
}
}
j starts from 3 because in the first 3 cells you don't have textboxes, that's why you had the System.NullReferenceException error (important: Findcontrol("txt" + j) or it won't find your textboxes).
And also your line:
test = cell.FindControl("txt").ToString();
would return the string "System.Web.UI.WebControls.TextBox" instead of the textbox value.
Hope it helps you.