使用上一个和下一个按钮在下拉列表中导航项目

Use previous and next buttons to navigate items in a drop down list

我正在尝试在页面上创建上一个和下一个按钮来浏览下拉列表中的项目。单击下一步应该 select DDL 中的下一个项目,单击上一个应该转到上一个项目。 这是我为下一个按钮尝试过的东西,但它只是把我带到最后一行。

protected void btnNext_Click(object sender, EventArgs e)
{
    int currentSelection = DDL.SelectedIndex;
    for (int i = currentSelection; i < DDL.Items.Count; i++)
    {
        string nextSelection = (DDL.Items[i].ToString());           
        DDL.SelectedValue = nextSelection;
    }
}

您将循环遍历列表中的所有项目,直到到达最后一个项目,然后单独选择每个项目,直到循环退出。在该循环内放置一个断点并进行调试以了解我的意思。

这里根本不需要任何循环。你想要的只是:

int nextIndex = DDL.SelectedIndex + 1;

if (nextIndex + 1 >= DDL.Items.Count)
    return; // We're on the last item, do nothing (or whatever you like)

DDL.SelectedValue = DDL.Items[nextIndex].ToString();

您可以轻松地通过其索引更改所选值,因此您不需要通过其值更改它。

int i = ddl.SelectedIndex;

if (i+1!=ddl.Items.Count)
{
    ddl.SelectedIndex = i + 1;
}
else
{
    ddl.SelectedIndex = i;
}

正如您在评论中所说,如果当前索引是最后一个,它不会更改索引。