c# - ArgumentOutOfRangeException: Index was out of range - 2 Forms
<p>Problem solved.</p>

<p>The original "private void buttonSave_Click" was changed to:</p>

<pre><code>private void buttonSave_Click(object sender, EventArgs e)
{
    if (MusicCollection.FormMain.PublicVars.AlbumList.Count != 100)
    {
        MusicCollection.FormMain.PublicVars.AlbumList.Add(new Album(NameTextBox.Text));

        MessageBox.Show("New Album added: " + NameTextBox.Text);
        formMain.ListAlbums(formMain.AlbumsListBox.Items);
        this.Close();
    }
    else
    {
        MessageBox.Show("No room for new album.");
        this.Close();
    }
}
</code></pre>

<p>Original Post:</p>

<p>I'm new to using C#, so appologies for any seemly obvious mistakes or terrible coding.</p>

<p>I'm trying to create a new Album object (that gets its Name from NameTextBox.Text on Form FormAlbumAC) and add it to List AlbumList when the user clicks the save button on FormAlbumAC. Then I want to list all of AlbumList in a ListBox on Form FormMain.</p>

<p>When I run the program and click the save button, I'm getting the error "ArgumentOutOfRangeException was unhandled, Index was out of range" at the line:</p>

<pre><code>if (MusicCollection.FormMain.PublicVars.AlbumList[i] == null)
// line 8 on my excerpt from Form FormAblumAC
</code></pre>

<p>I'm not sure what I'm doing wrong. Any help would be much appreciated, thank you.</p>

<p>Form FormMain:</p>

<pre><code>public const int MAX_ALBUMS = 100;
public int totalAlbums = 0;

public FormMain()
    {
        InitializeComponent();
    }

public static class PublicVars
{
    public static List&lt;Album&gt; AlbumList { get; set; }

    static PublicVars()
    {
        AlbumList = new List&lt;Album&gt;(MAX_ALBUMS);
    }
}

public ListBox AlbumListBox
{
    get
    {
        return AlbumListBox;
    }
}

public void ListAlbums(IList list)
{
    list.Clear();
    foreach (var album in PublicVars.AlbumList)
    {
        if (album == null)
            continue;
        list.Add(album.Name);
    }
}
</code></pre>

<p>Form FormAlbumAC:</p>

<pre><code>private FormMain formMain;

private void buttonSave_Click(object sender, EventArgs e)
{
    int index = -1;
    for (int i = 0; i &lt; MusicCollection.FormMain.MAX_ALBUMS; ++i)
    {
        if (MusicCollection.FormMain.PublicVars.AlbumList[i] == null)
        {
            index = i;
            break;
        }
    }
    if (index != -1)
    {
        MusicCollection.FormMain.PublicVars.AlbumList[index] = new Album(NameTextBox.Text);
        ++formMain.totalAlbums;

        MessageBox.Show("New Album added: " + NameTextBox.Text);
        formMain.ListAlbums(formMain.AlbumsListBox.Items);
        this.Close();
    }
    else
    {
        MessageBox.Show("No room for new album.");
        this.Close();
    }
}
</code></pre>
