Visual studio form not able to receive the data from Arduino when first connected to usb

I am using visual studio forms application to log the data received from Arduino every , and was able to log the data and plot it on the graph , i am facing a issue that when i am first time connecting Arduino Every board to USB port i am not able to send data from visual studio to Arduino, I have to first disconnect serial communication with visual studio and open the serial monitor in Arduino IDE given the user input then Arduino start receiving data after this if i close the Serial monitor of Arduino Ide and start serial communication with visual studio form application ,visual studio is able to send data to the Arduino and receive the data .
i am not able to figure out what the issue is?

Arduino Every code

#include <SPI.h> // include the SPI library
#include<Wire.h> // include the I2C library

#define Addr 0x4C
unsigned int LED_intensity_val=40000;  // Max value is 65535
unsigned int V_dac=0;  // Max value is 65535
unsigned int lsb,msb; 
int state=0;
char incomingByte; 
uint8_t data[2];



unsigned int result[4];
const int Conv_Pin = 8;
const int Busy_Pin = 9;
const int G0 = 2;
const int G1 = 3;
const int G2 = 4;
const int G3 = 5;
const int G4 = 6;

unsigned long digital_value = 0;
int conv_times = 2041;
int delay_time = 0;
int gain_change =1;
int LED_intensity_change = 0;
void setup() {
 Serial.begin(9600);
 Serial.setTimeout(1000);
 
  pinMode(G0, OUTPUT);
  pinMode(G1, OUTPUT);
  pinMode(G2, OUTPUT);
  pinMode(G3, OUTPUT);
  pinMode(G4, OUTPUT);
  digitalWrite(G0, HIGH);
  digitalWrite(G1, HIGH);
  digitalWrite(G2, LOW);
  digitalWrite(G3, LOW);
  digitalWrite(G4, LOW);
 // Serial.println("Gain set to 1");
//  Serial.println("Set another gain value => ");
 // start the SPI library:
 SPI.begin();
 // start the SPI library:
 Wire.begin();
 SPI.setBitOrder(MSBFIRST); // data is clocked in MSB first
 SPI.setDataMode(SPI_MODE0); // SCLK idle low (CPOL=0), MOSI read on rising edge (CPHI=0)
 SPI.setClockDivider(SPI_CLOCK_DIV16); // set SPI clock at 1 MHz. Arduino xtal = 16 MHz
// initalize the  start coversion and busy check select pins:
  pinMode(Busy_Pin, INPUT);
  pinMode(Conv_Pin, OUTPUT);
  digitalWrite(Conv_Pin, LOW);
  delay(1);
}

