I want to have a gridview control in C#.net that it can toggle between 15 and 10 columns depending on a boolean variable.
I have here the method wherein I will pass the DataTable and it renders it properly.
private void RenderDataTableToGrid(DataTable dt)
{
int gvcolCount = gvMandayEntry.Columns.Count;
pjkMain = itfinance_dataload_pjk.GetPjkMainRecord(PjkId);
IsCarryFoward = IsProjectCarryForward(pjkMain);
List<xreffy> FYlist = XrefTable(dt);
for (int cols = 2; cols < dt.Columns.Count; cols++)
{
gvMandayEntry.Columns[cols].HeaderText = dt.Columns[cols].ColumnName;
}
if (!IsCarryFoward)
{
while (dt.Columns.Count != gvMandayEntry.Columns.Count)
{
gvMandayEntry.Columns.RemoveAt(12);
}
}
gvMandayEntry.DataSource = dt;
gvMandayEntry.DataBind();
for (int x = 0; x < dt.Rows.Count; x++)
{
Label Category = (Label)gvMandayEntry.Rows[x].Cells[0].FindControl("Categories");
Label Type = (Label)gvMandayEntry.Rows[x].Cells[1].FindControl("Type");
Category.Text = dt.Rows[x][0].ToString();
Type.Text = dt.Rows[x][1].ToString();
for (int y = 2; y < dt.Columns.Count; y++)
{
TextBox txt = (TextBox)gvMandayEntry.Rows[x].Cells[y].FindControl(FYlist.Find(fy => fy.finyear == dt.Columns[y].ColumnName).control_name);
txt.Text = dt.Rows[x][y].ToString();
}
}
divMandaysEntry.Visible = true;
Session["dtManday"] = dt;
}
When its time for the user to click Save, the logic of the code is to readback the GridView per row using "FindControl".
It works fine if gvMandayEntry.Columns.RemoveAt(12); line from RenderDataTableToGrid was not executed at runtime.
But if its executed, the FindControl returns a Null.
for (int x = 0; x < gvMandayEntry.Rows.Count; x++)
{
Label Category = (Label)gvMandayEntry.Rows[x].Cells[0].FindControl("Categories");
Label Type = (Label)gvMandayEntry.Rows[x].Cells[1].FindControl("Type");
int manday_category_id = MdCatList.Find(mdcat => mdcat.name == Category.Text).id;
int pex_id = ExpenseType.Find(pex => pex.name == Type.Text).id;
int manday_id = MdList.Find(mditm => mditm.mandays_categories_id == manday_category_id && mditm.pex_id == pex_id).id;
}
What I have tried:
If the GridView is not altered at code runtime, the FindControl works.