从数据库拉取数据时触发System.IndexOutOfRangeException问题求助
解决System.IndexOutOfRangeException: Blurb错误及代码优化
错误根源
触发System.IndexOutOfRangeException: Blurb的直接原因是:
- 你的SQL查询仅选取了
b.BlurbText和b.BlurbID两个字段,但代码中尝试读取blurbReader["Blurb"]——这个字段不在查询结果集中,因此抛出索引越界异常。
代码中的其他问题
- 冗余参数:你给
SqlCommand添加了@BlurbID和@BlurbText参数,但SQL语句里完全没用到这些参数,属于无效代码,建议删除。 - 逻辑位置错误:判断“无评价”的
if (blurbPH.Controls.Count == 0)放在while循环内部,只要有一条数据被读取,控件计数就会大于0,导致提示永远无法显示。必须将该判断移到循环外部。
修正后的代码示例
protected void Page_Load(object sender, EventArgs e) { //BlurbID = Session["Blurb"]; Page.Title = "Testimonials"; try { sqlConnectionStr.Open(); // 确认TestimonialBlurb表存在Blurb字段后,添加到SELECT语句中 SqlCommand getBlurb = new SqlCommand(@"SELECT b.BlurbText, b.BlurbID, b.Blurb FROM TestimonialBlurb b ", sqlConnectionStr); using (SqlDataReader blurbReader = getBlurb.ExecuteReader()) { while (blurbReader.Read()) { blurbPH.Controls.Add(new Literal { Text = blurbReader["BlurbText"].ToString() + "<strong>" + blurbReader["Blurb"].ToString() + "</strong>" }); } // 循环结束后判断是否有数据 if (blurbPH.Controls.Count == 0) { Response.Write("There are currently no testimonials available."); } } } catch (Exception ex) { blurbPH.Controls.Add(new Literal { Text = ex.ToString() }); } finally { sqlConnectionStr.Close(); } }
关于DECLARE语句的疑问
你不需要在SQL开头添加DECLARE语句。DECLARE用于在SQL脚本中声明变量,而你的问题并非参数声明问题,而是字段不匹配和代码逻辑错误导致的,因此完全不需要这个操作。
内容的提问来源于stack exchange,提问作者estuhbawn
相关产品推荐
相关产品推荐

