I have a grid sitting on the aspx with the autogenerated columns set to true. I set the datasource to a datatable via code. In the rowdatabound, for the row being edited, I hide the autogenerated textboxes and add my own controls to the cells. This all works ok. When the user clicks the update link, I'm trying to get access to the controls in rowupdating but they are not in the grid anywhere (at least I can't find them), but the textboxes are there.
I assume all the columns are boundfields since they are autogenerated using the datatable. I've seen that you are supposed to use templatefields when wanting to use your own controls but since I did not add the columns manually I was trying to find a work around. I absolutely can't declare columns in the aspx since my data is not simplistic (ie I don't know how many columns need to be generated).
Is this something to do with the viewstate? Is the original setup of the grid in the viewstate but the added controls are not? If so, how do I get my controls in the viewstate for the grid?
Or are my controls being overwritten in an event occurring before rowupdating? I couldn't find the order of events to play around with them. But if I could even read the values of the controls prior to the rowupdating event and save them in a page variable, that would be a place to start.
Any help is greatly appreciated!
*** Code Sample ***
protected void grid1_RowDataBound(Object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
if ((grid1.EditIndex != -1) && (e.Row.RowIndex == grid1.EditIndex))
{
TextBox txbtemp;
//cycle through editable cells, add custom control, set custom control value, remove textbox
for (int icellidx = 0; icellidx < e.Row.Cells.Count; icellidx++)
{
CheckBox mycontrol = new CheckBox();
mycontrol.ID = "chk" + icellidx.ToString();
txbtemp = (TextBox)e.Row.Cells[icellidx].Controls[0];
if (txbtemp.Text == "1")
{
mycontrol.Checked = true;
}
else
{
mycontrol.Checked = false;
}
e.Row.Cells[icellidx].Controls.Add(mycontrol);
e.Row.Cells[icellidx].Controls[0].Visible = false;
}
}
}
}
protected void grid1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
for (int icolidx = 0; icolidx < grid1.Rows[e.RowIndex].Cells.Count; icolidx++)
{
//This next line works which I would expect even though the control is supposedly hidden
//TextBox mytxb = grid1.Rows[e.RowIndex].Cells[icolidx].Controls[0] as TextBox;
//This doesn't work. The cells only contain the textbox control for some reason so I get an out of range error.
CheckBox mychk = grid1.Rows[e.RowIndex].Cells[icolidx].Controls[1] as CheckBox;
}
//Reset the edit index.
grid1.EditIndex = -1;
//rebind grid
grid1.Bind();
}