2013-06-27 28 views
0

事件没有触发我在InsertItemTemplate中有一个LinkBut​​ton,当点击时,应该在InsertItemTemplate中显示一个隐藏的DropDownList。但是,它似乎并没有工作,但它会说,单击LinkBut​​ton时在Formview外改变标签的文本。事件正在触发,但在InsertItemTemplate中使DropDownList可见的部分没有任何作用。代码如下:事件没有按预期控制在formview asp.net

的.aspx:

<asp:FormView ID="formViewNewRecord" runat="server"> 
     <InsertItemTemplate> 
      <asp:DropDownList ID="ddlAddSelection2" runat="server" DataSourceID="dSource1" DataTextField="Users" DataValueField="Users" AppendDataBoundItems="true" Visible="false"> 
       <asp:ListItem></asp:ListItem> 
      </asp:DropDownList> 
      <asp:LinkButton runat="server" ID="lbAddAnother" OnClick="lbAddAnother_Click">+Add Another</asp:LinkButton> 
     </InsertItemTemplate> 
     </asp:FormView> 

    <asp:Label ID="Label2" runat="server" Text="Label"></asp:Label> 

C#:

protected void lbAddAnother_Click(object sender, EventArgs e) 
{ 
    DropDownList addSelection2 = (DropDownList)formViewNewItem.Row.Cells[0].FindControl("ddlAddSelection2"); 
    addSelection2.Visible = true; 
    Label2.Text = addSelection2.ID; 
} 

回答

0

你的下拉控件是不是你的FormView控件的直接子。因此,由于FindControl调用不是递归的,您必须在窗体视图的子控件的正确位置搜索控件。 See this for the details但在较高的水平,你需要沿着线的东西:

DropDownList ctrl = (DropDownList)FormView1.Row.Cells[0].FindControl("ddlAddSelection2"); 

之后,你应该检查它的空安全的措施。

+0

嗨@Tombala我更新了我的代码。我添加了.Row.Cells [0],但它仍然不起作用。我还添加了标签来显示控件的ID。单击LinkBut​​ton时,标签显示“ddlAddSelection2”。无论我保留还是忽略.Row.Cell [0]一块,但仍然没有发生控制,我试图使其可见。 –

+0

我会做的是在链接的讨论中还提出了什么建议:在该行上中断并使用监视窗口或立即窗口来确定您需要的控件位于控件树中的位置。然后,您可以使用正确的路径来控制。 – Tombala

+0

如果我正确地理解了你,你似乎暗示FindControl只是找不到控件,因为FindControl()中正在使用的路径(控件名称)。对我来说这没有意义,因为它显示控件的ID,它会在我放在formview之外的标签中找到。如果我把一个不正确的控件名称,例如'.FindControl('ddlAddSelection23')',它会给我一个'对象引用未设置为对象的实例'。错误。我在想,我遇到的这个问题与页面生命周期有关? –