我在GridView EditItemTemplate中有一个DropDownList。 ddl将在运行时填充;每行中的选项可能会有所不同。
GridView正在按需运行。在非编辑模式下,它绑定到数据。在编辑模式下,将呈现EditItemTemplate中指定的控件。
问题:为什么我在这个DropDownList上找不到FindControl ??? 请注意,我可以 FindControl在Calendar控件上,该控件也在EditItemTemplate中。
以下是ASPX& C#代码。
谢谢!
<asp:UpdatePanel ID="UpdatePanelSelections" runat="server">
<ContentTemplate>
<asp:GridView ID="GridViewSelections" runat="server"
...
<Columns>
<asp:TemplateField HeaderText="Options" >
<ItemTemplate>
<asp:Label ID="CurrentOption" runat="server"
Text='<%# Eval("Options.OptionName") %>'>
</asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList ID="ddlOptions" runat="server" >
</asp:DropDownList>
</EditItemTemplate>
<HeaderStyle HorizontalAlign="Left" />
</asp:TemplateField>
<asp:TemplateField HeaderText="Date" >
<ItemTemplate>
<asp:Label ID="CurrentlySelectedDate" runat="server"
Text='<%# Eval("SomeDate") %>'>
</asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:Calendar ID="calNewDate" runat="server" SelectedDate='<%# Bind("SomeDate") %>' VisibleDate='<%# Bind("SomeDate") %>' />
</EditItemTemplate>
<HeaderStyle HorizontalAlign="Left" />
</asp:TemplateField>
...
protected void GridViewSelections_RowEditing(object sender, GridViewEditEventArgs e)
{
// FindControl calNewDate works in GridViewSelections_RowUpdating but not in GridViewSelections_RowEditing
Calendar calNewDate = GridViewSelectionss.Rows[e.NewEditIndex].FindControl("calNewDate") as Calendar;
// FindControl ddlOptions doesn't work anywhere!
DropDownList ddlOptions = GridViewSelections.Rows[e.NewEditIndex].FindControl("ddlOptions") as DropDownList;
// Looking in Cells doesn't work either
DropDownList ddlOptions2 = GridViewSelections.Rows[e.NewEditIndex].Cells[2].FindControl("ddlOptions") as DropDownList;
答案 0 :(得分:1)
解决方案结果是检查DataItem不为null。只检查RowType和Edit标志是不够的。
protected void GridViewSelections_RowDataBound(object sender, GridViewRowEventArgs e)
{
if ((e.Row.RowType == DataControlRowType.DataRow) && (e.Row.RowState.HasFlag(DataControlRowState.Edit) && (e.Row.DataItem != null)))
{
DropDownList ddlOptions = e.Row.FindControl("ddlOptions") as DropDownList;
ddlOptions.Items.Add(new ListItem("aaa", "1"));
ddlOptions.Items.Add(new ListItem("bbb", "2"));
ddlOptions.Items.Add(new ListItem("ccc", "3"));