Hi
I 'm programatically creating text boxes in gridview. But I'm unable to get the value from the text box.
I have a text box where i get the number of rows to be created and on pressing "Go" button, it populates gridview with dynamically created text boxes.
I need to read the values from gridview text boxes and this is where i got stuck.
My Gridview:
<asp:GridView ID="gvPlan" runat="server" ShowFooter="True" AutoGenerateColumns="true">
<Columns>
</Columns>
</asp:GridView>
Code Page:
protected void btnGo_Click(object sender, EventArgs e)
{
Insert_Grid();
}
private void Insert_Grid()
{
CreateGridView();
int numbers = int.Parse(txtRows.Text.Trim());
int cellCount = gvPlan.Rows[0].Cells.Count;
int rowsCount = gvPlan.Rows.Count;
foreach (GridViewRow row in gvPlan.Rows)
{
TextBox txtID = new TextBox();
txtID.ID = "tID" + (Convert.ToInt32(row.RowIndex + 1)).ToString();
txtID.Attributes.Add("runat", "server");
row.Cells[1].Controls.Add(txtID);
TextBox txtName = new TextBox();
txtName.ID = "tName" + (Convert.ToInt32(row.RowIndex + 1)).ToString();
txtName.Attributes.Add("runat", "server");
txtName.Attributes.Add("ReadOnly", "true");
row.Cells[2].Controls.Add(txtName);
}
}
private void CreateGridView()
{
int numbers = int.Parse(this.txtRows.Text.Trim());
DataTable dt = new DataTable();
dt.Columns.Add("ID", typeof(string));
dt.Columns.Add("Name", typeof(string));
for (int i = 0; i < numbers; i++)
{
dt.Rows.Add("", "");
}
ViewState["CurrentTable"] = dt;
gvPlan.DataSource = dt;
gvPlan.DataBind();
}
protected void btnSave_Click(object sender, EventArgs e)
{
int rowIndex = 0;
if (ViewState["CurrentTable"] != null)
{
DataTable dtCurrentTable = (DataTable)ViewState["CurrentTable"];
if (dtCurrentTable.Rows.Count > 0)
{
for (int i = 1; i <= dtCurrentTable.Rows.Count; i++)
{
TextBox gtxtID = (TextBox)gvPlan.Rows[rowIndex].Cells[1].FindControl("tID" + (rowIndex+1));
TextBox gtxtName = (TextBox)gvPlan.Rows[rowIndex].Cells[2].FindControl("tName" + (rowIndex + 1));
gtxtName.Text = gtxtID.Text;
rowIndex++;
}
}
}
The issue is in "btnSave_Click" procedure where i dont seem to get the value from gtxtID. It cannot find the text box control and the object is null
Your help is much appreciated.
Regards
Ilyas
What I have tried:
Tried debugging code by code but in vain