C# ASP.NET-获取数据绑定列表中的下一个值

C# ASP.NET-获取数据绑定列表中的下一个值,c#,asp.net,C#,Asp.net,我正在对字符串列表进行数据绑定,我知道如何使用(string)e.Item.DataItem获取\u ItemDataBound函数使用的DataItem中的当前字符串,但我想知道是否有方法获取该函数将要使用的下一个DataItem 我试图避免将列表设置为全局变量 编辑:以下是我的实际代码示例,因为我目前无法使用实际代码访问PC 中继器.aspx <asp:Repeater ID="rptGeneral" runat="server" OnItemDataBound="rptItemDat

我正在对字符串列表进行数据绑定,我知道如何使用
(string)e.Item.DataItem
获取
\u ItemDataBound
函数使用的DataItem中的当前字符串,但我想知道是否有方法获取该函数将要使用的下一个
DataItem

我试图避免将列表设置为全局变量

编辑:以下是我的实际代码示例,因为我目前无法使用实际代码访问PC

中继器.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;
    }
}
受保护的无效页面加载(对象发送方,事件参数e)
{
中继器重复=常规;
如果(!IsPostBack)
{
//我正在从我的数据库中获取问题
//这里有连接、dataReader和其他sql变量
列表=新列表();
while(dataReader.Read())
{
添加(dataReader[“questionName”].ToString());
}
dataReader.Close()
repeat.DataSource=list;
repeat.DataBind();
}
}
public void rptItemDataBound(对象发送方,RepeaterItemEventArgs e)
{
如果(e.Item.ItemType==ListItemType.Item | | e.Item.ItemType==ListItemType.AlternatingItem)
{
字符串问题=(字符串)e.Item.DataItem;
String nextQuestion;//获取下一个数据项
Label lblQuestion=(Label)e.Item.FindControl(“lblQuestion”);
lblQuestion.Text=问题;
}
}

您无法访问中继器的OnItemDataBound事件中的下一项,因为ItemDataBound事件在从数据源项绑定当前数据项后立即触发。解决这一问题的一些解决方案可能是

  • 将数据源设为类级别变量。在OnItemDataBound事件中,查找数据源中的下一项。(当然你提到了,你不想这么做)

  • 您可以绑定自定义对象列表,而不是绑定字符串列表。对象可以包含两个属性CurrentValue和NextValue。在绑定到repeater之前,您必须建立这个列表并绑定它。然后,您可以在OnItemDataBound事件中访问这两者

  • 另一种方法是,在调用DataBind函数之后,循环遍历repeater项并执行您想要执行的操作,例如为某些控件设置next值等


  • 请把你的代码也贴出来。。!真的有必要吗?这是一个被数据索引的简单字符串列表,但哦,好吧,我将发布一个示例。