exception – MVC5 / C# – Cannot perform runtime binding on a null reference

exception – MVC5 / C# – Cannot perform runtime binding on a null reference

There are two issues in your 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 a null reference since speakers is not defined (null reference).

You can fix it by defining speakers in the dynamic ViewBag before the loop:

ViewBag.speakers = new List<string>();

The second issue:

ViewBag.speakers[n] = speakers;

speakers in your code is a List, you might want to define ViewBag.speakers as a List<List<string>> and call .Add(speakers) instead of accessing using an index (you might get index was out of range)

Calling the .ToString() method on a null column value can result in the Cannot perform runtime binding on a null reference. Use Convert.ToString() instead; it will return an empty string if you attempt to convert a null value and wont require additional code for null checking.

exception – MVC5 / C# – Cannot perform runtime binding on a null reference

ViewBag is a dynamic object and when you try to do assignments to its properties, the null check will happen in runtime. You get this error because ViewBag.speakers is either null, or it throws an exception while trying to access its nth slot with indexer (maybe its size is less than n, or it doesnt define an indexer at all). You should initialize ViewBag.speakers before adding elements to it.

var query = SELECT Id, UserName, List_Order, LoggedIn  + 
            FROM AspNetUsers +
            WHERE LoggedIn = 1 + 
            ORDER BY 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();
ViewBag.speakers = new List<string[]>();
while(rdr.Read())
{
    if (Convert.ToString(rdr[UserName]) != null)
    {
        var speakers = new string[4] {
            Convert.ToString(rdr[Id]),
            Convert.ToString(rdr[UserName]),
            Convert.ToString(rdr[List_Order]),
            Convert.ToString(rdr[LoggedIn]) 
        };
        ViewBag.speakers.Add(speakers);
    }
}

Leave a Reply

Your email address will not be published.