我想从两个单独的线程向DataGridView添加行。我尝试了一些代理和BeginInvoke,但是没有用。
这是我的行更新程序函数,它从一个线程中的另一个函数调用。
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 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);
}
答案 0 :(得分:2)
您可以使用以下代码:
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);
}
答案 1 :(得分:1)
this.BeginInvoke(new GRIDLOGDelegate(GRIDLOG),
//error seems to be here -> new object[] { myArray });
myArray) // <- how it should be
更新
你也可以这样做:
BeginInvoke(new GRIDLOGDelegate(GRIDLOG), ulke, url, ip);
答案 2 :(得分:1)
您需要传递参数数组。
在调用this.BeginInvoke
试试这样:
this.BeginInvoke(new GRIDLOGDelegate(GRIDLOG), new object[] { ulke, url, ip });
其他一切似乎都是正确的。
答案 3 :(得分:1)
希望这有用=]
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);
}
}
如果您发现我的代码不正确或可以改进,请发表评论。