Hi all,
I am writing a piece of code which will simply receive the data in UART(serial port) and populate the same in the Datagrid control. whenever it receives the data, it has to add a new row in the DataGrid control.
But when i tried writing the code it throwed me a error which i couldn't resolve and when i googled everyone talks about threading concept for this issue, which i am not aware or could not understand.
Error: "An unhandled exception of type 'System.InvalidOperationException' occurred in System.Windows.Forms.dll
Additional information: Cross-thread operation not valid: Control '' accessed from a thread other than the thread it was created on."
code snippet is attached for reference
DALIComm - Instance of Serialport DALIDataGrid - Instance of Datagrid
private void DALIComm_DataReceived(object sender, SerialDataReceivedEventArgs e) { // Process received data byte[] buffer = new byte[2];//DALIComm.BytesToRead]; int bytesRead = DALIComm.Read(buffer, 0, buffer.Length); strNewRowData[4] = Convert.ToBase64String(buffer); bUpdateDataGrid = true; AddNewRow(); }
public void AddNewRow() { if(bUpdateDataGrid) { DateTime TempData; long DeltaTime; gu32SerialNumber++; strNewRowData[0] = gu32SerialNumber.ToString(); strNewRowData[1] = System.DateTime.Now.ToShortDateString(); TempData = System.DateTime.Now; TimeSpan span = TempData.Subtract(Convert.ToDateTime(strNewRowData[2])); DeltaTime = (long)span.TotalMilliseconds; strNewRowData[3] = Convert.ToString(DeltaTime); strNewRowData[2] = TempData.ToString("hh:mm:ss.fff tt"); strNewRowData[5] = "1"; DALIDataGrid.Rows.Add(strNewRowData); bUpdateDataGrid = false; } }
Error on the line which is highlighted in bold and size-4.
|
Is there a simply to fix this issue? Thank you very much in advance.