0

I'm trying to execute some SQL queries that takes long time and returns a lot of rows, and that's why i use SqlDataReader for returning the rows.

I execute the query in a separate thread, so the UI would be usable while the rows are returned.

I also have a datatable, which i'm filling with the SqlDataReader, and the DataTable is bound to a BindingSource, and the BindingSource is bound to the DataGridView.

The problem is that the DataGridView seems to be unable to bind the columns of the DataTable to the Columns in the DataGridView, and all cells in the grid shows blank. Even with AutoGenerateColumns=true, the data is not shown!

The below is an example code quite similar to my problem:

public partial class Form2 : Form
{
    BindingSource binding;
    DataTable dt = new DataTable();
    DataGridView dgv;

    public Form2()
    {
        InitializeComponent();

        binding = new BindingSource();
        binding.DataSource = dt;

        dgv = new DataGridView();
        dgv.Columns.Add("Column1", "Column1");
        dgv.Columns[0].DataPropertyName = "Column1";
        dgv.AutoGenerateColumns = false;
        dgv.DataSource = binding;
        dgv.Click += new EventHandler(dgv_Click);
        this.Controls.Add(dgv);

        dostuff();  // ON FIRST TRY 5 ROWS SHOWN
    }

    void dgv_Click(object sender, EventArgs e)
    {
        dostuff();  // ON SECOND RUN EVERYTHING IS CLEARED!
    }

    void dostuff()
    {            
        dgv.DataSource = null;
        dt.Rows.Clear();
        dt.Columns.Clear();
        dgv.DataSource = binding;

        BackgroundWorker bgw = new BackgroundWorker();
        bgw.DoWork += new DoWorkEventHandler(bgw_DoWork);
        bgw.RunWorkerAsync();

    }

    void bgw_DoWork(object sender, DoWorkEventArgs e)
    {
        dt.Rows.Clear();
        dt.Columns.Clear();

        dt.Columns.Add("Column1");

        for (int i = 0; i < 5; i++)
        {
            DataRow r = dt.NewRow();
            r[0] = i;
            dt.Rows.Add(r);
        }
    }
}
4

2 に答える 2

2

DataGridViewメソッドの最後でを更新する必要があり、メソッドを UI スレッドで実行する必要があるため、bgw_DoWorkを使用する必要があります。変更された方法は次のとおりです。InvokeRefreshbgw_DoWork

void bgw_DoWork(object sender, DoWorkEventArgs e)
{
    dt.Rows.Clear();
    dt.Columns.Clear();

    dt.Columns.Add("Column1");

    for (int i = 0; i < 5; i++)
    {
        DataRow r = dt.NewRow();
        r[0] = i;
        dt.Rows.Add(r);
    }

    dgv.Invoke((MethodInvoker) delegate() { dgv.Refresh(); });
}
于 2012-11-06T09:30:23.263 に答える
0

で列を作成し、それぞれを で対応する列の名前にDataGridView設定できます。ここに示すように: http://msdn.microsoft.com/en-us/library/system.windows.forms.datagridviewcolumn.datapropertyname.aspxDataGridViewColumnDataPropertyNameDataTable

于 2012-11-01T13:53:56.650 に答える