[英]Selected value of dropdownlist in repeater control - with predefined items
我在具有預定義項目的ASP.NET頁面中的轉發器控件內部有一個DropDownList。 在將數據綁定到轉發器控件之后,我該如何設置它的選定值?
例如,我有這個代碼:
<asp:DropDownList ID="cboType" runat="server">
<asp:ListItem Text="Communication" Value="Communcation" />
<asp:ListItem Text="Interpersonal" Value="Interpersonal" />
</asp:DropDownList>
因為DropDownList控件沒有SelectedValue前端屬性,所以我無法在控件級別設置它。 相反,您必須使用列表項的selected屬性。 什么是理想的是:
<asp:DropDownList ID="cboType" runat="server" SelectedValue='<%# Eval("Type_Of_Behavior") %>'>
<asp:ListItem Text="Communication" Value="Communcation" />
<asp:ListItem Text="Interpersonal" Value="Interpersonal" />
</asp:DropDownList>
不幸的是,這不起作用,任何想法?
使用Pankaj Garg的代碼(謝謝!)我設法寫出了選擇正確值的方法。 我無法將其標記為答案,因為答案是選擇靜態值,而不是來自數據庫的靜態值。 這是功能:
protected void rpt_ItemDataBound(object sender, RepeaterItemEventArgs e)
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
DropDownList cbo = (DropDownList)e.Item.FindControl("cboType");
Behaviour b = (Behaviour)e.Item.DataItem;
for (int i = 0; i < cbo.Items.Count; i++)
{
if (b.Type_of_Behaviour == cbo.Items[i].Value)
cbo.Items[i].Selected = true;
else
cbo.Items[i].Selected = false;
}
}
}
感謝所有幫助過的人。
在運行時您可以像下面一樣使用Repeater的
OnItemDataBound
。
示例HTML
<asp:Repeater ID="rpt" runat="server" OnItemDataBound="YourhandlerName" >
</asp:Repeater>
OnItemDataBound
事件處理程序的示例代碼 protected void rpt_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
DropDownList DropDownID = (DropDownList)e.Item.FindControl("DropDownID");
int ItemNo = ((YourClassName)e.Item.DataItem).Yourproperty;
DropDownID.Items[ItemNo].Selected = true;
}
}
你要找的屬性是的一部分ListItem
本身,而不是多種類型的列表-也就是說,你可以指定一個項目是通過設置選擇Selected
在該項目上:
<asp:ListItem Text="Interpersonal" Value="Interpersonal" Selected="True"/>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.