2011-02-03 75 views
1

我有一個GridView EditItemTemplate中一個DropDownList。 ddl將在運行時填充;每行中的選項可能會有所不同。的GridView的FindControl找到日曆,但不DROPDOWNLIST

GridView控件正在按期望的。在非編輯模式下,它綁定到數據。在編輯模式下,將呈現EditItemTemplate中指定的控件。

問題:爲什麼我不能FindControl已在這個DropDownList的??? 請注意,我可以的FindControl上的日曆控件,也是在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

在你執行的FindControl碼點什麼,可能是在GridView已經產生的前行? – 2011-02-03 20:17:44

回答

1

溶液變成出要檢查該DataItem的不爲空。只檢查RowType和編輯標誌是不夠的。

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"));