1

I'm trying to display the 2d array in datagridview. Im generting data via Windows Form into 2d array and then trying to display that data into datagrid view but I get an error on line row.CreateCells(this.dataGridView1); Row provided already belongs to a DataGridView control. not sure what im doing wrong appreciate if anyone please put me on the right direction Code is below

   iArray = new String[2, 10];
            iArray = custDetails.pCustomDetails();


            int height = iArray.GetLength(0);
            int width = iArray.GetLength(1);
        MessageBox.Show(height.ToString());
        MessageBox.Show(width.ToString());

        this.dataGridView1.ColumnCount = width;

            for (int r = 0; r < height; r++)
            {

            row.CreateCells(this.dataGridView1);

                for (int c = 0; c < width; c++)
                {
                row.Cells[c].Value = iArray[r, c];

                }

                this.dataGridView1.Rows.Add(row);
            }

2 Answers 2

2

The only problem here is that you are trying to add the same instance of row again and again in loop.

So this small fix will make yr code work

 for (int r = 0; r < height; r++)
        {

         //Fix : create a new instance of row every time
          DataGridViewRow row = new DataGridViewRow();


        row.CreateCells(this.dataGridView1);

            for (int c = 0; c < width; c++)
            {
            row.Cells[c].Value = iArray[r, c];

            }

            this.dataGridView1.Rows.Add(row);
        }
Sign up to request clarification or add additional context in comments.

Comments

0

I think this answer is the best one you can find, just rewrite it into C#:

'at first add columns to the dataGridView before insert rows in it
'y = number of the columns which should equal yourArray.getlength(0) - 1 
'you can change (col) to any type of column you need

        For i = 0 To y
            Dim col As New DataGridViewTextBoxColumn
            col.DataPropertyName = "PropertyName" & i.ToString
            col.HeaderText = i.ToString
            col.Name = "colWhateverName" & i.ToString
            DataGridView1.Columns.Add(col)
        Next

'now you insert the rows
'exampleRow ={yourArray(0,0), yourArray(0,1), ..... ,yourArray(0,y)}
'x = number of rows

        For i = 0 To x
            Dim aarray As New List(Of String)
            For ii = 0 To y
                aarray.Add(yourArray(i, ii).ToString)
            Next
            DataGridView1.Rows.Add(aarray.ToArray)
        Next

I do such an app you can check it here: https://github.com/ammardab3an/Array-Rotate-90

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.