Operation op = new Operation(); public string header = string.Empty; protected void Page_Load(object sender, EventArgs e) { DataTable dt = op.queryMenu(); foreach (DataRow dr in dt.Rows) { header += "<a href='Category.aspx?menuID=" + dr["menuID"].ToString() + "' class='menu' target='_blank'>" + dr["menuTitle"].ToString() + "</a>"; } }
源错误:
行 9: { 行 10: DataTable dt = op.queryMenu(); 行 11: foreach (System.Data.DataRow dr in dt.Rows) 行 12: { 行 13: header += "<a href='Category.aspx?menuID=" + dr["menuID"].ToString() + "' class='menu' target='_blank'>" + dr["menuTitle"].ToString() + "</a>"; |
源文件: d:\myweb\nc\webheader.ascx.cs 行: 11
Operation op = new Operation(); public string header = string.Empty; protected void Page_Load(object sender, EventArgs e) { DataTable dt = op.queryMenu(); if (dt != null && dt.Rows.Count > 0) { StringBuilder sbHeader = new StringBuilder(); foreach(DataRow dr in dt.Rows) { string menuID = string.Empty, menuTitle = string.Empty; if (dr["menuID"] != null) { menuID = dr["menuID"].ToString(); } if (dr["menuTitle"] != null) { menuTitle = dr["menuTitle"].ToString(); } sbHeader.AppendFormat("<a href='Category.aspx?menuID={0}' class='menu' target='_blank'>{1}</a>", menuID, menuTitle); } header = sbHeader.ToString(); } }
谢谢
有没有检查,dt是否是空的?
空引用异常就是在异常的地方检查每个引用“.”是否为空
dt是NULL或者dt中的某个字段。数据库里是NULL
DataTable加非空判断,取DataTable某列ToString()之前也要加非空判断
先判断 dt.Rows.Count > 0 ? 然后再执行foreach循环