void loop() {
//Serial.println("Starting conversion");
//delay(1000);
if (Serial.available() > 0) {
//    char buffer[] = {' ',' ',' ',' '}; // Receive up to 4 bytes
//    while (!Serial.available()); // Wait for characters
//    Serial.readBytesUntil('\n', buffer, 4);
//    int gainval = atoi(buffer);
String input_set = Serial.readString();
int input_length=input_set.length();
//Serial.println(input_length);
//Serial.println(input_set);

for(int j=0;j<input_length;j=j+3)
{ 
  String gain="";
  gain = input_set.substring(j,j+2);
 int  gainval=gain.toInt();
// Serial.println(gainval);
  
    switch(gainval){

      case 0:
              digitalWrite(G0, LOW);
              digitalWrite(G1, LOW);
              digitalWrite(G2, LOW);
              digitalWrite(G3, LOW);
              digitalWrite(G4, LOW);
//              delay_time =0;
//              gain_change =1;
              LED_intensity_change = 1;
              V_dac = LED_intensity_val;
              adc_cal();
              Serial.print(gainval);
              Serial.println("B");
             // Serial.println("Gain set to 0.125");
//              Serial.println("Set another gain value => ");
              break;
     case 1:
              digitalWrite(G0, HIGH);
              digitalWrite(G1, LOW);
              digitalWrite(G2, LOW);
              digitalWrite(G3, LOW);
              digitalWrite(G4, LOW);
//              delay_time =0;
//              gain_change =1;
              LED_intensity_change = 1;
              V_dac = LED_intensity_val;
              adc_cal();
              Serial.print(gainval);
              Serial.println("B");
             // Serial.println("Gain set to 0.25");
//              Serial.println("Set another gain value => ");
              break;
     case 2:
              digitalWrite(G0, LOW);
              digitalWrite(G1, HIGH);
              digitalWrite(G2, LOW);
              digitalWrite(G3, LOW);
              digitalWrite(G4, LOW);
//              delay_time =0;
//              gain_change =1;
              LED_intensity_change = 1;
              V_dac = LED_intensity_val;
               adc_cal();
              Serial.print(gainval);
              Serial.println("B");
            //  Serial.println("Gain set to 0.5");
//              Serial.println("Set another gain value => ");
              break;
     case 3:
              digitalWrite(G0, HIGH);
              digitalWrite(G1, HIGH);
              digitalWrite(G2, LOW);
              digitalWrite(G3, LOW);
              digitalWrite(G4, LOW);
//              delay_time =0;
//              gain_change =1;
              LED_intensity_change = 1;
              V_dac = LED_intensity_val;
               adc_cal();
              Serial.print(gainval);
              Serial.println("B");
            //  Serial.println("Gain set to 1");
//              Serial.println("Set another gain value => ");
              break;
     case 4:
              digitalWrite(G0, LOW);
              digitalWrite(G1, LOW);
              digitalWrite(G2, HIGH);
              digitalWrite(G3, LOW);
              digitalWrite(G4, LOW);
//              delay_time =0;
//              gain_change =1;
              LED_intensity_change = 1;
              V_dac = LED_intensity_val;
               adc_cal();
              Serial.print(gainval);
              Serial.println("B");
             // Serial.println("Gain set to 2");
//              Serial.println("Set another gain value => ");
              break;
     case 5:
              digitalWrite(G0, HIGH);
              digitalWrite(G1, LOW);
              digitalWrite(G2, HIGH);
              digitalWrite(G3, LOW);
              digitalWrite(G4, LOW);
//              delay_time =0;
//              gain_change =1;
              LED_intensity_change = 1;
              V_dac = LED_intensity_val;
               adc_cal();
              Serial.print(gainval);
              Serial.println("B");
//              Serial.println("Gain set to 4");
//              Serial.println("Set another gain value => ");
              break;
     case 6:
              digitalWrite(G0, LOW);
              digitalWrite(G1, HIGH);
              digitalWrite(G2, HIGH);
              digitalWrite(G3, LOW);
              digitalWrite(G4, LOW);
//              delay_time =0;
//              gain_change =1;
              LED_intensity_change = 1;
              V_dac = LED_intensity_val;
               adc_cal();
              Serial.print(gainval);
              Serial.println("B");
//              Serial.println("Gain set to 8");
//              Serial.println("Set another gain value => ");
              break;
     case 7:
              digitalWrite(G0, HIGH);
              digitalWrite(G1, HIGH);
              digitalWrite(G2, HIGH);
              digitalWrite(G3, LOW);
              digitalWrite(G4, LOW);
//              delay_time =0;
//              gain_change =1;
              LED_intensity_change = 1;
              V_dac = LED_intensity_val;
               adc_cal();
              Serial.print(gainval);
              Serial.println("B");
//              Serial.println("Gain set to 16");
//              Serial.println("Set another gain value => ");
              break;
     case 8:
              digitalWrite(G0, LOW);
              digitalWrite(G1, LOW);
              digitalWrite(G2, LOW);
              digitalWrite(G3, HIGH);
              digitalWrite(G4, LOW);
//              delay_time =0;
//              gain_change =1;
              LED_intensity_change = 1;
              V_dac = LED_intensity_val;
               adc_cal();
              Serial.print(gainval);
              Serial.println("B");
//              Serial.println("Gain set to 32");
//              Serial.println("Set another gain value => ");
              break;
     case 9:
              digitalWrite(G0, HIGH);
              digitalWrite(G1, LOW);
              digitalWrite(G2, LOW);
              digitalWrite(G3, HIGH);
              digitalWrite(G4, LOW);
//              delay_time =0;
//              gain_change =1;
              LED_intensity_change = 1;
              V_dac = LED_intensity_val;
               adc_cal();
              Serial.print(gainval);
              Serial.println("B");
//              Serial.println("Gain set to 64");
//              Serial.println("Set another gain value => ");
              break;
     case 10:
              digitalWrite(G0, LOW);
              digitalWrite(G1, HIGH);
              digitalWrite(G2, LOW);
              digitalWrite(G3, HIGH);
              digitalWrite(G4, LOW);
//              delay_time =0;
//              gain_change =1;
              LED_intensity_change = 1;
              V_dac = LED_intensity_val;
               adc_cal();
              Serial.print(gainval);
              Serial.println("B");
//              Serial.println("Gain set to 128");
//              Serial.println("Set another gain value => ");
              break;
     case 16:
              digitalWrite(G0, LOW);
              digitalWrite(G1, LOW);
              digitalWrite(G2, LOW);
              digitalWrite(G3, LOW);
              digitalWrite(G4, HIGH);
//              delay_time =0;
//              gain_change =1;
              LED_intensity_change = 1;
              V_dac = LED_intensity_val;
               adc_cal();
              Serial.print(gainval);
              Serial.println("B");
//              Serial.println("Gain set to 0.172");
//              Serial.println("Set another gain value => ");
              break;
     case 17:
              digitalWrite(G0, HIGH);
              digitalWrite(G1, LOW);
              digitalWrite(G2, LOW);
              digitalWrite(G3, LOW);
              digitalWrite(G4, HIGH);
//              delay_time =0;
//              gain_change =1;
              LED_intensity_change = 1;
              V_dac = LED_intensity_val;
               adc_cal();
              Serial.print(gainval);
              Serial.println("B");
//              Serial.println("Gain set to 0.344");
//              Serial.println("Set another gain value => ");
              break;
     case 18:
              digitalWrite(G0, LOW);
              digitalWrite(G1, HIGH);
              digitalWrite(G2, LOW);
              digitalWrite(G3, LOW);
              digitalWrite(G4, HIGH);
//              delay_time =0;
//              gain_change =1;
              LED_intensity_change = 1;
              V_dac = LED_intensity_val;
               adc_cal();
              Serial.print(gainval);
              Serial.println("B");
//              Serial.println("Gain set to 0.688");
//              Serial.println("Set another gain value => ");
              break;
     case 19:
              digitalWrite(G0, HIGH);
              digitalWrite(G1, HIGH);
              digitalWrite(G2, LOW);
              digitalWrite(G3, LOW);
              digitalWrite(G4, HIGH);
//              delay_time =0;
//              gain_change =1;
              LED_intensity_change = 1;
              V_dac = LED_intensity_val;
               adc_cal();
              Serial.print(gainval);
              Serial.println("B");
//              Serial.println("Gain set to 1.375");
//              Serial.println("Set another gain value => ");
              break;
     case 20:
              digitalWrite(G0, LOW);
              digitalWrite(G1, LOW);
              digitalWrite(G2, HIGH);
              digitalWrite(G3, LOW);
              digitalWrite(G4, HIGH);
//              delay_time =0;
//              gain_change =1;
              LED_intensity_change = 1;
              V_dac = LED_intensity_val;
               adc_cal();
              Serial.print(gainval);
              Serial.println("B");
//              Serial.println("Gain set to 2.75");
//              Serial.println("Set another gain value => ");
              break;
     case 21:
              digitalWrite(G0, HIGH);
              digitalWrite(G1, LOW);
              digitalWrite(G2, HIGH);
              digitalWrite(G3, LOW);
              digitalWrite(G4, HIGH);
//              delay_time =0;
//              gain_change =1;
              LED_intensity_change = 1;
              V_dac = LED_intensity_val;
               adc_cal();
              Serial.print(gainval);
              Serial.println("B");
//              Serial.println("Gain set to 5.5");
//              Serial.println("Set another gain value => ");
              break;
     case 22:
              digitalWrite(G0, LOW);
              digitalWrite(G1, HIGH);
              digitalWrite(G2, HIGH);
              digitalWrite(G3, LOW);
              digitalWrite(G4, HIGH);
//              delay_time =0;
//              gain_change =1;
              LED_intensity_change = 1;
              V_dac = LED_intensity_val;
               adc_cal();
              Serial.print(gainval);
              Serial.println("B");
//              Serial.println("Gain set to 11");
//              Serial.println("Set another gain value => ");
              break;
     case 23:
              digitalWrite(G0, HIGH);
              digitalWrite(G1, HIGH);
              digitalWrite(G2, HIGH);
              digitalWrite(G3, LOW);
              digitalWrite(G4, HIGH);
//              delay_time =0;
//              gain_change =1;
              LED_intensity_change = 1;
              V_dac = LED_intensity_val;
               adc_cal();
              Serial.print(gainval);
              Serial.println("B");
//              Serial.println("Gain set to 22");
//              Serial.println("Set another gain value => ");
              break;
     case 24:
              digitalWrite(G0, LOW);
              digitalWrite(G1, LOW);
              digitalWrite(G2, LOW);
              digitalWrite(G3, HIGH);
              digitalWrite(G4, HIGH);
//              delay_time =0;
//              gain_change =1;
              LED_intensity_change = 1;
              V_dac = LED_intensity_val;
               adc_cal();
              Serial.print(gainval);
              Serial.println("B");
//              Serial.println("Gain set to 44");
//              Serial.println("Set another gain value => ");
              break;
     case 25:
              digitalWrite(G0, HIGH);
              digitalWrite(G1, LOW);
              digitalWrite(G2, LOW);
              digitalWrite(G3, HIGH);
              digitalWrite(G4, HIGH);
//              delay_time =0;
//              gain_change =1;
              LED_intensity_change = 1;
              V_dac = LED_intensity_val;
               adc_cal();
              Serial.print(gainval);
              Serial.println("B");
//              Serial.println("Gain set to 88");
//              Serial.println("Set another gain value => ");
              break;
     case 26:
              digitalWrite(G0, LOW);
              digitalWrite(G1, HIGH);
              digitalWrite(G2, LOW);
              digitalWrite(G3, HIGH);
              digitalWrite(G4, HIGH);
//              delay_time =0;
//              gain_change =1;
              LED_intensity_change = 1;
              V_dac = LED_intensity_val;
               adc_cal();
              Serial.print(gainval);
              Serial.println("B");
//              Serial.println("Gain set to 176");
//              Serial.println("Set another gain value => ");
              break;
     default:
//          Serial.println("Invalid gain Value");
//          Serial.println("Set another gain value => ");
          break;  
    }
}
}
}

