如何使用C#winform创建带并行的dataGridView? [英] How to create dataGridView with Parallel for using C# winform?

查看:179
本文介绍了如何使用C#winform创建带并行的dataGridView?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我是并行编程的新手。我试图使用并行For循环填充dataGridView的列标题和行标题。但是每次运行程序时我都会遇到不同的错误:



索引超出了数组的范围。



在调整列的DisplayIndex时,无法执行此操作。



有人可以解决这个问题吗? />



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?

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
                        });            
        }
    }
}

推荐答案

修复 索引超出了数组的范围。错误,您可以使用返回值 Rows.Add ,如下所示



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

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





但是,这不是Parallel.ForEach的良好用户案例。您可能需要使用 BeginInvoke 并在其他事件中执行此操作,例如按钮单击,然后加载datagridview,您将不会获得异常。





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.

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();
    })));   
}   


这篇关于如何使用C#winform创建带并行的dataGridView?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