DataReader提供DatagridView控件 - 逐行

时间:2014-10-27 13:04:47

标签: c# datagridview sqldatareader stack-overflow

我有一个处理datareading的类(注意,ischanged是我提出的一个事件,表示新行的可用性)

public DataRow FetchNext()
{
    DataRow drow = dt.NewRow();
    if (dr.Read() && dr.HasRows)  //this will loop through rows unless cancel is clicked
    {
        try
        {
            for (int i = 0; i < listCols.Count; i++)
            {
                drow[(DataColumn)listCols[i]] = dr[i];
            }
            dt.ImportRow(drow);
            totalRowCount++;
            this.isChanged();
            return drow;
        }
        catch (Exception ex)
        {
            throw;
        }
    }
    else
    {
        return drow;
    }
}

另一个使用此类的类实现读取行并将它们插入到datagridview中,如下所示(bs是绑定到数据表dt的绑定源)

private void buttonGo_Click(object sender, EventArgs e)
{
    myrow = p.FetchNext();
    this.dt = p.dt.Copy();
    bs.DataSource = dt;
    dataGridViewMyData.DataSource = bs;
    bs.ResetBindings(false);       
}
private void handleChanged()
{
    bs.ResetBindings(false);
    dt.Rows.Add(p.FetchNext());
}

当我开火时,我得到了:

System.StackOverflowException was unhandled
_HResult=-2147023895

任何帮助都将不胜感激。

1 个答案:

答案 0 :(得分:0)

好的,这就是答案:

    public DataRow FetchNext()
{
    DataRow drow = dt.NewRow();
    if (dr.Read() && dr.HasRows)  //this will loop through rows unless cancel is clicked
    {
        try
        {
            for (int i = 0; i < listCols.Count; i++)
            {
                drow[(DataColumn)listCols[i]] = dr[i];
            }
            dt.ImportRow(drow);
            totalRowCount++;
            this.isChanged();
            return drow;
        }
        catch (Exception ex)
        {
            throw;
        }
    }
    else
    {

        return drow;
    }
}

在调用类中,我实现了一个后台工作器,它在Dowork上:获取Next。虽然workcompleted也接下来,每次都读取isEnded的值。

private void buttonGo_Click(object sender, EventArgs e)
        {
            myrow = p.FetchNext();
            this.dt = p.dt.Copy();
            bs.DataSource = dt;
            dataGridViewMyData.DataSource = bs;
            bs.ResetBindings(false);
            if (!p.isEnded && !backgroundWorker1.IsBusy )
            {
                bs.SuspendBinding();
                backgroundWorker1.RunWorkerAsync();
            }
         }


  private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
    {
        bs.SuspendBinding();
        if (!p.isEnded)
        {
            dt.ImportRow(p.FetchNext());
        }

    }
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
    bs.ResumeBinding();
    if (!p.isEnded)
    {

        backgroundWorker1.RunWorkerAsync();
    }
    else
    {

        MessageBox.Show("Done");
    }
    RefreshData();

}

这确实解决了问题,并且网格确实逐行填充。但是,对于包含数十万行的查询,这将非常耗时。