如果在子線程中使用了代碼去刷新DataGridView的數據,可能會出現滾動條卡死的問題,具體解決方法如下:
方法1:
將子線程關於DataGridView操作的這部分代碼放回主線程,在子線程中去操作DataGridView時,很容易導致DataGridView右側滾動條卡死。
方法2:
使用委托來解決,即將關於DataGridView的這部分代碼放進委托里面,DataGridView的操作仍然在子線程里面。
this.Invoke(new Action(delegate{
//綁定datagridview代碼
}));
以下是示例代碼:
private void GetSysInfo()
{
this.Invoke(new Action(delegate
{
//綁定datagridview代碼
int i = 0;
try
{
this.dgvSystem.Rows.Clear();
dList = Collect.Configuration.getInstance().DeviceList;
htCollector = ThreadManager.GetInstance().HtCollector;
foreach (string key in dList.Keys)
{
DeviceInfo deviceInfo = dList[key];
i = dgvSystem.Rows.Add();
dgvSystem.Rows[i].Cells["colSystem"].Value = deviceInfo.GetSubSystemName();
//dgvSystem.Rows[i].Cells["colInsideCode"].Value = deviceInfo.Protocol;
if (null == htCollector || 0 == htCollector.Count)
{
//dgvSystem.Rows[i].Cells["colstatus"].Value = "NoStart";
dgvSystem.Rows[i].Cells["colStarttime"].Value = "";
dgvSystem.Rows[i].Cells["colDataTime"].Value = "";
}
else
{
ClientInfo ci = ((Collector)htCollector[key]).clientInfo;
//dgvSystem.Rows[i].Cells["colstatus"].Value = ci.SysStatus;
dgvSystem.Rows[i].Cells["colStarttime"].Value = ci.StartTime.ToString();
dgvSystem.Rows[i].Cells["colDataTime"].Value = ci.LastDataTime.ToString();
}
this.dgvSystem.FirstDisplayedScrollingRowIndex = i;
}
dgvSystem.Refresh();
//開啟定時器,去定時刷新系統信息
tmSysInfo = new System.Timers.Timer(1000);
tmSysInfo.Elapsed += new ElapsedEventHandler(RefreshSysInfo);
tmSysInfo.AutoReset = true;
tmSysInfo.Enabled = true;
tmSysInfo.Start();
//dgvSystem.ColumnHeadersDefaultCellStyle.ForeColor = Color.Red;
}
catch (Exception e)
{
log.Error("FrmMain ", "GetSysInfo Error: " + e.Message);
}
}));
return;
}