使用DataTable将数据加载到DataGridView的Progressbar

Mar*_*rek 14 c# sql sql-server datagridview winforms

我有一个DataGridView从SQL服务器数据库加载数据.当我加载数据时需要很长时间.

我想向用户提供数据正在加载的信息.请问您Progressbar在将数据加载到数据库时连接的最佳方式是DataGridView什么?

我不希望任何人为我制作完整的代码.我只是想知道如何做到这一点.

我看到有人以赏金授予我的问题.我想说,目前我使用这个代码,如果它适合的话我会恭喜.

DTGdataTable = new DataTable();
SqlDataAdapter SDA = new SqlDataAdapter
SDA.Fill(DTGdataTable);
dataGridView1.DataSource = DTGdataTable ;
Run Code Online (Sandbox Code Playgroud)

谢谢大家的时间.

小智 20

如果问题是从数据库中获取数据需要很长时间,我有一个可能的解决方案:

    private void buttonLoad_Click(object sender, EventArgs e)
    {
        progressBar.Visible = true;
        progressBar.Style = ProgressBarStyle.Marquee;
        System.Threading.Thread thread = 
          new System.Threading.Thread(new System.Threading.ThreadStart(loadTable));
        thread.Start();
    }

    private void loadTable()
    {
        // Load your Table...
        DataTable table = new DataTable();
        SqlDataAdapter SDA = new SqlDataAdapter();
        SDA.Fill(table);
        setDataSource(table);
    }

    internal delegate void SetDataSourceDelegate(DataTable table);
    private void setDataSource(DataTable table)
    {
        // Invoke method if required:
        if (this.InvokeRequired)
        {
            this.Invoke(new SetDataSourceDelegate(setDataSource), table);
        }
        else
        {
            dataGridView.DataSource = table;
            progressBar.Visible = false;
        }
    }
Run Code Online (Sandbox Code Playgroud)

将加载数据的方法放入另一个线程,并在数据源完成时设置数据源.应该有一个调用.如果要在进度条中显示百分比值,请不要使用"Marquee"样式并添加另一个函数和委托,您可以调用该函数来设置进度条的值.

如果将数据绑定到网格是问题,那么您不能将绑定放入另一个线程,并且您可能会显示在另一个线程中运行的进度弹出窗口.

我希望这有帮助.