You need to enable JavaScript to run this app. WinForm DataGridView按搜索内容选行快速输入触发NullReferenceException异常
优惠活动
大模型
产品
解决方案
定价
更多

WinForm DataGridView按搜索内容选行快速输入触发NullReferenceException异常

异常触发原因
  • 最直接的空引用触发点:用FirstOrDefault()查询匹配行时,找不到结果会返回null,但代码直接执行row.Index访问null对象的属性,直接抛出异常。
  • 后台线程非法访问UI控件:把dgvScriptures.Rows、txtSearchReference.Text这类UI对象放到Task.Run的后台线程中读取,WinForms规定UI控件只能在创建它的UI线程操作,后台线程访问时很可能获取到已被释放、状态变更的控件对象,引发空引用。
  • 单元格值未判空就调用方法:遍历行做匹配时,未判断r.Cells[1].Value是否为null就直接调用.ToString(),遇到未完成赋值的单元格时也会触发空引用。
  • 快速输入的并发冲突:TextChanged事件触发频率随输入速度升高,前一个异步任务还没执行完,新的输入已经清空搜索文本、或是触发了新的选择逻辑,导致旧任务返回的行索引已经失效,操作CurrentCell时出错。
修复方案
  • 替换UI控件遍历逻辑,改用已加载的数据源做匹配
    不要在后台线程直接读取DataGridView的行对象,先在UI线程拿到搜索文本,把纯数据的匹配逻辑放到后台执行,同时对查询结果做判空处理:
    private async Task dgvScripturesChangeRowSelection() 
    {
        // 先在UI线程读取搜索文本,避免后台跨线程访问
        string searchText = txtSearchReference.Text.Trim();
        if (string.IsNullOrEmpty(searchText)) 
        {
            dgvScriptures.ClearSelection();
            return;
        }
    
        int? matchedRowIndex = await Task.Run(() =>
        {
            // 直接读取已经加载到内存的数据源,不要碰DataGridView控件
            var bibleData = (List<dynamic>)dgvScriptures.DataSource;
            for (int i = 0; i < bibleData.Count; i++)
            {
                // 强类型属性不会出现null值,避免单元格空引用问题
                if (bibleData[i].Reference.Contains(searchText))
                {
                    return i;
                }
            }
            return null;
        });
    
        // 回到UI线程操作控件
        if (matchedRowIndex.HasValue)
        {
            dgvScriptures.ClearSelection();
            dgvScriptures.CurrentCell = dgvScriptures[1, matchedRowIndex.Value];
            dgvScriptures.Rows[matchedRowIndex.Value].Selected = true;
        }
        else
        {
            // 找不到匹配项时清空选中状态,避免索引错误
            dgvScriptures.ClearSelection();
        }
    }
    
  • 加输入防抖逻辑,解决快速输入的并发问题
    新增计时器控制搜索执行时机,只有用户暂停输入300ms后才执行搜索,避免频繁触发异步任务导致的状态错乱:
    private System.Windows.Forms.Timer searchDebounceTimer;
    public MainForm()
    {
        InitializeComponent();
        // 初始化防抖计时器
        searchDebounceTimer = new System.Windows.Forms.Timer();
        searchDebounceTimer.Interval = 300;
        searchDebounceTimer.Tick += async (s, e) =>
        {
            searchDebounceTimer.Stop();
            await dgvScripturesChangeRowSelection();
        };
    }
    
    private void txtSearchReference_TextChanged(object sender, EventArgs e)
    {
        // 每次输入重置计时器,只有用户停止输入后才执行搜索
        searchDebounceTimer.Stop();
        searchDebounceTimer.Start();
    }
    
  • 移除原TextChanged事件里无意义的try-catch嵌套,异步任务的异常可以统一在防抖逻辑里捕获,避免漏捕获后台任务的异常。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.02 02:15:04