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

ASP.NET Repeater控件ItemDataBound中FindControl出现意外错误排查

问题分析与解决

你的代码触发意外错误的核心原因是未判断RepeaterItem的类型:Repeater的ItemDataBound事件会在所有模板项(包括ItemTemplate、SeparatorTemplate等)绑定数据时触发,但txLicenseHistoryType仅存在于ItemTemplate中。当事件触发到SeparatorTemplate这类不包含该TextBox的项时,FindControl会返回null,此时强制转换为TextBox就会抛出空引用异常。

修复后的C#代码

protected void rptLicenseHistory_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
    // 仅处理包含ItemTemplate控件的项类型
    if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
    {
        TextBox txtLicense = (TextBox)e.Item.FindControl("txLicenseHistoryType");
        if (txtLicense != null)
        {
            txtLicense.Text = "Test";
        }
    }
}

额外注意事项

  • 你的ASPX中Repeater的ID(rptLicHistory)与事件绑定的方法名(rptLicenseHistory_ItemDataBound)匹配,这部分没有问题。
  • 增加null判断可以避免因控件ID拼写错误等极端情况再次触发异常。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 06:10:09