void adc_cal()
{

uint8_t data[2];
data[1]= V_dac;
data[0]= V_dac >> 8; 
lsb = data[1];
msb = data[0];
  // Start I2C transmission
  Wire.beginTransmission(Addr);
  // Select DAC and input register
  Wire.write(0x30);
  // Write data = 0x8000(32768)
  // data msb = 0x80
  Wire.write(data[0]);
  // data lsb = 0x00
  Wire.write(data[1]);
  // Stop I2C transmission
  Wire.endTransmission();

  
//Serial.print("call ack");
for(int z=0;z<=10;z++)
{
for(int k=0; k <= conv_times; k++)
{
digitalWrite(Conv_Pin, HIGH);
delayMicroseconds(1);
digitalWrite(Conv_Pin, LOW); // conversion puse of one microsecond
delayMicroseconds(1);
}
result[0] = SPI.transfer(0x00);
result[1] = SPI.transfer(0x00);
result[2] = SPI.transfer(0x00);
//Serial.println("end of data aquiring");
//Serial.println("results are");

//Serial.println(result[0]);
//Serial.println(result[1]);
//Serial.println(result[2]);

//Serial.println(result[0],BIN);
//Serial.println(result[1],BIN);
//Serial.println(result[2],BIN);

digital_value = 0 ;
digital_value = result[0] ;
//Serial.println(digital_value);
digital_value = digital_value << 8;
//Serial.println(digital_value);
digital_value |= result[1] ;
//Serial.println(digital_value);
digital_value = digital_value << 8;
digital_value |= result[2] ;
//Serial.println(digital_value);
//Serial.println(digital_value,HEX);
//Serial.println(digital_value,BIN);
if( digital_value < 8388608)
{
digital_value = 8388608 + digital_value;
//digital_value = digital_value-8000000;
}
else
{
digital_value = 8388607 -(16777215-digital_value);
//digital_value = digital_value-8000000;
}

//Serial.println(digital_value);
//if((delay_time >= 10) && (gain_change == 1))
//{
// //Serial.print(delay_time);
// Serial.print(digital_value); 
// Serial.println("A");
// gain_change =0;
 LED_intensity_change = 1;
// V_dac = 0;
//}
//else
//{
// delay_time++; 
//}

//if(LED_intensity_change == 1)
//{
////  Serial.println("led=");
// // Serial.println(V_dac);
//uint8_t data[2];
//data[1]= V_dac;
//data[0]= V_dac >> 8; 
//lsb = data[1];
//msb = data[0];
//  // Start I2C transmission
//  Wire.beginTransmission(Addr);
//  // Select DAC and input register
//  Wire.write(0x30);
//  // Write data = 0x8000(32768)
//  // data msb = 0x80
//  Wire.write(data[0]);
//  // data lsb = 0x00
//  Wire.write(data[1]);
//  // Stop I2C transmission
//  Wire.endTransmission();
//
//  // Convert the data, Vref = 5 V
//  double voltage = (((msb * 256) + lsb) / 65536.0) * 2.5;
//
//  // Output data to serial monitor
////  Serial.print("Voltage : ");
////  Serial.println(voltage,4);
//  LED_intensity_change =0;
//}
}
Serial.print(digital_value);
Serial.print("A");
V_dac = 0;
//uint8_t data[2];
data[1]= V_dac;
data[0]= V_dac >> 8; 
lsb = data[1];
msb = data[0];
  // Start I2C transmission
  Wire.beginTransmission(Addr);
  // Select DAC and input register
  Wire.write(0x30);
  // Write data = 0x8000(32768)
  // data msb = 0x80
  Wire.write(data[0]);
  // data lsb = 0x00
  Wire.write(data[1]);
  // Stop I2C transmission
  Wire.endTransmission();
}

