'Got some error with float. When I run it gives error . Incorrectly formatted input string. It is a Serial Port program

            float parsedFloat = float.Parse(inputWithoutPoint); // this converts the string into an actual float ---> HERE IS ALSO THE ERROR WHEN I Open connection
using System.IO.Ports;
using System.Windows.Forms;
using System.Collections.Generic;
using MySql.Data.MySqlClient;
using System.Text;
using System.IO;
using System.Drawing;
using System;
using System.Diagnostics;



namespace TesteSerial
{
    public partial class frmPrincipal : MetroForm
    {
        List<float> weights = new List<float>();


        public frmPrincipal()
        {
            InitializeComponent();
            CarregarImpressoras();

            //ComboBox Opcoes BaudRate
            cboBaudRate.Items.Add("75");
            cboBaudRate.Items.Add("110");
            cboBaudRate.Items.Add("300");
            cboBaudRate.Items.Add("1200");
            cboBaudRate.Items.Add("2400");
            cboBaudRate.Items.Add("4800");
            cboBaudRate.Items.Add("9600");
            cboBaudRate.Items.Add("19200");
            cboBaudRate.Items.Add("38400");
            cboBaudRate.Items.Add("57600");
            cboBaudRate.Items.Add("115200");
        }

        private void frmPrincipal_Load(object sender, System.EventArgs e)
        {
            string[] ports = SerialPort.GetPortNames();
            cboPortaCom.Sorted = true;
            foreach (var s in ports)
            {
                cboPortaCom.Items.Add(s);
            }
            if (cboPortaCom.Items.Count > 0)
            {
                cboPortaCom.SelectedIndex = 0;
            }
        }
        [System.ComponentModel.Bindable(true)]
        [System.ComponentModel.Browsable(false)]
        public object SelectedItem { get; set; }

        private const string textPrefix = @"+";
        private const string prefixmenos = @"-";

        private void btnteste_Click(object sender, EventArgs e) // Button for send Data in txtDadosRecebidos
        {
            txtDadosRecebidos.Text += "+   0.089";

            if (txtDadosRecebidos.Text.StartsWith(textPrefix))
            {
                string input = txtDadosRecebidos.Text; // this is your input, replace that with your variable where the text comes from
                string inputWithoutNewline = input.Remove(input.Length - 1, 1); // removes last character, is now: "+ 9.81"
                string inputWithoutSpace = inputWithoutNewline.Replace(" ", ""); // this replaces all spaces with nothing (aka removes the one after the +), is now "+9.81"
                string inputWithoutPoint = inputWithoutSpace.Replace(".", ","); // Trying to change "," to "."

                Console.WriteLine(inputWithoutPoint);
                float parsedFloat = float.Parse(inputWithoutPoint); // this converts the string into an actual float
            }
        }

        private void btnAbrirPorta_Click(object sender, System.EventArgs e) // Opening / Closing COM Port 
        {
          

            if (cboBaudRate.SelectedItem != null)
            {
                int selectedIndex = cboBaudRate.SelectedIndex;
                Object selectedItem = cboBaudRate.SelectedItem;

                string BaudRate = cboBaudRate.SelectedItem.ToString();

                float parsedFloat = float.Parse(BaudRate); // this converts the string into an actual float

                int parsedInt = int.Parse(BaudRate);

                if (spComunica.IsOpen)
                {
                    btnAbrirPorta.BackColor = Color.LightGreen;
                    btnAbrirPorta.Text = "Abrir";
                    spComunica.Close();
                }
                else
                {
                    btnAbrirPorta.BackColor = Color.Red;
                    btnAbrirPorta.Text = "Fechar";
                    spComunica.PortName = cboPortaCom.Text;
                    spComunica.BaudRate = parsedInt;
                    Console.WriteLine(cboBaudRate.SelectedItem);
                    spComunica.Open();
                }
                btnEnviar.Enabled = txtEnviaDado.Enabled = spComunica.IsOpen;
            }
            else
            {
                MessageBox.Show("Selecione um Baud Rate");
            }
        }

