asp.net – Repeater中DropDownList的SelectedValue

前端之家收集整理的这篇文章主要介绍了asp.net – Repeater中DropDownList的SelectedValue前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
如何在转发器中设置dropDownList的选定项?

转发器绑定到repeaterData DataTable,dropDownList绑定到后面的代码中的dropDownList DataTable.我需要将DropDownList的SelectedValue属性设置为repeaterData表中的字段值.

这就是我尝试过的:

<asp:Repeater runat="server" ID="myRepeater>
<ItemTemplate>
    <asp:DropDownList runat="server" CssClass="fullSelect" ID="degree_dropdown"
            AppendDataBoundItems="true" 
            selectedValue='<%#DataBinder.Eval(Container.DataItem,"degreeCode")%>'>
                  <asp:ListItem Text="Select Degree" />
     </asp:DropDownList>
</ItemTemplate>
</asp:Repeater>

填充转发器的代码

myRepeater.DataSource = myRepeaterData; //myRepeaterData is a datatable
myRepeater.DataBind();

用于填充下拉列表的代码

protected void educationPopup_repeater_ItemDataBound(object sender,RepeaterItemEventArgs e)
        {
            DropDownList degree_dropdown = e.Item.FindControl("degree_dropdown") as DropDownList;
            if (degree_dropdown != null)
            {
                degree_dropdown.DataSource = degrees; //a datatable
                degree_dropdown.DataTextField = "degree";
                degree_dropdown.DataValueField = "code";
                degree_dropdown.DataBind();
            }
}

解决方法

你快到了.您只需要将DataItem转换为DataRowView,并将其分配给DropDownList,如下所示 –
protected void myRepeater_ItemDataBound(object sender,RepeaterItemEventArgs e)
{
    if (e.Item.ItemType == ListItemType.Item || 
       e.Item.ItemType == ListItemType.AlternatingItem)
    {
        var degree_dropdown = e.Item.FindControl("degree_dropdown") as DropDownList;
        string degreeCode = (string) ((DataRowView) e.Item.DataItem)["degreeCode"];

        if (degree_dropdown != null)
        {
            degree_dropdown.DataSource = degrees; //a datatable
            degree_dropdown.DataTextField = "degree";
            degree_dropdown.DataValueField = "code";
            degree_dropdown.DataBind();

            if (degree_dropdown.Items.FindByValue(degreeCode) != null)
                degree_dropdown.SelectedValue = degreeCode;
        }
    }
}

猜你在找的asp.Net相关文章