Dropdownlist索引从-1开始

时间:2014-07-02 07:07:08

标签: c# asp.net .net drop-down-menu

我有一个下拉列表,无法弄清楚索引的工作方式。我在列表中有两个项目,默认情况下在加载页面时选择item1。加载页面时,选择item1并且索引为-1。如果我将项目更改为item2,则索引将变为1.如果我更改回item1,则会转到0.

起始指数是否始终为-1?如果是这样,是否可以更改它以使起始索引为0?这个设计的原因是什么?

Clairification:

protected void Page_Load(object sender, EventArgs e)
{
    dropDownList1.SelectedIndex = 0;     //I try to set the index to 0
    myVariable = dropDownList1.SelectedIndex; //Debugger says SelectedIndex is -1
}

2 个答案:

答案 0 :(得分:0)

我现在只是做了一个解决方法。

protected void Page_Load(object sender, EventArgs e)
{
    if(dropDownList1.SelectedIndex == 1)
    {
        myVariable = 1;
    }
    else
    {
        myVariable = dropDownList1.SelectedIndex;
    }
}

这有效,但我仍觉得它很难看。如果有人有更好的解决方案,请告诉我。 =)

答案 1 :(得分:-1)

除了我的评论,-1作为索引选择含义并且这是默认值,当您加载页面时,您的下拉列表中不会显示任何项目。但您可以添加yourList.SelectedIndex = 0;