开发者

Adding row to DataGridView from Thread

I would like to add rows to DataGridView from two seperate threads. I tried something with delegates and BeginInvoke but doesn't work.

Here is my row updater function which is called from another function in a thread.

    public delegate void GRIDLOGDelegate(string ulke, string url, string ip = "");
    private void GRIDLOG(string ulke, string url, string ip = "")
    {

        if (this.InvokeRequired)
        {
            // Pass the same function开发者_StackOverflow社区 to BeginInvoke,
            // but the call would come on the correct
            // thread and InvokeRequired will be false.
            object[] myArray = new object[3];

            myArray[0] = ulke;
            myArray[1] = url;
            myArray[2] = ip;

            this.BeginInvoke(new GRIDLOGDelegate(GRIDLOG),
                                             new object[] { myArray });

            return;
        }

        //Yeni bir satır daha oluştur
        string[] newRow = new string[] { ulke, url, ip };
        dgLogGrid.Rows.Add(newRow);
    }


You can use the following code:

   private void GRIDLOG(string ulke, string url, string ip = "")
    {
        object[] myArray = new object[] { ulke, url, ip};
        if (this.InvokeRequired)
            dgLogGrid.Invoke((MethodInvoker)(() => dgLogGrid.Rows.Add(myArray)));
        else dgLogGrid.Rows.Add(myArray);
    }


this.BeginInvoke(new GRIDLOGDelegate(GRIDLOG),
        //error seems to be here -> new object[] { myArray });
        myArray) // <- how it should be

Update:

You can also do it this way:

BeginInvoke(new GRIDLOGDelegate(GRIDLOG), ulke, url, ip);


Hope this is helpful =]

private object[] DatagridBuffer(Person p)
{
    object[] buffer = new object[1];
    buffer[0] = p.FirstName;
    buffer[1] = p.LastName;
    return buffer;
{

public void ListPeople() 
{
    List<DatagridViewRow> rows = new List<DataGridViewRow>();
    Dictionary<int, Person> list = SqlUtilities.Instance.InstallationList();
    int index = 0;
    foreach (Person p in list.Values) {
        rows.Add(new DataGridViewRow());
        rows[index].CreateCells(datagrid, DatagridBuffer(p));
        index += 1;
    }
    UpdateDatagridView(rows.ToArray());
}

public delegate void UpdateDatagridViewDelegate(DataGridViewRow[] list);
public void UpdateDatagridView(DataGridViewRow[] list)
{
    if (this.InvokeRequired)
    {
        this.BeginInvoke(
             new UpdateDatagridViewDelegate(UpdateDatagridView), 
             new object[] { list }
        );
    }
    else
    {
        datagrid.Rows.AddRange(list);
    }
}

If you find that my code is incorrect, or can be improved, please do comment.


You need to pass array of parameters. You are making a mistake while calling this.BeginInvoke

Try like this:

this.BeginInvoke(new GRIDLOGDelegate(GRIDLOG), new object[] { ulke, url, ip });

Everything else seems correct.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