I have the following code in an ASP.NET datagrid:
<asp:TemplateField HeaderText="" Visible="True" >
<ItemTemplate>
<%--<asp:TextBox ID="txtAnswer" Text='<%# Bind("Answer") %>' runat="server"
TextMode="MultiLine" Height="76px" MaxLength="2000" Width="377px" >
</asp:TextBox>--%>
<asp:HiddenField ID="hfQuestionID" Value='<%# Bind("QuestionID") %>' runat="server" />
<asp:HiddenField ID="hfAnswerID" Value='<%# Bind("AnswerID") %>' runat="server" />
<asp:HiddenField ID="hfAnswer" Value='<%# Bind("Answer") %>' runat="server" />
<asp:PlaceHolder ID="ph1" runat="server" />
<%--<%# GetAnswerControl(DataBinder.Eval(Container.DataItem,"QuestionID").ToString(),
DataBinder.Eval(Container.DataItem,"Answer").ToString()) %>--%>
</ItemTemplate>
<EditItemTemplate>
<asp:HiddenField ID="hfQuestionID" Value='<%# Bind("QuestionID") %>' runat="server" />
<asp:HiddenField ID="hfAnswerID" Value='<%# Bind("AnswerID") %>' runat="server" />
<asp:HiddenField ID="hfAnswer" Value='<%# Bind("Answer") %>' runat="server" />
<asp:PlaceHolder ID="ph1" runat="server" />
<%--<asp:TextBox ID="txtAnswer" Text='<%# Bind("Answer") %>' runat="server"
TextMode="MultiLine" Height="76px" MaxLength="2000" Width="377px" ></asp:TextBox>--%>
</EditItemTemplate>
</asp:TemplateField>
The placeholder is dynamically populated with either a textbox or a dropdownlist depending on the type of answer the user needs to give. The code to render the initial answer fields (textbox or dropdown) works fine.
However, when I fire my button click event, the controls property of the placeholder is always empty. Why is this happening? I've been wracking my brain for days over this and it doesn't make any sense to me.
A snippet where I'm trying to access the datagrid's dynamically added controls follows...what am I doing wrong?
foreach (GridViewRow r in gridUserSupplierTypeQuestionsAndAnswers.Rows)
//if (IsRowModified(r))
//{
// gridUserSupplierTypeQuestionsAndAnswers.UpdateRow(r.RowIndex, false);
//}
{
PlaceHolder ph =(PlaceHolder) r.FindControl("ph1");
Control c = ph.FindControl("Answer");
string answer = string.Empty;
if(c.GetType() == typeof(TextBox))
{
TextBox tb = (TextBox) c;
answer = tb.Text;
}
else if (c.GetType() == typeof(DropDownList))
{
DropDownList dl = (DropDownList)c;
answer = dl.SelectedValue;
}