Dropdownlist数据绑定到sqldatasource - 插入的记录在页面刷新之前不会显示

时间:2012-12-04 16:35:14

标签: c# asp.net

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

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的新手,所以可能会遗漏一些明显的东西,任何帮助都会受到赞赏。

0 个答案:

没有答案