1

我有一个绑定到 sqldatasource 的供应商下拉列表。可以通过表单视图添加供应商,但是一旦单击插入按钮,记录就会插入到数据库中,但不会显示在下拉列表中。

sqldatasource的代码如下:

<asp:SqlDataSource runat="server" ID="sqlAddSupplier" 
 ConnectionString="<%$ ConnectionStrings:cctConnectionString%>" 
 ProviderName="<%$ ConnectionStrings:cctConnectionString.ProviderName%>" 
 InsertCommand="suppliers_Insert" InsertCommandType="StoredProcedure">
    <InsertParameters>
        <asp:SessionParameter SessionField="siteId" DefaultValue="0" Name="p_siteId" Type="Int64" />
        <asp:Parameter Name="code" Type="String" />
        <asp:Parameter Name="name" Type="String" />
    </InsertParameters>
</asp:SqlDataSource>

下拉列表和表单视图添加供应商的代码如下:

<asp:DropDownList ID="lstSuppliers" runat="server" CssClass="dropDownList" 
 AppendDataBoundItems="true" DataSourceID="sqlSuppliers" DataTextField="name" 
 DataValueField="id" SelectedValue='<%# Bind("supplierId") %>' >
    <asp:ListItem Text="" Value="0"></asp:ListItem>
</asp:DropDownList>

<asp:Panel runat="server" ID="pnlAddSupplier" CssClass="groupBoxPageWidth">

    <asp:FormView ID="fvAddSupplier" runat="server" DataSourceID="sqlAddSupplier" 
     OnItemInserted="fvAddSupplier_ItemInserted">

        <InsertItemTemplate>
            <b>Code:*</b>
            <asp:TextBox ID="txtCode" runat="server" Text='<%# Bind("code") %>' CssClass="textbox"></asp:TextBox>
            <b>Name *:</b>
            <asp:TextBox ID="txtName" runat="server" Text='<%# Bind("name") %>' CssClass="textbox"></asp:TextBox>
            <br /><br />
            <asp:Button runat="server" ID="cmdInsertSupplier" Text="Save" CssClass="buttonControlGreen" CommandName="Insert" OnClientClick="needToConfirm=false;" />
            <asp:Button runat="server" ID="cmdCancelSupplier" Text="Cancel" CssClass="buttonControl" CommandName="Cancel" OnClientClick="needToConfirm=false;" />
        </InsertItemTemplate>
    </asp:FormView>
</asp:Panel>

ItemInserted 事件的代码如下:

protected void fvAddSupplier_ItemInserted(object sender, FormViewInsertedEventArgs e)
{
    fvAddSupplier_CommandCompletion(e.Exception, e.KeepInInsertMode, "Inserted");
}

protected void fvAddSupplier_CommandCompletion(Exception sqlException, bool keepInMode, String procedureExecuted)
{
    Panel pnlAddSupplier = (Panel)fvProduct.FindControl("pnlAddSupplier");
    Label lblAddSupplierError = (Label)pnlAddSupplier.FindControl("lblAddSupplierError");

    if (sqlException != null)
    {
        keepInMode = true;
    }
}

如果我调用 Response.Redirect 来刷新整个页面,它将刷新下拉列表,但我认为这应该在 PostBack 发生吗?插入记录后,我还尝试在下拉列表上调用 DataBind,但随后看到以下错误:

Databinding methods such as Eval(), XPath(), and Bind() can only be used in the context of a databound control.

我对 asp.net 比较陌生,所以可能会遗漏一些明显的东西,任何帮助将不胜感激。

4

0 回答 0