c#
  • .net
  • asp.net
  • 2011-09-22 75 views 0 likes 
    0

    我在GridView中有一個項目模板,我想爲每一行創建一個下拉列表並將其綁定到從數據庫檢索的值..但我不知道如何這樣做..這是我迄今爲止..但不知道從哪裏把代碼來填充下拉每排下來..在itemtemplate中添加一個下拉列表並動態填充值

    <ItemTemplate> 
        <asp:DropDownList runat="server" ID="ddlMyQuantity" SelectedValue='<%# 
         (DataBinder.Eval(Container.DataItem,"Quantity")) %>'> 
        </asp:DropDownList> 
        </ItemTemplate> 
    

    並在後面的代碼,不知道如何或在哪裏放這使它創建在每一行..

    public void BindMyQuantity() 
        { 
         for (int i = 1; i < 15; i++) 
         { 
          ddlMyQuantity.Items.Add(i.ToString()); 
         } 
        } 
    

    另外我不知道如果我能做到這一點,但代碼是不合作mplaining ..在ASP聲明添加的SelectedValue

    回答

    0

    您可以使用OnRowDataBound動態綁定您的下拉菜單:

    protected void GridView_RowDataBound(Object sender, GridViewRowEventArgs e) 
    { 
        if(e.Row.RowType == DataControlRowType.DataRow) 
        { 
        var dropdownList = (DropDownList)e.Row.FindControl("ddlMyQuantity"); 
        for (int i = 1; i < 15; i++) 
        { 
         dropdownList.Items.Add(i.ToString()); 
        } 
        dropdownList.SelectedValue = 
          Convert.ToString(DataBinder.Eval(e.Row.DataItem, "Quantity")); 
        } 
    } 
    

    添加綁定:

    <asp:GridView ... OnRowDataBound="GridView_RowDataBound"> 
        ... 
    </asp:GridView> 
    
    +0

    很好,最後我在最後添加的問題怎麼樣?非常感謝 – edcod81

    +0

    是的,這是完全有效的,但如果DropDownList沒有爲SelectedValue綁定綁定時,您可能會遇到問題。在OnRowDataBound事件中執行此操作可能更安全。 – TheCodeKing

    +0

    問題我試圖綁定它..但它仍然回來空白..任何想法爲什麼? – edcod81

    0

    按我的知識,最好的辦法是在Grid的「RowDataBound」事件中編寫此代碼。請參閱以下示例代碼。

    protected void GridView_RowDataBound(..) 
        { 
         if (e.Row.RowType.Equals(DataControlRowType.DataRow)) 
         { 
          DropDownList ddl = e.Row.FindControl("ddlMyQuantity") as DropDownList; 
    
          if (ddl != null) 
          { 
           for (int i = 1; i < 15; i++) 
           { 
            ddl.Items.Add(i.ToString()); 
           } 
          } 
         } 
        } 
    

    在aspx頁面,提供這種

    <ItemTemplate>   
         <asp:DropDownList runat="server" ID="ddlMyQuantity"></asp:DropDownList> 
        </ItemTemplate> 
    

    希望這有助於!

    相關問題