Click here to Skip to main content
15,885,985 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,

I've a gui and I get data values data from a Uc. I can see the data in the rich text box and save to a text file. But I cannot understand how to sort the saved data in the column format. Right now it is a long row of data. Please advice.

Would it be advisable to replace the rich text box to a normal text box? This is an image of the saved data in text file: https://i.imgur.com/swgT4er.jpg[^]
and this is in a terminal window: https://i.imgur.com/L0CDo5H.png[^]
Input is the temperature sent by the controller. The controller is running a demo code and it sends temperature over the serial link. Thanks.

I've a button to save data to the text file (button3_Click);

What I have tried:

C#
using System;
using System.Windows.Forms;
using System.IO.Ports;
using System.IO;
namespace Serial_receive
{
    public partial class Form1 : Form
    {
        // All members variables should be placed here
        // make it more readable, hopefully!
        string t;
        SerialPort sp;

        public Form1()
        {
            InitializeComponent();
            Control.CheckForIllegalCrossThreadCalls = false;

            // User can already search for ports when the constructor of the FORM1 is calling 
            // And let the user search ports again with a click
            // Searching for ports function

            SearchPorts();
        }
       //search button  
        private void button1_Click(object sender, EventArgs e)
        {
            comboBox1.Items.Clear();
            SearchPorts();
        }
        void SearchPorts()
        {
            string[] ports = SerialPort.GetPortNames();
            foreach (string port in ports)
            {
                comboBox1.Items.Add(port);
            }
        }
  
        private void button2_Click(object sender, EventArgs e)
        {
            // Catch exception if it will be thrown so the user will see it in a message box
            OpenCloseSerial();
        }      
        void OpenCloseSerial()
        {
            try
            {
                if (sp == null || sp.IsOpen == false)
                {
                    t = comboBox1.Text.ToString();
                    sErial(t);
                    button2.Text = "Close Serial port"; // button text
                }
                else
                {
                    sp.Close();
                    button2.Text = "Connect and wait for inputs";   // button text

                }
            }
            catch (Exception err)   // catching error message
            {
                MessageBox.Show(err.Message);   // displaying error message
            }           
        }
      
        void sErial(string Port_name)
        {
            try
            {
                sp = new SerialPort(Port_name, 115200, Parity.None, 8, StopBits.One);   // serial port parameters
                sp.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler);
                sp.Open();
            }
            catch (Exception err)
            {
                throw (new SystemException(err.Message));
            }
        }
//
        private  void DataReceivedHandler(object sender,SerialDataReceivedEventArgs e)
        {

            // This below line is not need , sp is global (belongs to the class!!)
            //SerialPort sp = (SerialPort)sender;
            if (e.EventType == SerialData.Chars)
            {
                if (sp.IsOpen)
                {
                    string w = sp.ReadExisting();
                    if (w != String.Empty)
                    {
                       // Text += "\r\n";
                        Invoke(new Action(() => richTextBox1.AppendText(w)));
                    }
                }
            }
        }

        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (sp == null || sp.IsOpen == false)
            {
                OpenCloseSerial();
            }
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            this.Text = "Serial Channel to FRDM-KW40Z";
        }
        //public void SaveMyFile()
        //{
        //    // Create a SaveFileDialog to request a path and file name to save to.
        //    SaveFileDialog saveFile1 = new SaveFileDialog();

        //    // Initialize the SaveFileDialog to specify the RTF extension for the file.
        //    String fileName = "C:\\Users\varman\\Desktop\\Test.rtf"; //set this to your file you want
        //    saveFile1.DefaultExt = "*Test.rtf";
        //    saveFile1.Filter = "RTF Files|*.rtf";

        //    // Determine if the user selected a file name from the saveFileDialog.
        //    if (saveFile1.ShowDialog() == System.Windows.Forms.DialogResult.OK &&
        //       saveFile1.FileName.Length > 0)
        //    {
        //        // Save the contents of the RichTextBox into the file.
        //        richTextBox1.SaveFile(saveFile1.FileName, RichTextBoxStreamType.PlainText);
        //    }
        //}

        private void button3_Click(object sender, EventArgs e)
        {
            SaveFileDialog saveFileDialog1 = new SaveFileDialog();
            saveFileDialog1.InitialDirectory = @"C:\Users\varman\Documents\";
            saveFileDialog1.Title = "Save text Files";
            saveFileDialog1.CheckFileExists = true;
            saveFileDialog1.CheckPathExists = true;
            saveFileDialog1.DefaultExt = "txt";
            saveFileDialog1.Filter = "Text files (*.txt)|*.txt|All files (*.*)|*.*";
            saveFileDialog1.FilterIndex = 2;
            saveFileDialog1.RestoreDirectory = true;

            if (saveFileDialog1.ShowDialog() == DialogResult.OK)
            {
                Text += "\r\n";
                File.WriteAllText(saveFileDialog1.FileName, richTextBox1.Text);
                richTextBox1.Text = saveFileDialog1.FileName;
            }
        }

        private void richTextBox1_TextChanged(object sender, EventArgs e)
        {
            
        }
    }
}
Posted
Updated 18-Feb-17 11:33am
v5
Comments
[no name] 18-Feb-17 13:25pm    
You realize, don't you, that text files do not have "columns" right?
PIEBALDconsult 18-Feb-17 13:44pm    
Among other things, you need to learn about separation of concerns.
Ram _Varman 18-Feb-17 16:18pm    
Yes! I hope to learn that among other things, and quicker :)
In the meantime, please help. I was under the impression that Text += "\r\n" in the DataReceivedHandler field would solve the formatting problem. I think I can manipulate the save data before it is written to the text file. But I'm not sure if I should do it in DataReceivedHandler or button3_Click. Would just that one piece be sufficient? Based on @NotPoliticallyCorrect's comment, is it even possible? Thanks.
Patrice T 18-Feb-17 13:52pm    
Do you realize that you forgot to show your input data and the result you want ?
Ram _Varman 18-Feb-17 16:11pm    
This is an image of the saved data in text file: https://i.imgur.com/swgT4er.jpg
and this is in a terminal window: https://i.imgur.com/L0CDo5H.png
Input is the temperature sent by the controller. The controller is running a demo code and it sends temperature over the serial link. Thanks.


Hello,

The .Text property of the RichTextBox is no good for you.

Instead use .Lines

File.AppendAllLines(@"c:\temp\test1.txt", richTextBox1.Lines);


The is because the .Text property uses \n to indicate a new line and in a Text file it is not enough.

Try this to debug:
File.WriteAllText(@"c:\temp\test2.txt", richTextBox1.Text);
File.AppendAllLines(@"c:\temp\test1.txt", richTextBox1.Lines);
File.WriteAllText(@"c:\temp\test3.txt", richTextBox1.Text.Replace("\n",Environment.NewLine));

Valery.
 
Share this answer
 
Your problem is that the EOL used by your device is not recognized bu your text editor.
Use a text editor that can display in Hex mode and look a the char before "Temperature", it is not a space.
Other solution is to replace that EOL with the one standard on windows.
Newline - Wikipedia[^]
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900