Click here to Skip to main content
15,890,897 members
Please Sign up or sign in to vote.
3.00/5 (1 vote)
See more:

I'm new to Parallel programming. I' trying to populate column header and row-header of a dataGridView with numbers using parallel For loop. But I'm getting every time different error when ever run the program:

"Index was outside the bounds of the array."

"This operation cannot be performed while the DisplayIndex of a column is being adjusted."

Could anyone please fix this problem?

C#
using System;
using System.Drawing;
using System.Windows.Forms;
using System.Threading.Tasks;


namespace DataGridView
{
    public partial class Form1 : Form
    {

        public Form1()
        {
            InitializeComponent();
            Parallel.For(0, 1000, k =>
                        {

                            dataGridView1.Columns.Add("", k.ToString());// Adding column during run-time and populating
                            dataGridView1.Rows.Add();// Adding row during run-time
                            dataGridView1.Rows[k].HeaderCell.Value = k.ToString();// To populate row headers
                        });            
        }
    }
}
Posted
Updated 2-May-14 17:29pm
v6

1 solution

to fix "Index was outside the bounds of the array." error, you can use return value of Rows.Add as below

C#
int rowindex = dataGridView1.Rows.Add();
dataGridView1.Rows[rowindex].HeaderCell.Value = k.ToString();


But, This is not a good user case for Parallel.ForEach. you may need to use BeginInvoke and also do this in some other event like button click, then your datagridview loaded and you will not get exception.

C#
private void button1_Click(object sender, EventArgs e)
{
    Parallel.For(0, 5, k =>
    BeginInvoke(new Action(() =>
    {
        dataGridView1.Columns.Add("", k.ToString());
        int index = dataGridView1.Rows.Add();
        dataGridView1.Rows[index].HeaderCell.Value = k.ToString();
    })));   
}   
 
Share this answer
 
v2
Comments
Member 9794576 2-May-14 23:26pm    
I'm getting following error:
This operation cannot be performed while the DisplayIndex of a column is being adjusted.
DamithSL 3-May-14 0:55am    
any reason for down vote this answer?
Member 9794576 3-May-14 16:16pm    
Thank you, it worked.
Member 9794576 3-May-14 16:19pm    
Thank you, it worked. I have voted 5;

But when I give limit as 101, the results are not stable. The rows are not printed in right order. Can you please suggest how to fix this problem?

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900