简体   繁体   中英

Value cannot be null (exception)

I was not experiencing this error when all of the sudden it comes up - no idea why. I have tried resolving it but nothing works. The error occurs at " genreList.Items.AddRange(trackList);" (the last line of code). Does anyone know how to solve this?

    private void readFile()
    {
        string[] lines = System.IO.File.ReadAllLines(>path<);
        for (int i = 0; i <= 10; i++)
        {
            if (i == 2)
            {
                media[0, 0] = lines[i]; // General (title)
                System.Diagnostics.Debug.WriteLine(media[0, 0]); // Debug, checking values in array after each 'if'
            }
            if (i == 3)
            {
                media[0, 1] = lines[i]; // Introduction.wma (list)
                System.Diagnostics.Debug.WriteLine(media[0, 1]);
            }
            if (i == 5)
            {
                media[1, 0] = lines[i]; // Setup (title)
                System.Diagnostics.Debug.WriteLine(media[1, 0]);
            }
            if (i == 6)
            {
                media[1, 1] = lines[i]; // Calling Setup.wma (list)
                System.Diagnostics.Debug.WriteLine(media[1, 1]);
            }
            if (i == 8)
            {
                media[2, 0] = lines[i]; // Hint & Tips (title)
                System.Diagnostics.Debug.WriteLine(media[2, 0]);
            }
            if (i == 9)
            {
                media[2, 1] = lines[i]; // Big Bad John (1961) - Jimmy Dean.mp3 (list)
                System.Diagnostics.Debug.WriteLine(media[2, 1]);
            }
            if (i == 10)
            {
                media[2, 2] = lines[i]; // My Ding A Ling - Chuck Berry.mp3 (list)
                System.Diagnostics.Debug.WriteLine(media[2, 2]);
            }
        }
    }

    private void populateGenreList()
    {
        genreTitle.Text = media[0, 0];
        string[] trackList = new string[3];
        trackList[0] = media[0, 1];
        genreList.Items.AddRange(trackList);
    }

You need to avoid adding values that contain null while using AddRange

trackList[0] = media[0, 1];
if(trackList != null)
{
        genreList.Items.AddRange(trackList);
}

In this line,

genreList.Items.AddRange(trackList);

the trackList is not null since you're just initializing it a line ago. Also, you can add a list containing null values using the AddRange method. so trackList could have 3 null values and still you shouldn't see the null reference.

But this happens to List AddRange method.

So in your case, there is some custom code that is creating this exception. Definition of genreList class and stack trace of the exception, please.

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