簡體   English   中英

從 gridview 投射下拉列表

[英]Cast a dropdown list from a gridview

我正在嘗試使用 findcontrol 方法來動態填充下拉列表。 我不斷獲得 null 參考,並嘗試了幾種不同的方法。 這是我嘗試過的一些代碼。

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

您的下拉列表位於項目模板中。 這意味着如果 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();
    }
}
}

由於這是在項目模板中,最簡單的方法是在下拉列表本身上使用處理程序:

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

因為這是 gridview 中的一行,所以這個下拉列表可能有很多實例。 您必須遍歷 gridview 中的每一行

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM