asp.net – Repeater中DropDownList的SelectedValue

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

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

这就是我尝试过的:

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

填充转发器的代码

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

用于填充下拉列表的代码

  1. protected void educationPopup_repeater_ItemDataBound(object sender,RepeaterItemEventArgs e)
  2. {
  3. DropDownList degree_dropdown = e.Item.FindControl("degree_dropdown") as DropDownList;
  4. if (degree_dropdown != null)
  5. {
  6. degree_dropdown.DataSource = degrees; //a datatable
  7. degree_dropdown.DataTextField = "degree";
  8. degree_dropdown.DataValueField = "code";
  9. degree_dropdown.DataBind();
  10. }
  11. }

解决方法

你快到了.您只需要将DataItem转换为DataRowView,并将其分配给DropDownList,如下所示 –
  1. protected void myRepeater_ItemDataBound(object sender,RepeaterItemEventArgs e)
  2. {
  3. if (e.Item.ItemType == ListItemType.Item ||
  4. e.Item.ItemType == ListItemType.AlternatingItem)
  5. {
  6. var degree_dropdown = e.Item.FindControl("degree_dropdown") as DropDownList;
  7. string degreeCode = (string) ((DataRowView) e.Item.DataItem)["degreeCode"];
  8.  
  9. if (degree_dropdown != null)
  10. {
  11. degree_dropdown.DataSource = degrees; //a datatable
  12. degree_dropdown.DataTextField = "degree";
  13. degree_dropdown.DataValueField = "code";
  14. degree_dropdown.DataBind();
  15.  
  16. if (degree_dropdown.Items.FindByValue(degreeCode) != null)
  17. degree_dropdown.SelectedValue = degreeCode;
  18. }
  19. }
  20. }

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