我正在 asp.net 4.0 中创建一个 web 应用程序
我有一个 Web 表单,其中有一个 ListBox 控件,它在 Page_Load 事件上添加了一个字符串列表。如果我从 ListBox 选择任何列表项并想使用 Listbox.SelectedValue 计算它,它会在 Listbox 上抛出 .Object reference not set to an instance of an object 异常.SelectedValue
通过使用“QuickWatch”(在 Visual Studio 2010 中)我做了一些发现,我可以通过给出索引(比如 Listbox.Items[2])来获得值(value),但如果我得到 null 或 -1我使用 Listbox.SelectedValue 或 Listbox.SelectedIndex
我的问题是为什么 ListBox 控件在选择项目时显示 null 异常错误,因为此列表框不为空?
请您参考如下方法:
我假设您在回发时将 ListBox 绑定(bind)到它的 DataSource,对吗?那么ListBox就会失去他的SelectedValue(连SelectedIndexChanged事件都不会被触发)。
相反,您应该仅在初始加载时进行数据绑定(bind)并检查 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
