none
Help me with a save method. RRS feed

  • Question

  • I have a basic app that have a list box with some text(Jack Brown is a presidend and is happy). I want to take theese values and save them to a csv row in a text file. I've create a save method is the class Person. Here is the class:

    public class Person
        {
            public string FirstName { get; set; }
            public string LastName { get; set; }
            public string Job{ get; set; }
            public bool IsHappy { get; set; }
    
            public override string ToString()
            {
                var StatusText = IsHappy ? "happy" : "unhappy";
    
                return $"{FirstName} {LastName} is a {Job} and is {StatusText}";
            }
            public  void Save(StreamWriter writer)
            {
                string sPath = @"C:\Users\user\Desktop\Document.TXT";
                System.IO.StreamWriter SaveFile = new System.IO.StreamWriter(sPath);
                SaveFile.Write(FirstName + LastName + Age + IsHappy);
                SaveFile.Close();
            }
        }

    The first problem is that I couldn't call this function here:

    public void saveListButton_Click(object sender, EventArgs e)
            {
                Person savefile = new Person();
                savefile.Save();
            }

    The second problem is since the isHappy is a bool, i want to write instead of the status true or false(or 1 or 0). And I don't know how should I do that.

    A little mention, this will work at RunTime. The user can enter the name, job, and status(this is a checkbox), and then save them and so on.

    Here is the add user script:

    private void addUserButton_Click(object sender, EventArgs e)
            {
                var person = new Person { FirstName = firstNameText.Text, LastName = lastNameText.Text, Job = jobText.Text, IsHappy = isHappyCheckbox.Checked };
                _persons.Add(person);
            }

    Thanks for attention!

    Saturday, October 19, 2019 3:08 PM

Answers

  • Hi horatiu_alex,

    Your person class : 

      public sealed class Person
        {
            private string FirstName { get; set; }
            private string LastName { get; set; }
            private string Job { get; set; }
            private bool IsHappy { get; set; }
    
    
            public Person(string firstname,string lastname , string job,bool happy)
            {
                this.FirstName = firstname;
                this.LastName = lastname;
                this.Job = job;
                this.IsHappy = happy;
    
            }
    
            public override string ToString()
            {
                var StatusText = IsHappy ? "happy" : "unhappy";
    
                return $"{FirstName} {LastName} is a {Job} and is {StatusText}";
    
            }
    
            public void Save()
            {
              
                using (StreamWriter SaveFile = new StreamWriter(@"C:\Users\Mehmet Emin\Desktop\Document.TXT")) {
    
                    SaveFile.Write(this.ToString());
                    SaveFile.Close();
                }
                    
            }
        }

    And usage :

      private void Button1_Click(object sender, EventArgs e)
            {
                Person myperson = new Person(firstNameText.Text, lastNameText.Text, jobText.Text, isHappyCheckbox.Checked);
                myperson.Save();
                
    
            }

    • Marked as answer by horatiu_alex Saturday, October 19, 2019 6:48 PM
    Saturday, October 19, 2019 4:08 PM

All replies

  • Hi horatiu_alex,

    Your person class : 

      public sealed class Person
        {
            private string FirstName { get; set; }
            private string LastName { get; set; }
            private string Job { get; set; }
            private bool IsHappy { get; set; }
    
    
            public Person(string firstname,string lastname , string job,bool happy)
            {
                this.FirstName = firstname;
                this.LastName = lastname;
                this.Job = job;
                this.IsHappy = happy;
    
            }
    
            public override string ToString()
            {
                var StatusText = IsHappy ? "happy" : "unhappy";
    
                return $"{FirstName} {LastName} is a {Job} and is {StatusText}";
    
            }
    
            public void Save()
            {
              
                using (StreamWriter SaveFile = new StreamWriter(@"C:\Users\Mehmet Emin\Desktop\Document.TXT")) {
    
                    SaveFile.Write(this.ToString());
                    SaveFile.Close();
                }
                    
            }
        }

    And usage :

      private void Button1_Click(object sender, EventArgs e)
            {
                Person myperson = new Person(firstNameText.Text, lastNameText.Text, jobText.Text, isHappyCheckbox.Checked);
                myperson.Save();
                
    
            }

    • Marked as answer by horatiu_alex Saturday, October 19, 2019 6:48 PM
    Saturday, October 19, 2019 4:08 PM
  • Here is an example which foregoes the add from TextBox controls, focus is on the save. There is some optimization e.g. expression body member for ToString, no need for the statusText variable.

    using System;
    using System.IO;
    using System.Windows.Forms;
    
    namespace SimpleDemo
    {
        public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
                Shown += Form1_Shown;
            }
            private void Form1_Shown(object sender, EventArgs e)
            {
    
                listBox1.Items.Add(new Person()
                {
                    FirstName = "Karen",
                    LastName = "Payne",
                    IsHappy =  true,
                    Job = "ABC"
                });
                listBox1.Items.Add(new Person()
                {
                    FirstName = "Mary",
                    LastName = "Smith",
                    IsHappy = false,
                    Job = "BBB"
                });
            }
            /// <summary>
            /// Only save if there is a selected Person
            /// </summary>
            /// <param name="sender"></param>
            /// <param name="e"></param>
            private void button1_Click(object sender, EventArgs e)
            {
                if (listBox1.SelectedItem == null) return;
                var person = (Person) listBox1.SelectedItem;
                person.Save();
            }
        }
        /// <summary>
        /// This should be in a class file
        /// </summary>
        public class Person
        {
            public string FirstName { get; set; }
            public string LastName { get; set; }
            public string Job { get; set; }
            public bool IsHappy { get; set; }
            /// <summary>
            /// Save to app folder
            /// If we were sure first and last name were set these
            /// properties could be used to create a base file name
            /// e.g. KarenPayne.txt
            /// </summary>
            public void Save()
            {
                File.WriteAllText(Path.Combine(
                    AppDomain.CurrentDomain.BaseDirectory, "SomeFile.txt"), 
                    ToString());
            }
            /// <summary>
            /// Save to specified folder
            /// </summary>
            /// <param name="fileName"></param>
            public void Save(string fileName)
            {
                File.WriteAllText(fileName, ToString());
            }
    
            public override string ToString() => 
                $"{FirstName} {LastName} is a {Job} and is {(IsHappy ? "happy" : "unhappy")}";
        }
    }
    


    Please remember to mark the replies as answers if they help and unmarked them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.

    NuGet BaseConnectionLibrary for database connections.

    StackOverFlow
    profile for Karen Payne on Stack Exchange

    Saturday, October 19, 2019 4:27 PM
    Moderator