我正在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不为空?
答案 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
。
然后您尝试检查事件处理程序中的SelectedValue
或SelectedIndex
,因此它将是-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上重置)