Visual Studio code

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.IO;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Windows.Forms.DataVisualization.Charting;

namespace Data_logger
{
    
    public partial class Form1 : Form
    {
        string serialDataIn;
        Int32 indexOfA;
        Int32 indexOfB;
        string VoltageText,VoltageGraph;
        string GainText,GainGraph;
        Int32 Vout;
       string time;
        Int32 gain_receive;
        string SolutionText ;
        int checkBoxCount;
        






        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            button_open.Enabled = true;
            button_close.Enabled = false;
            button_Gain.Enabled = false;
            button_Gain_Select.Enabled = true;

            verticalProgressBar_StatusCom.Value = 0;
            comboBox_BaudRate.Text = "9600";
            comboBox_Solution.Text = "1";

           
            label6.Text = DateTime.Now.ToLongDateString();
            
           
          

            chart1.Series["Solution1"].Points.AddXY(1, 1);
            chart1.Series["Solution2"].Points.AddXY(1, 1);
            chart1.Series["Solution3"].Points.AddXY(1, 1);
            chart1.Series["Solution4"].Points.AddXY(1, 1);
            chart1.Series["Solution5"].Points.AddXY(1, 1);
            chart1.Series["Solution6"].Points.AddXY(1, 1);
            chart1.Series["Solution7"].Points.AddXY(1, 1);
            chart1.Series["Solution8"].Points.AddXY(1, 1);


        }