        private void btnEnviar_Click(object sender, System.EventArgs e) // Send Data for Com Port
        {
            spComunica.Write(txtEnviaDado.Text);
        }
        private void spComunica_DataReceived(object sender, SerialDataReceivedEventArgs e) // Receive Data from COM Port and starts working
        {
            string input = "";
            try
            {
                input = spComunica.ReadExisting();
            }
            catch (InvalidOperationException)
            {
                return;
            }

            if (input.StartsWith(textPrefix)) // IF start with "+", that is how Weight Come from Balance, will treat and put correctly for convert to float ( Remove Spaces and that stuff))
            {
                txtDadosRecebidos.BackColor = Color.LightGreen;
                string inputWithoutNewline = input.Remove(input.Length - 1, 1); // removes last character, is now: "+ 9.81"
                string inputWithoutSpace = inputWithoutNewline.Replace(" ", ""); // this replaces all spaces with nothing (aka removes the one after the +), is now "+9.81"
                string inputWithoutPoint = inputWithoutSpace.Replace(".", ","); // Trying to change "," to "."
                BeginInvoke((MethodInvoker)(() => { txtDadosRecebidos.Text = inputWithoutPoint; }));
                Console.WriteLine(inputWithoutPoint);
                float parsedFloat = float.Parse(inputWithoutPoint); // this converts the string into an actual float ---> HERE IS THE ERROR WHEN I Open connection

                weights.Add(parsedFloat);

                if (weights.Count >= 5) // What I need to catch 5 weights, if they are the same that means that the balace is estabilized, so It will send Weight to left txtBox 
                {
                    float average = (weights[0] + weights[1] + weights[2] + weights[3] + weights[4]) / 5;
                    if (Math.Abs(average - weights[0]) < 0.02) ;
                    {
                        string avgString = average + "KG \n";
                        BeginInvoke((MethodInvoker)(() => { metroTextBox1.Text = avgString; }));
                        weights.Clear();
                    }
                }
                else
                {
                    weights.RemoveAt(0);
                    return;

                }
            }

            else if (input.StartsWith(prefixmenos))
            {
                txtDadosRecebidos.BackColor = Color.Red;
                string inputWithoutNewline = input.Remove(input.Length - 1, 1); // removes last character, is now: "+ 9.81"
                string inputWithoutSpace = inputWithoutNewline.Replace(" ", ""); // this replaces all spaces with nothing (aka removes the one after the +), is now "+9.81"
                string inputWithoutPoint = inputWithoutSpace.Replace(".", ","); // Trying to change "," to "."
                BeginInvoke((MethodInvoker)(() => { txtDadosRecebidos.Text = inputWithoutPoint; }));
                 Console.WriteLine(inputWithoutPoint);
                float parsedFloat = float.Parse(inputWithoutPoint); // this converts the string into an actual float ---> HERE IS ALSO THE ERROR WHEN I Open connection
            }
        }
        private void btSair_Click(object sender, System.EventArgs e)
        {
            Application.Exit();
        }

        private void btenviardb_Click(object sender, System.EventArgs e)
        {
            try
            {
                //This is my connection string i have assigned the database file address path  
                string connetionString = "server=localhost;database=codbarras;uid=root;pwd=;";
                //This is my insert query in which i am taking input from the user through windows forms  
                string Query = "insert into codigobarras values('" + this.metroTextBox1.Text + "');";
                //This is  MySqlConnection here i have created the object and pass my connection string.  
                MySqlConnection MyConn2 = new MySqlConnection(connetionString);
                //This is command class which will handle the query and connection object.  
                MySqlCommand MyCommand2 = new MySqlCommand(Query, MyConn2);
                MySqlDataReader MyReader2;
                MyConn2.Open();
                MyReader2 = MyCommand2.ExecuteReader();     // Here our query will be executed and data saved into the database.  
                MessageBox.Show("Dados Guardados!");
                while (MyReader2.Read())
                {
                }
                MyConn2.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        //botão imprimir 
        private void btImprimir_Click(object sender, System.EventArgs e)
        {
            using (var pd = new System.Drawing.Printing.PrintDocument())
            {
                pd.PrinterSettings.PrinterName = impressoraComboBox.SelectedItem.ToString();
                pd.Print();
            }
        }
        private void CarregarImpressoras()
        {
            impressoraComboBox.Items.Clear();

            foreach (var impressora in System.Drawing.Printing.PrinterSettings.InstalledPrinters)
            {
                impressoraComboBox.Items.Add(impressora);
            }
        }

        private void cboBaudRate_SelectedIndexChanged(object sender, EventArgs e)
        {


        }
        private void txtDadosRecebidos_Click(object sender, EventArgs e)
        {
            {

            }
        }
        private void bt1_Click(object sender, EventArgs e)
        {
        }

        private void btenviardbPeso_Click(object sender, EventArgs e)
        {
            try
            {
                //This is my connection string i have assigned the database file address path  
                string connetionString = "server=localhost;database=codbarras;uid=root;pwd=;";
                //This is my insert query in which i am taking input from the user through windows forms  
                string Query = "insert into pesobalanca values('" + this.metroTextBox1.Text + "');";
                //This is  MySqlConnection here i have created the object and pass my connection string.  
                MySqlConnection MyConn2 = new MySqlConnection(connetionString);
                //This is command class which will handle the query and connection object.  
                MySqlCommand MyCommand2 = new MySqlCommand(Query, MyConn2);
                MySqlDataReader MyReader2;
                MyConn2.Open();
                MyReader2 = MyCommand2.ExecuteReader();     // Here our query will be executed and data saved into the database.  
                MessageBox.Show("Dados Guardados!");
                while (MyReader2.Read())
                {
                }
                MyConn2.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void metroTextBox1_Click(object sender, EventArgs e)
        {
        }
        private void btLimpar_Click(object sender, System.EventArgs e)
        {
            txtDadosRecebidos.Clear();
        }

        private void limparRegisto_Click(object sender, EventArgs e)
        {
            metroTextBox1.Clear();
        }
    }
}```


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source