![](/img/trans.png)
[英]Adding a row to a datagridview from another thread in another class
[英]Adding row to DataGridView from Thread
我想從兩個單獨的線程向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);
}
您可以使用以下代碼:
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);
}
希望這對您有幫助=]
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);
}
}
如果您發現我的代碼不正確或可以改進,請發表評論。
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);
您需要傳遞參數數組。 您在致電時this.BeginInvoke
嘗試這樣:
this.BeginInvoke(new GRIDLOGDelegate(GRIDLOG), new object[] { ulke, url, ip });
其他一切似乎都正確。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.