将数据加载到DataGridView需要花费大量时间。 [英] Loading data to DataGridView is taking lot of time.

查看:103
本文介绍了将数据加载到DataGridView需要花费大量时间。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个100X100大小的dataGridView1,以编程方式生成单元格。当我运行程序时,需要花费大量时间(5分钟)才能在dataGrid中显示数据。任何人都可以提供 帮助来解决这个问题吗?





I have a dataGridView1 which is of 100X100 size, cells are generated programmatically. When I'm running the program it is taking lot of time (5min) to display the data in the dataGrid. Could anyone please provide help to fix this problem?


using System;
using System.Windows.Forms;


namespace MatrixToDataGridView
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
   
            for (int k = 0; k < 100; k++)
            {
                dataGridView1.TopLeftHeaderCell.Value = "Theta / Phi";
                dataGridView1.Columns.Add("", k.ToString() );// dynamic cloumn adding
                dataGridView1.Rows.Add();//dynamic row adding
            }              
        }       
        public void function()
        {
            double [,] num = new double[100, 100];

            //Populates the array
            for (int i = 0; i < 100; i++)
            {
                for (int j = 0; j < 100; j++)
                {
                    num[i, j] = i+j;                     
                }
            }
            //Populates the dataGridView1
            for (int i = 0; i < 100; i++)
            {
                for (int j = 0; j < 100; j++)
                {
                    dataGridView1.Rows[i].Cells[j].Value = num[i, j].ToString();                    
                }
            }       
        }

        //Button for calling the function() to populate the array num and dataGridView1
        private void button1_Click(object sender, EventArgs e)
        {
            function(); 
        }
    }
}

推荐答案

这需要永远,因为你正在填充每个单元格,个别。这是设置每个单元格的10,000次调用。 DataGridView不是Excel!你试图强迫DGV做一些它不打算做的事情。



在我的机器上,你的代码运行时间不到1秒。你在运行什么?
It takes forever because you're populating each cell, individually. That's 10,000 calls to set each cell. The DataGridView is NOT Excel! You're trying to force the DGV to do something it was not designed to do.

On my machine, your code takes less than 1 second to run. What are you running this on?


当我将属性中的datagridview1的AutoSizeColumnsMode变为显示的单元格时,问题就解决了。
The problem solved when I made "AutoSizeColumnsMode" of datagridview1 in properties to "Displayed Cells" .


这篇关于将数据加载到DataGridView需要花费大量时间。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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