0

I want show some calculated 2D data in grid form in C# using datagridview. The size of grid is not prefixed and I have to calculate the for one cell at a time using some for loop, so I'm not able to make use of datatable class for the same purpose where we add data for a complete row at time (I don't not know if there is a way add data to a single cell at time).

So I tried the 2D array perform the same but when I'm trying to show data in datagridview it showing error that: array was not a one-dimensional array.

Here is snapshot of error message:

Error Dialog

And here is the code:

string[,] difference = new string[dataGridView1.Rows.Count, dataGridView2.Rows.Count];

            foreach (DataGridViewRow row1 in dataGridView1.Rows)
            {
                foreach ( DataGridViewRow row2 in  dataGridView2.Rows)
                {
                    difference[row1.Index, row2.Index] = Convert.ToString(Math.Abs((Convert.ToSingle(dataGridView1.Rows[row1.Index].Cells[0].Value)) - (Convert.ToSingle(dataGridView2.Rows[row2.Index].Cells[0].Value))));
                }
            }

            dataGridView3.DataSource = difference;

            }
Ajeet Shah
  • 18,551
  • 8
  • 57
  • 87
  • Possible duplicate of [Show 2d-array in DataGridView](http://stackoverflow.com/questions/29633018/show-2d-array-in-datagridview) – OhBeWise Jun 09 '16 at 17:15

1 Answers1

0

you have taken two dimensional array but passing only one dimensional array

i have modified below code , please look into it.

if(dataGridView1.Rows.Count== dataGridView2.Rows.Count)
{
string[] difference = new string[dataGridView1.Rows.Count];

            foreach (DataGridViewRow row1 in dataGridView1.Rows)
            {
                foreach ( DataGridViewRow row2 in  dataGridView2.Rows)
                {
                    difference[row1.Index] = Convert.ToString(Math.Abs((Convert.ToSingle(dataGridView1.Rows[row1.Index].Cells[0].Value)) - (Convert.ToSingle(dataGridView2.Rows[row2.Index].Cells[0].Value))));
                }
            }

            dataGridView3.DataSource = difference;

            }
}
  • thanks Sridhar bro, yeah actually i want to pass that 2D array to the datagridview but don't know what would be the syntax for that. And equal no. of row count is not ma condtion so my array can be a rectangular 2D... – Kuldeep Kaushik Jun 14 '16 at 08:47