        private void comboBox_ComPort_DropDown(object sender, EventArgs e)
        {
            string[] portlists = System.IO.Ports.SerialPort.GetPortNames();
            comboBox_ComPort.Items.Clear();
            comboBox_ComPort.Items.AddRange(portlists);

          

        }

        private void button_open_Click(object sender, EventArgs e)
        {
            try
            {
                serialPort1.PortName = comboBox_ComPort.Text;
                serialPort1.BaudRate = Convert.ToInt32(comboBox_BaudRate.Text);
                serialPort1.Open();

                timer1.Start();
                label5.Text = DateTime.Now.ToLongTimeString();
               


                chart1.Series["Solution1"].Points.Clear();
                chart1.Series["Solution2"].Points.Clear();
                chart1.Series["Solution3"].Points.Clear();
                chart1.Series["Solution4"].Points.Clear();
                chart1.Series["Solution5"].Points.Clear();
                chart1.Series["Solution6"].Points.Clear();
                chart1.Series["Solution7"].Points.Clear();
                chart1.Series["Solution8"].Points.Clear();






                button_open.Enabled = false;
                button_close.Enabled = true;
                button_Gain.Enabled = true;
                button_Gain_Select.Enabled = true;

                verticalProgressBar_StatusCom.Value = 100;
                MessageBox.Show("Successfully Connected");

            }
            catch(Exception error)
            {
                MessageBox.Show(error.Message);
            }
        }

