ASP.获取绑定列表中的下一个值
本文关键字:下一个 列表 获取 绑定 ASP | 更新日期: 2023-09-27 18:10:41
我正在绑定字符串列表,我知道如何使用(String)e.Item.DataItem
获得_ItemDataBound
函数使用的DataItem中的当前字符串,但我想知道是否有方法获得该函数将要使用的下一个DataItem
。
我试图避免将List设置为全局变量。
编辑:这是我的实际代码的一个例子,因为我目前无法访问实际代码的PC。
Repeater.aspx
<asp:Repeater ID="rptGeneral" runat="server" OnItemDataBound="rptItemDataBound">
<ItemTemplate>
<asp:Label ID="lblQuestion" runat="server"></asp:Label>
</ItemTemplate>
</asp:Repeater>
Repeater.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
Repeater repeat = rptGeneral;
if (!IsPostBack)
{
//I'm obtaining the questions from my database
//connection, dataReader and other sql variables are here
List<String> list = new List<String>();
while(dataReader.Read())
{
list.Add(dataReader["questionName"].ToString());
}
dataReader.Close()
repeat.DataSource = list;
repeat.DataBind();
}
}
public void rptItemDataBound(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
String question = (String)e.Item.DataItem;
String nextQuestion; //get the next DataItem
Label lblQuestion = (Label)e.Item.FindControl("lblQuestion");
lblQuestion.Text = question;
}
}
您不能访问重复器的OnItemDataBound事件中的下一项,因为ItemDataBound事件仅在从数据源项绑定当前数据项之后触发。对于这个问题的一些解决方案可以是
-
将数据源作为类级别变量。在OnItemDataBound事件中查找数据源中的下一项。(当然你提到了,你不想这样做)
-
不绑定字符串列表,可以绑定自定义对象列表。该对象可以包含两个属性CurrentValue和NextValue。在绑定到repeater之前,你必须建立这个列表并绑定它。然后你可以在OnItemDataBound事件中访问它们。
-
另一种方法是,在调用DataBind函数后,循环遍历重复器项并执行您想要执行的操作,例如为某些控件设置next值等。