Error with C# when close port

Hi guys, I'm doing a project that is receiving data from Arduino board which is than displayed onto Visual Studio 2010 C#. But currently when I click on Close port I get this error: "IOException was unhandled"

The error is pointed to the line which I have commented below

My C# codes

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO.Ports;

namespace TestClose
{
    public partial class Form1 : Form
    {
        string Data;

        public Form1()
        {
            InitializeComponent();
        }

        private void btnStart_Click(object sender, EventArgs e)
        {
            serialPort1.PortName = txtPortName.Text;
            serialPort1.BaudRate = 9600;
            serialPort1.Open();
            serialPort1.DataReceived += new SerialDataReceivedEventHandler(serialPort1_DataReceived);
            serialPort1.DataReceived += serialPort1_DataReceived;
        }

        void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            try
            {
                Data = serialPort1.ReadLine();     // ------>>> ERROR POINTED HERE
                this.Invoke(new EventHandler(displaydata_event));
            }
            catch (TimeoutException)
            {

            }
        }

        void displaydata_event(object sender, EventArgs e)
        {
            txtData.AppendText(Data + "\n");
        }

        private void btnStop_Click(object sender, EventArgs e)
        {
            serialPort1.Close();
        }
    }
}

Please help me guys, been trying to solve this issue for few days now :o
Thanks in advance!

Hello,

Add a try catch block like you did on the DataReceived event.

For example:

try
{
    serialPort1.Close();
}
catch ( IOException e )
{
    txtData.AppendText( "Close error: " + e.Message + "\n" );
}

Also see: https://msdn.microsoft.com/library/system.io.ports.serialport.close(v=vs.110).aspx

Hi guix,

I have edited it but still getting the same error

 private void btnStop_Click(object sender, EventArgs e)
        {
            try
            {
                serialPort1.Close();
            }
            catch (IOException ex2)
            {
                txtData.AppendText("Close error: " + ex2 + "\n");
            }
        }