        private void groupBox1_Enter(object sender, EventArgs e)
        {

        }

        private void button_close_Click(object sender, EventArgs e)
        {
            try
            {
               
                serialPort1.Close();

                button_open.Enabled = true;
                button_close.Enabled = false;
                button_Gain.Enabled = false;
                button_Gain_Select.Enabled = true;
               
                verticalProgressBar_StatusCom.Value = 0;
                timer1.Stop();
               
                MessageBox.Show("Disconnected");

            }
            catch (Exception error)
            {
                MessageBox.Show(error.Message);
            }

        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            label5.Text = DateTime.Now.ToLongTimeString();
            timer1.Start();

        }
        private void button_Gain_Select_Click(object sender, EventArgs e)
        {
            textBox_GainSet.Clear();
            int item_count = checkedListBox_Gain_Multi.CheckedItems.Count;
            for (int j = 0; j < checkedListBox_Gain_Multi.CheckedItems.Count; j++)
            {
                if(j<=(item_count-2))
                {
                    textBox_GainSet.Text += checkedListBox_Gain_Multi.CheckedItems[j] + ",";

                }
                else
                {
                    textBox_GainSet.Text += checkedListBox_Gain_Multi.CheckedItems[j];

                }

            }
        }

    

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (serialPort1.IsOpen)
            { 
                try
                {

                    serialPort1.Close();

                }
                catch (Exception error)
                {
                    MessageBox.Show(error.Message);
                }
            }

        }

        private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
        {
            serialDataIn = serialPort1.ReadLine();
            this.BeginInvoke(new EventHandler(ProcessData));
            this.BeginInvoke(new EventHandler(ShowData));
        }

        private void ShowData(object sender, EventArgs e)
        {
            
            switch (comboBox_Solution.Text)
            {
                case "1":
                    chart1.Series["Solution1"].Points.AddXY(gain_receive, Vout);
                    
                    break;
                case "2":
                    chart1.Series["Solution2"].Points.AddXY(gain_receive, Vout);
                    break;
                case "3":
                    chart1.Series["Solution3"].Points.AddXY(gain_receive, Vout);
                    break;
                case "4":
                    chart1.Series["Solution4"].Points.AddXY(gain_receive, Vout);
                    break;
                case "5":
                    chart1.Series["Solution5"].Points.AddXY(gain_receive, Vout);
                    break;
                case "6":
                    chart1.Series["Solution6"].Points.AddXY(gain_receive, Vout);
                    break;
                case "7":
                    chart1.Series["Solution7"].Points.AddXY(gain_receive, Vout);
                    break;
                case "8":
                    chart1.Series["Solution8"].Points.AddXY(gain_receive, Vout);
                    break;


            }

        }

       

        private void ProcessData(object sender, EventArgs e)
        {
            try
            {
                indexOfA = Convert.ToInt32(serialDataIn.IndexOf("A"));
                indexOfB = Convert.ToInt32(serialDataIn.IndexOf("B"));

                VoltageText = serialDataIn.Substring(0, indexOfA);
                VoltageGraph = serialDataIn.Substring(0, (indexOfA));
                GainText = serialDataIn.Substring(indexOfA + 1, (indexOfB - indexOfA) - 1);
                GainGraph = serialDataIn.Substring(indexOfA + 1, (indexOfB - indexOfA) - 1);

                textBox_Voltage.Text = VoltageText;
                textBox_Voltage.Refresh();
                textBox_Gain.Text = GainText;
                textBox_Gain.Refresh();
              
                Vout = Convert.ToInt32(VoltageGraph);
                gain_receive = Convert.ToInt32(GainGraph);
                time = DateTime.Now.ToLongTimeString();
                SolutionText = comboBox_Solution.Text;
                addRecord(time, VoltageText, GainText, SolutionText, @"C:\Users\Admin\Documents\MyLab\data1.csv");
               
              

            }
            catch (Exception error)
            {
                MessageBox.Show(error.Message);
            }
            
      
        }

        private void button_Gain_Click_1(object sender, EventArgs e)
        {
            // Actions performed when gain Select button is pressed
            try
            {
                checkBoxCount = checkedListBox_Gain_Multi.CheckedItems.Count;
                GainText = textBox_GainSet.Text;
                serialPort1.Write(GainText);           // a string foramt of G1,G2,G3,\n will be send to the serial port
                textBox_GainSet.Clear();
                // gain = Convert.ToInt32(textBox_GainSet.Text);
                /* gain++;
                 if (gain > 8)
                 {
                     gain = 0;
                 }
                 textBox_GainSet.Text = Convert.ToString(gain);
                */

            }
            catch (Exception error)
            {
                MessageBox.Show(error.Message);
            }

        }

        public static void addRecord(string time , string VoltageText, string GainText, string SolutionText, string filepath)
        {
            try
            {
                using (System.IO.StreamWriter File = new System.IO.StreamWriter(@filepath, true))
                {
                    File.WriteLine(time + "," + VoltageText + "," + GainText + "," + SolutionText);
                }
                 
            }
            catch(Exception error)
            {

                MessageBox.Show(error.Message);

            }
        }
        private void chart1_MouseMove(object sender, MouseEventArgs e)
        {
            try
            {
                Point mousePoint = new Point(e.X, e.Y);

                chart1.ChartAreas[0].CursorX.Interval = 0;
                chart1.ChartAreas[0].CursorY.Interval = 0;

                chart1.ChartAreas[0].CursorX.SetCursorPixelPosition(mousePoint, true);
                chart1.ChartAreas[0].CursorY.SetCursorPixelPosition(mousePoint, true);

                label7.Text = "pixel X position " + chart1.ChartAreas[0].AxisX.PixelPositionToValue(e.X).ToString();
                label8.Text = "pixel y position " + chart1.ChartAreas[0].AxisY.PixelPositionToValue(e.Y).ToString();

            }
            catch (Exception error)
            {
                MessageBox.Show(error.Message);


            }

            

            



        }
    }
}

