C# .NET - Not able to retrive value from dynamic column in gridview

Asked By prakash ramalingam on 25-Aug-15 10:53 AM
dear friends,

I have added dynamic rows and columns with textbox in gridview, but not able to retrieve the values.

code sample for column add dynamically

        DataTable dtCurrentTable = (DataTable)ViewState["CurrentTable"];
          DataTable dtS = dtCurrentTable;
          string colName = "NewColumn" + colCount;
          dtS = AddColumn(dtS, colName);
          BindGrid(dtS);
          colCount++;
      
          // Rows
          foreach (GridViewRow row in this.GrdDynamic.Rows)
          {
            for (int i = initialCount; i < row.Cells.Count; i++)
            {
              TableCell tc = row.Cells[i];
              TextBox textBox = new TextBox();
              textBox.ID = "txtData" + i;
              textBox.Text = dtS.Rows[0].Field<string>(i);
              textBox.EnableViewState = true;
              textBox.Attributes.Add("runat", "server");

              tc.Controls.Add(textBox);
            }
          }

code sample for row add,

if (dtCurrentTable.Rows.Count > 0)
          {
            for (int i = 1; i <= dtCurrentTable.Rows.Count; i++)
            {
              TextBox TextBoxName =
              (TextBox)grvStudentDetails.Rows[rowIndex].Cells[1].FindControl("txtCol1");
            
              drCurrentRow = dtCurrentTable.NewRow();
              drCurrentRow["RowNum"] = i + 1;
              dtCurrentTable.Rows[i - 1]["Col1"] = TextBoxName.Text;
            
              rowIndex++;
            }
            dtCurrentTable.Rows.Add(drCurrentRow);
            ViewState["CurrentTable"] = dtCurrentTable;

            grvStudentDetails.DataSource = dtCurrentTable;
            grvStudentDetails.DataBind();
          }
        }

Please help on this.



Robbe Morris replied to prakash ramalingam on 25-Aug-15 11:12 AM
You need to populate the gridview before the Page_Load event.  I think it is the PreInit event or something like that. On postback, dynamically created textboxes are not visible (for lack of a better word) because the control has to be recreated in order for it to be matched up with view state on post back.  Doing it in the Page_Load event is too late for this to occur.

If you name the textboxes with some sort naming convention, you can get the value from the Request form elements collection that gets posted back.