簡體   English   中英

ASP如何在詳細信息視圖中綁定下拉列表的選定值

[英]ASP How to bind the selected value of a dropdownlist in detailsview

我在detailsview控件中有一個下拉列表。 數據源是一個帶有dayofthemonth列的SQL表。

<asp:TemplateField HeaderText="Day of Month: ">
            <EditItemTemplate>
                <asp:DropDownList ID="ddlDoM" runat="server" > 
                </asp:DropDownList>
            </EditItemTemplate>
            <InsertItemTemplate>
                <asp:TextBox ID="TextBox6" runat="server" Text='<%# Bind("dayofthemonth") %>'></asp:TextBox>
            </InsertItemTemplate>
            <ItemTemplate>
                <asp:Label ID="Label7" runat="server" Text='<%# Bind("dayofthemonth") %>'></asp:Label>
            </ItemTemplate>
            <HeaderStyle Font-Bold="True" />
</asp:TemplateField>

在DataBound事件中,我使用數字1-31填充了下拉列表。

protected void DataView1_DataBound(object sender, EventArgs e)
{
    DropDownList ddlDoM = (DropDownList)Page.FindControl("ctl00$formPlaceHolder$DataView1$ddlDoM");
    if (DataView1.CurrentMode == DetailsViewMode.Edit)
    {
        for (int i = 1; i < 32; i++)
        {
            ListItem item = ListItem.FromString(i.ToString());
            ddlDoM.Items.Add(item);
        }
    }
        DataRowView drv = DataView1.DataItem as DataRowView;
        ddlDoM.SelectedIndex = ddlDoM.Items.IndexOf(ddlDoM.Items.FindByValue(drv["dayofthemonth"].ToString()));
    }
}

在這里的最后一行中,我將下拉列表的選定值設置為當前數據源值。

ddlDoM.SelectedIndex = ddlDoM.Items.IndexOf(ddlDoM.Items.FindByValue(drv["dayofthemonth"].ToString()));

更改后,如何綁定下拉列表以更新數據源中的值? 我嘗試將選定的value屬性設置為<%# Bind("dayofthemonth") %> ,但是我收到OutOfRangeException。 我假設在切換到“編輯模式”時尚未填充列表。

有什么想法嗎? 讓我知道您是否需要更多代碼。

嘗試將ControlParameter添加到數據源中的UpdateParameters ,並確保在適當的情況下將下拉列表設置為AutoPostBack。 您可能還考慮在更早的事件(例如Page_Init )中填充下拉列表,並保留其默認值,直到您已經擁有DataBound事件為止。

<asp:SqlDataSource ... UpdateCommand=""....>
    <UpdateParameters>
        <asp:ControlParameter ControlID="ddlDoM" Name="dayofthemonth" PropertyName="SelectedValue" Type="Int32" />
    </UpdateParameters>
</asp:SqlDataSource>

另外,如果仍然引起問題,一個安全(但冗長)的選擇是將ListItems直接添加到dropdownlist控件中,因為它們似乎是靜態值:

<asp:DropDownList ID="ddlDoM" runat="server" AutoPostBack="true">
    <asp:ListItem Value="1" />
    <asp:ListItem Value="2" />
    <asp:ListItem Value="3" />
    etc...
</asp:DropDownList>

暫無
暫無

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

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