-2

got datagridview with 3 data, I want to get the first cells data on each rows, when I use this kind of code

string[] DataGridViewArray = { };
            for (int i = 0; i < DataGridView1.Rows.Count; i++)
            {
                DataGridViewArray[i] = DataGridView1.Rows[i].Cells[0].Value.ToString().Trim();
            }
            textBox1.Text = DataGridViewArray.ToString();

why it keep said 'Index was outside the bounds of the array.'

2 Answers2

1

Array is fixed size and its size is determined when declaring it (eg. in your first line of code) .

However, you gave it no single element nor set its size with expected number of items its going to hold - which in your case should be DataGridView1.Rows.Count.

       string[] DataGridViewArray = { }; 

Instead, if you replace that (line #1 code) as follows, it should work:

        string[] DataGridViewArray = new string[DataGridView1.Rows.Count];

        for (int i = 0; i < DataGridView1.Rows.Count; i++)
        {
             DataGridViewArray[i] = 
             DataGridView1.Rows[i].Cells[0].Value.ToString().Trim();
        }

        textBox1.Text = DataGridViewArray.ToString();

I don't have DataGridView1 but I did something similar just to show you the reason why you are getting out of index error and how to fix it.

Clostly look at the length of the array in a way you defined it vs when array length is provided when declaring it.

enter image description here

Koref Koref
  • 300
  • 4
  • 13
0

It's because you didn't properly instantiate your array so any iteration will be out of bounds.

Enigmativity
  • 113,464
  • 11
  • 89
  • 172