You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ASP.NET中Asp:ListBox选中项文本获取失败,报空引用异常

解决Asp:ListBox获取选中项文本时的NullReferenceException问题

常见原因及对应修复方案

1. 回发时重复绑定数据导致选中状态丢失

如果ListBox的填充逻辑写在Page_Load中但未判断IsPostBack,每次回发都会重新清空并绑定数据,导致选中项状态丢失,SelectedItem变为null。

修复代码:

protected void Page_Load(object sender, EventArgs e)
{
    // 仅首次加载时填充数据,回发时跳过
    if (!IsPostBack)
    {
        FillListBoxData();
    }
}

private void FillListBoxData()
{
    // 你的数据填充逻辑示例
    lbModules.Items.Add(new ListItem("模块1", "MOD001"));
    lbModules.Items.Add(new ListItem("模块2", "MOD002"));
}

2. 未判断选中项是否存在就直接访问

若触发事件时ListBox无选中项,直接访问SelectedItem会抛出空引用异常,需先做非空判断。

修复事件处理代码:

protected void lbModules_SelectedIndexChanged(object sender, EventArgs e)
{
    if (lbModules.SelectedItem != null)
    {
        string code = lbModules.SelectedItem.Text;        
        int week = 1;
        UpdateTextBox(week, code);
    }
    else
    {
        // 可添加无选中项时的处理逻辑,比如提示用户
    }
}

3. 通过sender获取控件避免ID匹配问题

若页面使用母版页或用户控件,控件实际ID可能被ASP.NET自动修改,通过事件参数中的sender直接获取ListBox更可靠。

优化后的事件处理代码:

protected void lbModules_SelectedIndexChanged(object sender, EventArgs e)
{
    ListBox targetListBox = sender as ListBox;
    if (targetListBox != null && targetListBox.SelectedItem != null)
    {
        string code = targetListBox.SelectedItem.Text;        
        int week = 1;
        UpdateTextBox(week, code);
    }
}

4. 确认ViewState处于启用状态

ASP.NET依赖ViewState保存控件的选中状态,若页面或ListBox的EnableViewState设为false,回发时会丢失选中状态。

检查并修正控件设置:

<asp:ListBox ID="lbModules" runat="server" AutoPostBack="true" 
             OnSelectedIndexChanged="lbModules_SelectedIndexChanged" 
             EnableViewState="true"></asp:ListBox>

页面级ViewState设置(确保未禁用):

<%@ Page Language="C#" AutoEventWireup="true" 
         CodeBehind="YourPage.aspx.cs" Inherits="YourNamespace.YourPage"
         EnableViewState="true" %>

内容的提问来源于stack exchange,提问作者omo_codes

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 13:41:01