如何解决索引超出范围的异常? [英] how to solve index out of range Exception?

查看:1020
本文介绍了如何解决索引超出范围的异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

namespace BusinessLayer
{
   public class BusinessLogic
    {
       public IEnumerable<employee> Employees
       {
           get
           {
               string cs = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
               List<employee> employees = new List<employee>();
               using (SqlConnection con = new SqlConnection(cs))
               {
                   SqlCommand cmd = new SqlCommand("SPGETEMPLOYEE", con);
                   cmd.CommandType = CommandType.StoredProcedure;
                   con.Open();
                   SqlDataReader dr = cmd.ExecuteReader();
                   while (dr.Read())
                   {
                       Employee emp = new Employee();
                       emp.Id = Convert.ToInt32(dr["Id"]);
                       emp.name = dr["Name"].ToString();
                       emp.gender = dr["Gender"].ToString();
                       emp.mobile = dr["Mobile"].ToString();
                       emp.doj = Convert.ToDateTime(dr["doj"]);
                       employees.Add(emp);
                   }


               }


               return Employees;
           }

       }
    }
}



从数据库读取数据时获取异常。为什么任何人都可以帮助我

这里


getting the exception while reading the data from database. why can any one help me
Here

emp.Id = Convert.ToInt32(dr["Id"]);



提前感谢


thanks in advance

推荐答案

使用它:

Use this:
emp.Id = Convert.ToInt32(dr["EmpId"]);


您需要匹配列的名称使用您从DataReader访问的名称:

You need to match the names of your columns with the names you access they with from the DataReader:
select EmpId,Name,Gender,MobileNumber,Dateofjoining,[Address] from tblEmployee

列名与代码不匹配:

Does not match the column names with the code:

emp.Id = Convert.ToInt32(dr["Id"]);
emp.name = dr["Name"].ToString();
emp.gender = dr["Gender"].ToString();
emp.mobile = dr["Mobile"].ToString();
emp.doj = Convert.ToDateTime(dr["doj"]);

所以试试:

So try:

emp.Id = Convert.ToInt32(dr["EmpId"]);
emp.name = dr["Name"].ToString();
emp.gender = dr["Gender"].ToString();
emp.mobile = dr["MobileNumber"].ToString();
emp.doj = Convert.ToDateTime(dr["DateofJoining"]);





根据喜好,不要使用Convert或ToString:改为使用它:



And by preference, don't use Convert or ToString: cast it instead:

emp.Id = (int) dr["EmpId"];
emp.name = (string) dr["Name"];
emp.gender = (string) dr["Gender"];
emp.mobile = (string) dr["MobileNumber"];
emp.doj = (DateTime) dr["DateofJoining"];



使用Convert和ToString意味着您已将数据库中的值存储为字符串而不是正确的数据类型 - 这将在以后给您带来巨大的问题。


Using Convert and ToString implies that you have stored the values in your DB as strings instead of the "proper" datatypes - which would give you enormous problems later on.


这篇关于如何解决索引超出范围的异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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