繁体   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