指数数组的边界之外。如何解决这个错误? [英] Index was outside the bounds of the array. how to solve this error?

查看:108
本文介绍了指数数组的边界之外。如何解决这个错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有谁知道这个?



这是我的编码....执行时会产生错误索引超出范围数组





Can anyone know this?

This my coding....when execute it produce the error that "Index was outside the bounds of the array."


public void details(string id)
   {
       if (con.State == ConnectionState.Closed)
       {
           con.Open();
       }
           string ids = Request.QueryString["ID"];
       Session["pro_id"] = ids.ToString();
       SqlCommand cmd = new SqlCommand("select pro_id,pro_name,description,pro_img,price from product where pro_id='"+ids+"'", con);
       SqlDataReader dr = cmd.ExecuteReader();
       if (dr.HasRows)
       {
           while (dr.Read())
           {
               lblpro_id.Text = dr[0].ToString();
               lblpro_name.Text = dr[1].ToString();
               description.Text = dr[2].ToString();
               pro_img.Text= dr[7].ToString();
               lblprice.Text = dr[20].ToString();
             }
       }
       dr.Close();
       con.Close();

   }

推荐答案

未显示异常信息,但很可能是例外情况博士[20] 。或 dr [7] 。看起来您在数据读取器输出中的列数少于您的假设 - 只需查看您的查询。



代码通常很糟糕。像i,7,20这样的立即常量使得代码难以支持。此外,如果您有多于一行,则不断地将读数分配给相同的变量,丢失先前分配的值,因此数据读取器读取块内的整个块没有意义:它的结果只分配了来自同一行的值。每次调用详细信息时,不应每次都要关闭连接。使用懒惰评估策略( http://),按需打开连接并保持打开状态要好得多en.wikipedia.org/wiki/Lazy_evaluation [ ^ ])。



-SA
Exception information is not shown, but most likely the exception is in dr[20]. Or dr[7]. It looks like you have less columns in data reader output than you assume — just look at your query.

The code is generally bad. Immediate constants like 2, 7, 20 make the code hard to support. Also, if you have more than 1 row, you keep assigning the reading to the same variable over and over, loosing the previously assigned values, so the whole block inside data reader reading block makes no sense: the result of it is assigning only the values from the same row. And you should not close connection every time to open it again and again on each call to details. It's much better opening the connection on demand and keep it open, using the lazy evaluation strategy (http://en.wikipedia.org/wiki/Lazy_evaluation[^]).

—SA


你的表中至少有21列?如果不是这就是您的例外原因。
Are there a minimum of 21 columns in your table? if not this is the reason for your exception.


IMO调试器足以解决此错误。



System.IndexOutOfRangeException未处理(Message =Index超出了数组的范围。) [ ^ ]

索引超出了数组的范围 [ ^ ]
IMO debugger is enough to fix this error.

System.IndexOutOfRangeException was unhandled (Message="Index was outside the bounds of the array.")[^]
Index was outside the bounds of the array[^]


这篇关于指数数组的边界之外。如何解决这个错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