Dec 16, 2015 Serial Number To A Datagridview in VB Net ROWINDEX ignore this: Content: aCalendar+ Android Calendar v0.99.8 No Ad.apk Air War v1 [Mod Money].apk APUS-Small,Fast,Android Boost v1.6.0 No Ad.apk. DataGridView.RowPrePaint event will be raised every time when datagridview must be repainting. This will happened for example when you drag over datagridview another form or MessageBox or when you minimize/hide form and reopen it again. In your case you need update Serial No only after count of the rows was changed.
Assuming an unbound datagrid where the row header number is for display purposes only, you can draw it dynamically and not worry about associating the number with a particular row. This assumes that changing row order (via a sort for example) should still result in sequential row numbering (it is not clear if that is the desired behavior). Private Sub DataGridView1CellPainting(sender As Object, e As DataGridViewCellPaintingEventArgs) Handles DataGridView1.CellPainting If e.ColumnIndex = -1 AndAlso e.RowIndex -1 AndAlso e.RowIndex. Assuming an unbound datagrid where the row header number is for display purposes only, you can draw it dynamically and not worry about associating the number with a particular row.
This assumes that changing row order (via a sort for example) should still result in sequential row numbering (it is not clear if that is the desired behavior). Private Sub DataGridView1CellPainting(sender As Object, e As DataGridViewCellPaintingEventArgs) Handles DataGridView1.CellPainting If e.ColumnIndex = -1 AndAlso e.RowIndex -1 AndAlso e.RowIndex.
About Questions that are asked on Forums about serial ports are complicated because of the many approaches taken with device communication and / or not having a clear understanding of the device protocol. Taking the approach presented to serial data reception removes part of the complexity, and leaves only a discussion of the protocol.
Basics This is some basic information that you know, or should know to use this code. It is not meant to insult your intelligence; just bear in mind that not all readers of this have the same knowledge level.
Modern PC’s have multiple cores and can execute multiple threads at the same time. Take advantage of this. Only one SerialPort event handler can execute at a time. There are three operational. When the SerialPort DataReceived event fires there may or may not be an entire protocol data unit (PDU or message) available. This is a common forum question and one that used to stumped me.
SerialPort reads are blocking except ReadExisting. SerialPort communication can take one of three forms. non-polled – the serial port receives data unsolicited. This means that the device that is attached to the serial port sends messages without being asked to. My GPS device does this. As soon as it is connected it starts sending NMEA messages.
polled - the device that is attached to the serial port sends messages only in response to the receipt of a message from the application. Combination of both of the above. You must know the protocol of the device you are communicating with. Windows form controls can only be manipulated from the UI thread, and UI control updating is inherently slow.
Threading and ResetEvent classes. The difficulty people have using the serial port tends to be with receiving data. As I worked with different devices I kept searching for THE answer to receiving data. What is presented below is as close as I have come to THE answer. This code has been used for:. PC – Loopback – PC communicating with itself for testing.
PC – PC – PC communicating with another PC. PC – GPS – retrieval of NMEA messages. PC as ASCII terminal. PC – microcontroller.
etc. BaudRate The speed of the serial port is set using the BaudRate property, and is set based on the device you are connected to. This number represents the maximum amount of data that can be received in one second. If the BaudRate is 19200 the maximum bytes per second your application has to be able to process is 2400 bytes per second. Or 1 byte every 0.000416 seconds, If the BaudRate is 115200 the maximum bytes per second your application has to be able to process is 14400 bytes per second. Or 1 byte every 0.000069 seconds, Those are the maximum rates possible but the actual rate can be much slower depending on the device you are attached to. In reality your application will read between 1 and n bytes depending on how the application is structured, and these bytes are further packaged into PDU’s.
If your application is presenting the data to the user you have to ask yourself if the user interface can be updated at the actual PDU arrival rate, and if it can’t what do you do↑ Code Overview The structure of the code is:. Three event handlers that do as little as possible to communicate with the background threads without the loss of data. Threading.AutoResetEvents are used for this communication. Three background threads that do most of the work.
a thread to accumulate the bytes received from the port into a buffer. This code reads bytes only! This code is rarely changed. a thread to process PDU’s. The base code just removes the bytes from the buffer. This is just a placeholder because most of the coding for every new application occurs here. a thread to deal with pin changed and error events.
This code is changed as needed by the protocol and application. The base code just removes the items from the queue.
Code to start the threads, configure and open the port, and code to stop the threads and close the port. Guiding principles:. handlers do a minimum of work. make use of as many cores as possible.
no blocking serial port methods are executed on the UI The base code as a forms project is included below and is also available for download. Here are short movies showing the simulated complex PDU code running. The first movie is the general flow of the program, and the second is a more detailed look at data reception. Here is what the UI looks like. If you do not have a loopback plug I highly recommend you get one(see references). They are inexpensive and as you will see it is sometimes useful to talk to yourself.
You can create a simple loopback for RS232 DB9 / DB25 by connecting pins two and three together; be careful not to short the pins to the case. Receive Data Flow This is the basic flow of data through the code. Other than several threads running this code is not complicated. Data from the serial port is first read into a Windows-created buffer. The size of that buffer is controlled by the ReadBufferSize property. The code is notified that there are bytes to read by the firing of the DataReceived event. The DataReceived event handler sets an AutoResetEvent that causes the Receive method to execute.
The Receive method reads all available bytes. Bytes read are accumulated into a list of bytes, RcvBuffer.
This method then sets another AutoResetEvent that causes the Protocol method to execute. Since RcvBuffer can be modified by more than one method access to it is controlled using thread synchronization. The Protocol method determines if there are PDU’s, and removes the PDU bytes from RcvBuffer. The PDU’s are then processed. Based on how the code is written this is where most, if not all, application code is written. +-+ +-+ +-+ Serial Bytes Windows Device +-+ Port +-+ Buffer +-+ +-+ +-+ +-+ DataReceived Receive method+- signal +-+Protocol method +-+ +-+ ^ v + bytes bytes to from + ^ +-+ +- RcvBuffer +-+ list of bytes +-+ ↑ Code Discussion The code presented is:.
the common code that works in all environments, forms or console, in this case a form application. a device emulator that constantly sends PDU’s. a couple of protocol handlers to process the PDU’s #Region directives are used to organize the code and are used to direct the conversation.
Common Objects and Variables This section of code contains the serial port object and variables used throughout. The primary buffer and its lock object are defined here. Also a ConcurrentQueue of Object is defined for pin changes and errors. There are three threads defined with a corresponding AutoResetEvent to control event firing.
In addition there is a ManualResetEvent that controls general thread execution. Variables used for instrumentation are defined here. A variable to control instrumentation collection is defined. Their meaning can be ascertained by usage.
Handlers DataReceived – this handler first check is to see the event type is SerialData.Eof. This event type is ignored. If the event type is SerialData.Chars rcvARE, the AutoResetEvent that control the Receive method, is set. ErrorReceived – the SerialErrorReceivedEventArgs are added to a queue that holds both errors and pin event arguments.
The AutoResetEvent that control the PinsAndErrors method, is set. PinChanged - the SerialPinChangedEventArgs are added to a queue that holds both errors and pin event arguments. The AutoResetEvent that control the PinsAndErrors method, is set. Receive method This method is responsible for reading all available bytes from the serial port.
These bytes are accumulated into RcvBuffer for processing by the Protocol method. This method is ran on a separate thread that is started before the port is opened, and is in a loop until runThreads is reset. Until rcvARE is set by the DataReceived event handler the thread is blocked by this line rcvARE.WaitOne near the end of the method. When rcvARE is set by the DataReceived event handler the code checks to see if runThreads is set.
If it is then the loop executes otherwise the thread ends. RcvReadCT is set to zero. This tracks how many times the loop that follows it executes for one firing of the DataReceived event handler. The inner do loop continually executes while the port is open and there are bytes to read. The number of bytes to read is determined and a temporary array large enough to hold that number of bytes is created.
The bytes are then read. Note that the serial port read returns the number of bytes actually read which can be less than the number of bytes available. If that is the case the temporary buffer is resized.
Next the temporary buffer is added to the primary buffer, RcvBuffer, which is protected by rcvBufLock. RcvReadCT is incremented.
AutoResetEvent protoARE is set after the first read and if there are multiple reads, which causes the Protocol method to execute. Which brings the code back to rcvARE.WaitOne, blocking until another DataReceived event happens. Instrumentation lines were skipped in the discussion. They start with If RcvInstr Then. RcvInstr is a Boolean that controls whether or not to do instrumentation.
PinsAndErrors method This method is responsible for processing serial port errors and pin changes. This method is ran on a separate thread that is started before the port is opened, and is in a loop until runThreads is reset.
Until pinsErrorsARE is set the thread is blocked by this line pinsErrorsARE.WaitOne near the end of the method. When pinsErrorsARE is set the code checks to see if runThreads is set.
If it is then the loop executes otherwise the thread ends. The code in this method is a prototype that can be tailored based on the application. As written the queue is emptied and a Debug statement is used to report the error.
The exception to this is SerialError.Overrun. This is a hardware error and the method discards the input buffer when this occurs. Open / Close SerialPortOpen method This method is responsible for opening the port and starting the threads. The threads are started by a call to the StartSerialPortThreads method. Then the ports settings are defined. These setting must match the device that you are connected to.
Settings of Interest. ReceivedBytesThreshold – one is the default, recommend no change unless absolutely needed. ReadTimeout - default is infinite if not set. Recommend some value. WriteTimeout - default is infinite if not set. Recommend some value.
ReadBufferSize - Windows-created input buffer 4096 is default, change if needed. WriteBufferSize - Windows-created output buffer 2048 is default, change if needed. Encoding – this is important if you are using character based read / write methods. The code provided uses byte read methods so this setting has no affect.
If you are using writes that are character based this setting should match the attached devices encoding. StartSerialPortThreads method This method is responsible for starting the background threads used by the serial port.
This method resets the AutoResetEvents, then creates and starts the background threads. Before starting the threads runThreads is set to the run state. ↑ SerialPortClose method This method is responsible for closing the port and stopping the threads. At the end of each of the threads is Loop While runThreads.WaitOne(0).
The first thing this method does is to Reset runThreads which causes the Loop While to fail, thus ending the thread. To make sure that the threads get to the Loop While their individual AutoResetEvent’s are then Set. Once those steps are taken all of the threads are joined and the port is closed. If the application is ending this method should be called with True which causes the ResetEvent’s to be disposed. Protocol (Region App specific) At this point if you use the code discussed so far and connect to a device what you would see is all of the bytes received from the device in RcvBuffer.
(If the device needs to be polled to get it to send add that in a button.) What is needed now is a Protocol method to see that. Here is a simple version. End Sub Give it a try with a breakpoint set inside the loop. Each time the break is encountered examine RcvBuffer.
You will see that the data from the device is being accumulated into RcvBuffer and if you let the code run long enough it will run out of memory. Not very useful. Lets look at another example.
Included with the code is a class, PDUCommon. Also included is another class, LinePDU, that inherits PDUCommon.
LinePDU retrieves messages from RcvBuffer that end with the ControlChars.Lf. Here is a Protocol method for receiving lines. End Sub What you do with the lines received is up to you. Another PDU that is simulated in the code provided looks like this (see Movie above).
STX = one byte = 2. ID = four bytes = sequence. DL = one byte = length of data (1 - 255). data - string.