2011-08-15 177 views
0

我正在尝试使用findcontrol方法来动态填充下拉列表。我不断收到一个空引用,并尝试了几种不同的方式。这里是我试过的一些代码。从gridview投下拉列表

<ItemTemplate> 
    <asp:DropDownList runat="server" 
      ID="ddlCalculateGrid" 
      Style="border: none; border-width: 0px; width: 90%" 
      OnSelectedIndexChanged="ddlCalculateGrid_OnSelectedIndexChanged" 
      AutoPostBack="true"> 
    </asp:DropDownList> 
    <asp:HiddenField runat="server" 
      ID="hdnCalculate" 
      Value='<%# Eval("Calculate") %>' /> 
</ItemTemplate> 

这里是后端代码。

 DropDownList tempddl; 
     tempddl = (DropDownList)grvbillDetail.FindControl("ddlCalculateGrid"); 
     tempddl.DataSource = rcta.GetDataByTrueValue(); 
     tempddl.DataBind(); 
+0

你有任何其他控件的顶部的GridView。我的意思是这是一个嵌套的gridview? – Vinay

+1

这个后端代码到底在哪里?在一些GridView事件处理程序?另请注意,GridView模板中定义的控件不直接属于gridview;它们属于'GridViewRow'。所以你可能想通过'grvbillDetail.Rows'循环,然后在每一行上尝试一个'FindControl()'。 –

+0

你确认FindControl()返回了什么吗?什么是rcta,你确定它不是null? – cdkMoose

回答

2

您的下拉列表位于项目模板中。这意味着如果gridview绑定到没有行的源,那么您的gridview可能包含多个下拉列表(每行一个)或根本没有下拉列表。

如果你想要为每一行绑定每个下拉菜单,你可以在GridViewRowDatabound事件中这样做。

protected void Page_Load(object sender, EventArgs e) 
{ 
    grvbillDetail.RowDataBound += grvbillDetail_RowDataBound; 
} 

void grvbillDetail_RowDataBound(object sender, GridViewRowEventArgs e) 
{ 
    if (e.Row.RowType != DataControlRowType.DataRow) 
     return; 
    var ddl = e.Row.FindControl("ddlCalculateGrid") as DropDownList; 
    if (ddl != null) 
    { 
     ddl.DataSource = rcta.GetDataByTrueValue(); 
     ddl.DataBind(); 
    } 
} 
} 
1

由于这是一个项目模板,最简单的事情是使用一个处理器上的下拉列表本身:

<asp:DropDownList runat="server" ID="ddlCalculateGrid" 
    Style="border: none; border-width: 0px;width: 90%" 
    OnSelectedIndexChanged="ddlCalculateGrid_OnSelectedIndexChanged" 
    OnLoad="ddlCalculateGrid_OnLoad" 
    AutoPostBack="true"> 

然后在ddlCalculateGrid_OnLoad方法:

DropDownList tempddl = (DropDownList)sender; 
1

由于这是gridview中的一行,因此这个dropdownlist可能会有很多实例。你必须遍历gridview中的每一行

foreach (GridViewRow tt in GridView1.Rows) 
     { 
      if (tt.RowType == DataControlRowType.DataRow) 
      {      
       tt.FindControl("ddlCalculateGrid"); 
      } 
     }