简体   繁体   中英

MVC5 C# - System.IndexOutOfRangeException

I'm trying to retrieve data from a SQL database using MVC5 C# and storing the data into a ViewBag array. However, the code results in a IndexOutOfRangeException error.

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++;
    }
}

Solution is I forgot to add LoggedIn column to the query.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM