列表框控件在选择项目时抛出null异常

时间:2012-06-12 19:37:55

标签: c# asp.net visual-studio-2010 listbox postback

我正在asp.net 4.0中创建一个Web应用程序

我有一个网页表单,其中有一个ListBox控件,它在Page_Load事件上添加一个字符串列表。如果我从ListBox中选择任何列表项并希望使用Listbox.SelectedValue进行计算,则会在Object reference not set to an instance of an object上抛出Listbox.SelectedValue例外。

通过使用“QuickWatch”(在Visual Studio 2010中),我做了一些调查结果,我可以通过给出索引来获得价值(比如说Listbox.Items[2])但是如果我使用Listbox.SelectedValue,我得到null或-1 Listbox.SelectedIndex

我的问题是,为什么ListBox控件在选择项目时显示空异常错误,因为此Listbox不为空?

2 个答案:

答案 0 :(得分:3)

我假设您将回复ListBox绑定到DataSource,我是对的吗?然后ListBox将丢失SelectedValue(即使SelectedIndexChanged事件也不会被触发)。

相反,您应该仅在初始加载时进行数据绑定并检查IsPostback属性:

C#

protected void Page_Load(object sender, EventArgs e)
{
    if(!Page.IsPostBack) 
    {
        // pseudo code: 
        ListBox1.DatSource = GetYourDataSource();
        ListBox1.DataBind();
    }
}

VB.NET

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    If Not IsPostBack Then
        ' pseudo code: '
        ListBox1.DatSource = GetYourDataSource()
        ListBox1.DataBind()
    End If
End Sub

答案 1 :(得分:1)

根据我对情况的理解,您在Listbox.SelectedValue重新填充Page_Load后检查ListBox,以便重置SelectedIndex,即-1。 然后您尝试检查事件处理程序中的SelectedValueSelectedIndex,因此它将是-1

<强>建议:
 1.首次在Page_Load上填充ListBox。

protected void Page_Load(object sender, EventArgs e)
{
 if(!IsPostBack) 
  {
    //Bind it once on first time page load
    MyListbox.DatSource = SqlDataSource1();
    MyListbox.DataBind();
  }
}


 2.然后在处理事件后重新填充MyListBox  3.您应该使用protected方法填充ListBox

注意:“null exception”是由于没有选择任何项目,即-1(实际上是在Page_Load上重置)