-3

I am new to csharp so bear with me. I am trying to display a 2D array in a textbox when I press a button. I get error "system.indexOutOfRange"

public int[,] setupState()
{
    int[,] startArray = new int[5, 5] // 2 Dem array using 0 as empty and 1 as full and 3 as not valid location. 
    {
        { 0, 1, 1, 1, 1  },
        { 1, 1, 1, 1, 3  },
        { 1, 1, 1, 3, 3  },
        { 1, 1, 3, 3, 3  },
        { 1, 3, 3, 3, 3  }};

    return startArray;
}

private void button1_Click(object sender, EventArgs e)
{
    //MessageBox.Show("Testing Button");
    int[,] cState = new int[5, 5];
    cState = setupState();
    if (cState.Length > 0)
    {
        StringBuilder col = new StringBuilder();
        StringBuilder row = new StringBuilder();
        for (int i = 0; i < cState.Length; i++)

            for (int j = 0; j < cState.Length; j++)

                col.Append(", ").Append(cState[i, j]);
        //row.Append(", ").Append(cState[i, j]);
        textBox1.Text = col.ToString();
    }
}
Simon Karlsson
  • 4,090
  • 22
  • 39
Brayan103
  • 1
  • 1

1 Answers1

1

The problem is that you are using cState.Length to find the length of the dimensions. You need to use something like what's shown in What is IndexOutOfRangeException and how do I fix it?, using array.GetLength(), to find the size of the different dimensions.

Here's your code with cState.Length replaced with the correct cState.GetLength() statements.

public int[,] setupState ()
    {
         int[,] startArray = new int[5, 5] // 2 Dem array using 0 as empty and 1 as full and 3 as not valid location. 
        {
            { 0, 1, 1, 1, 1  },
            { 1, 1, 1, 1, 3  },
            { 1, 1, 1, 3, 3  },
            { 1, 1, 3, 3, 3  },
            { 1, 3, 3, 3, 3  }};

        return startArray;


    }  

private void button1_Click(object sender, EventArgs e)
    {
        //MessageBox.Show("Testing Button");
        int[,] cState = new int[5, 5];
        cState = setupState();
        if (cState.Length > 0)
        {
            StringBuilder col = new StringBuilder();
            StringBuilder row = new StringBuilder();
            for (int i = 0; i < cState.GetLength(0); i++)

                for (int j = 0; j < cState.GetLength(1); j++)

                    col.Append(", ").Append(cState[i, j]);
                    //row.Append(", ").Append(cState[i, j]);
                    textBox1.Text = col.ToString();
        }
    }
Community
  • 1
  • 1
Gabby Paolucci
  • 887
  • 8
  • 23