2010-08-11 78 views
0

將Visual Web Developer Express 2010與ASP.NET 4.0結合使用。如何在FormView控件的EditItemTemplate中綁定dropdownlist?

我有一個FormView,我想從數據庫中設置一個默認值。我無法將它綁定到數據庫中的值。我FormView控件看起來是這樣的:

<asp:FormView 
ID="frmOrderDetails" 
DataSourceID="sdsFormOrderDetails" 
runat="server" 
DataKeyNames="orderId"> 

<EditItemTemplate> 
    <h3>Edit Order Details</h3> 

    <asp:Label ID="lblStrategy" Text="Strategy:" AssociatedControlID="ddlStrategies" runat="server" /> 
    <asp:DropDownList SelectedValue='<%# Bind("strategyId") %>' 
    ID="ddlStrategies" 
    runat="server" 
    DataTextField="strategy" 
    DataValueField="strategyId" 
    DataSourceID="sdsStrategies" 
    /> 

    <asp:LinkButton 
    id="lnkUpdate" 
    Text="Update Order" 
    CommandName="Update" 
    Runat="server" /> 
    | 
    <asp:LinkButton 
    id="lnkCancel" 
    Text="Cancel" 
    CommandName="Cancel" 
    Runat="server" /> 

</EditItemTemplate> 
</asp:FormView> 

<asp:SqlDataSource ID="sdsFormOrderDetails" runat="server" 
    ConnectionString="<%$ ConnectionStrings:LocalSQLServer %>" 
    ProviderName="<%$ ConnectionStrings:LocalSQLServer.ProviderName %>" 
    SelectCommand="usp_GetOrderDetails" SelectCommandType="StoredProcedure" 
    UpdateCommand="usp_UpdateOrder" UpdateCommandType="StoredProcedure"> 
    <SelectParameters> 
     <asp:ControlParameter Name="orderId" ControlID="grdOrders" PropertyName="SelectedDataKey.Value" /> 
    </SelectParameters> 
    <UpdateParameters> 
     <asp:ControlParameter Name="orderId" ControlID="grdOrders" /> 
    </UpdateParameters> 
</asp:SqlDataSource>      

<asp:SqlDataSource ID="sdsStrategies" runat="server" 
    ConnectionString="<%$ ConnectionStrings:LocalSQLServer %>" 
    ProviderName="<%$ ConnectionStrings:LocalSQLServer.ProviderName %>" 
    SelectCommand="usp_GetStrategiesDropDown"> 
</asp:SqlDataSource>  

的EditItemTemplate裏,當我點擊我的FormView控件的編輯按鈕甚至不加載,但我也不得到一個錯誤信息。

回答

3

需要FormView的數據綁定事件使用像

protected void frmOrderDetails_DataBound(object sender, EventArgs e) 
{ 
    if (frmOrderDetails.CurrentMode == FormViewMode.Edit) 
    { 
     DropDownList ddlStrategies = (DropDownList)frmOrderDetails.FindControl("ddlStrategies"); 
     ddlStrategies.SelectedValue = Your DB Value Goes here; 
    } 
} 
+0

感謝您的答覆。有沒有辦法做到這一點,而不使用代碼? – 2010-08-11 13:08:49

+0

nop,這就是我告訴過你的,否則SelectedValue ='<%#綁定(「strategyId」)%>'這個方法會在綁定同一個源的特定值時起作用 – 2010-08-11 13:17:10

+0

好的,謝謝。我如何獲得DB值?我只想在點擊Edit按鈕之前顯示在ItemTemplate中的當前strategyId。我對ASP.NET很陌生 - 感謝任何幫助。 – 2010-08-11 13:34:47

4

你需要做以下綁定一個DropDownListEditItemTemplate

  1. 添加DropDownList及其DataSourceEditItemTemplate
  2. 設置DropDownList參數:

    DataSourceID="SqlDataSourceDropDownlist" SelectedValue=<%# Bind("ValueToBind") %> 
    DataTextField="ValueToDisplay" DataValueField="ValueToBind" 
    
  3. 設置ListView/FormView DataSource <UdateParameters>: <asp:Parameter Name="RankID" Type="Int32" />

相關問題