ASP ListBox返回-1

时间:2011-09-21 16:03:59

标签: c# .net asp.net

我有一个ASP listBox。每当我在列表中选择一个新项时,都会调用以下函数:

 protected void prevSubList_SelectedIndexChanged(object sender, EventArgs e)
 {
        // Get the currently selected item in the ListBox index
        int index = prevSubList.SelectedIndex;
        if (index < 0)
        {
            return;
        }
        //get the nominee for that index
        Nominees currNominee = nominees[index];
        populateFields(currNominee);
    }


<td ID="previousSubmissions" align="left">
    <asp:ListBox ID="prevSubList" runat="server" Height="16px" Width="263px" 
     Rows="1" onselectedindexchanged="prevSubList_SelectedIndexChanged" 
     AutoPostBack="True">
     </asp:ListBox>
</td>

问题是int index = prevSubList.SelectedIndex;始终评估为-1。我的列表中有三个项目,比如我选择第二个项目,我希望该值为1,但它是-1。有什么想法吗?

1 个答案:

答案 0 :(得分:2)

您可能绑定了Page_Load上的数据,而您没有检查IsPostBack是否为真。

示例:

if (!IsPostBack)
{
      Dictionary<string, string> data = new Dictionary<string, string>();

      for (int i = 0; i < 10; i++)
       data.Add("i" + i, "i" + i);    

       prevSubList.DataSource = data;
       prevSubList.DataBind();
}