exception - MVC5 / C# - Cannot perform runtime binding on a null reference -
i'm trying figure out what's causing cannot perform runtime binding on null reference
error code:
var query = "select id, username, list_order, loggedin " + "from aspnetusers" + "where loggedin = 1" + "order list_order asc"; var conn = new sqlconnection(system.configuration.configurationmanager.connectionstrings["defaultconnection"].connectionstring); var cmd = new sqlcommand(query, conn); conn.open(); var rdr = cmd.executereader(); var n = 0; while(rdr.read()) { if (convert.tostring(rdr["username"]) != null) { viewbag.speakers[n] = new string[4] { convert.tostring(rdr["id"]), convert.tostring(rdr["username"]), convert.tostring(rdr["list_order"]), convert.tostring(rdr["loggedin"]) }; //exception details: microsoft.csharp.runtimebinder.runtimebinderexception: cannot //perform runtime binding on null reference n++; } }
the n++
increment seems cause of error , don't understand why.
updated code reflect possible solutions. however, error still remains.
tried same result:
if (!string.isnullorwhitespace(convert.tostring(rdr["username"]))) { list<string> speakers = new list<string>(); speakers.add(convert.tostring(rdr["id"])); speakers.add(convert.tostring(rdr["username"])); speakers.add(convert.tostring(rdr["list_order"])); speakers.add(convert.tostring(rdr["loggedin"])); viewbag.speakers[n] = speakers; n++; }
there 2 issues in code:
consider this:
public actionresult index() { int n = 0; viewbag.speakers[n] = 5; return view(); }
this simplified piece of code throws cannot perform runtime binding on null reference
since speakers not defined (null reference).
you can fix defining speakers
in dynamic viewbag before loop:
viewbag.speakers = new list<string>();
the second issue:
viewbag.speakers[n] = speakers;
speakers in code list, might want define viewbag.speakers
list<list<string>>
, call .add(speakers)
instead of accessing using index (you might index out of range)
Comments
Post a Comment