MVC5 C# - System.IndexOutOfRangeException



我试图使用MVC5 c#从SQL数据库检索数据并将数据存储到ViewBag数组中。然而,该代码导致IndexOutOfRangeException错误。

query = "SELECT Id, UserName, List_Order FROM AspNetUsers WHERE LoggedIn = 1 ORDER BY 
List_Order ASC";
SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager
.ConnectionStrings["DefaultConnection"].ConnectionString);
SqlCommand cmd = new SqlCommand(query, conn);
conn.Open();
SqlDataReader rdr = cmd.ExecuteReader();
int n = 0;
while(rdr.Read())
{
    if (rdr["UserName"].ToString() != null)
    {
        //Exception Details: System.IndexOutOfRangeException: LoggedIn
        ViewBag.speakers[n] = new string[4] { rdr["Id"].ToString(), rdr["UserName"]
.ToString(), rdr["List_Order"].ToString(), rdr["LoggedIn"].ToString() };
        n++;
    }
}

解决方案是我忘记在查询中添加LoggedIn列。

query = "SELECT Id, UserName, List_Order, LoggedIn FROM AspNetUsers WHERE LoggedIn = 1 
ORDER BY List_Order ASC";

相关内容

  • 没有找到相关文章

最新更新