GUI

Note in advance: I'm not familiar with the Nano Every.

So it workend in the past and now no longer works as expected? Did you change anything in the Arduino code or VS code?

Is your problem happening after an upload or when the Arduino code is already running?

To verify the sequence of events

  1. You connect the Arduino to the PC.
  2. You start your PC application.
  3. You select and open the serial port; port opens succesfully but you can not communicate.
  4. You close the serial port.
  5. You open serial monitor and send data to the Arduino Every.
  6. You close the serial monitor.
  7. You start your application.
  8. You select and open the serial port; you can now communicate.

Can you test with a normal terminal program like hyperterm, realterm, teraterm etc; just in case serial monitor does something special?

What happens if you open/close the port in the PC application and next open again?

How do you know? Does the PC application throw an exception? Don't you see the RX led (is there one) on the Nano Every flash?

Note
I haven't looked in depth at your code.

  1. You connect the Arduino to the PC.
  2. You start your PC application.
  3. You select and open the serial port; port opens succesfully but you can not communicate.
  4. You close the serial port.
  5. You open serial monitor and send data to the Arduino Every.
  6. You close the serial monitor.
  7. You start your application.
  8. You select and open the serial port; you can now communicate.

This is what is actually happening.
i am not able to figure out what the issue is

This seems like a port configuration issue. Which explains why it works after the Arduino serial monitor has ben connected (ports retain the configuration after it's closed).

Specify the entire configuration of the port in your C# code. Play around with the hardware flow control as well, sometimes it's on by default.

private void comboBox_ComPort_DropDown(object sender, EventArgs e)
        {
            string[] portlists = System.IO.Ports.SerialPort.GetPortNames();
            comboBox_ComPort.Items.Clear();
            comboBox_ComPort.Items.AddRange(portlists);

          

        }

is there something more that i need to mention in the port configuration code?

The most common properties of a serial connection is:

  • Baudrate
  • Number of stopbits
  • Number of databits
  • Parity
  • Flowcontrol

You can take a look at the reference here: SerialPort Class (System.IO.Ports) | Microsoft Docs

Edit:

Also try asserting the RTS signal. Even with flowcontrol disabled.

See, SerialPort.RtsEnable Property (System.IO.Ports) | Microsoft Docs