-1

I been having trouble trying to figure this out. When I think I have it I get told no. Here is a picture of it. enter image description here

I am working on the save button. Now after the user adds the first name, last name and job title they can save it. If a user loads the file and it comes up in the listbox, that person should be able to click on the name and then hit the edit button and they should be able to edit it. I have code, but I did get inform it looked wackey and the string should have the first name, last name and job title.

It is getting me really confused as I am learning C#. I know how to use savefiledialog but I am not allowed to use it on this one. Here is what I am suppose to be doing:

When the user clicks the “Save” button, write the selected record to the file specified in txtFilePath (absolute path not relative) without truncating the values currently inside.

I am still working on my code since I got told that it will be better file writes records in a group of three strings. But this is the code I have right now.

    private void Save_Click(object sender, EventArgs e)
    {

            string path = txtFilePath.Text;


            if (File.Exists(path))
            {
                using (StreamWriter sw = File.CreateText(path))
                {

                    foreach (Employee employee in employeeList.Items)
                        sw.WriteLine(employee);
                }
            }
            else
                try
            {

                StreamWriter sw = File.AppendText(path);

                foreach (var item in employeeList.Items)
                    sw.WriteLine(item.ToString());

            }

    catch
{
    MessageBox.Show("Please enter something in");
}

Now I can not use save or open file dialog. The user should be able to open any file on the C,E,F drive or where it is. I was also told it should be obj.Also the program should handle and exceptions that arise.

I know this might be a noobie question but my mind is stuck as I am still learning how to code with C#. Now I have been searching and reading. But I am not finding something to help me understand how to have all this into 1 code. If someone might be able to help or even point to a better web site I would appreciate it.

Bart
  • 19,692
  • 7
  • 68
  • 77
shan
  • 1,311
  • 4
  • 13
  • 17
  • Are you looking for corrections to the code you posted or the additional code that would be necessary to implement the load function given the code you posted as the save function? – BlueMonkMN Apr 27 '12 at 11:08
  • Im not going to lie right now anything will help. – shan Apr 27 '12 at 11:12
  • Are you supposed to be storing many people in one file or just one person per file? – BlueMonkMN Apr 27 '12 at 12:13
  • I expect you will need to be more specific about your question. Start by breaking it down into smaller problems, and then ask questions about the pieces that you can't figure out. And if you can't figure out how to break it down, make that an issue of its own. List the requirements and deal with the question "What are the pieces I need to fulfill these requirements?" – BlueMonkMN Apr 27 '12 at 12:17
  • With storing the people in the file it is whatever a person puts in for the employee such as a person says they have 3 employees well all 3 will be save to the save file. – shan Apr 27 '12 at 12:32
  • I need to be able to save the information that the user puts in the list box with all 3 lines(Firstname,Lastname,JobTitle). write the selected record to the file specified in txtFilePath (which is the textbox.) If a file is not there then it will be created. This is my main problem I am having. – shan Apr 27 '12 at 12:38
  • let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/10598/discussion-between-shan-and-bluemonkmn) – shan Apr 27 '12 at 12:39
  • I can write in chat or some reason. But this is what I was told your save button has some "whacky" functioning.writing a value to the file as a single string and reading it is as a single string is a very difficult way of doing it. It is much easier of the file writes records in a group of three strings – shan Apr 27 '12 at 13:28

3 Answers3

1

You have to determine a way of saving that suits your needs. A simple way to store this info could be CSV:

"Firstname1","Lastname 1", "Jobtitle1"
" Firstname2", "Lastname2","Jobtitle2 "

As you can see, data won't be truncated, since the delimiter " is used to determine string boundaries.

As shown in this question, using CsvHelper might be an option. But given this is homework and the constraints therein, you might have to create this method yourself. You could put this in Employee (or make it override ToString()) that does something along those lines:

public String GetAsCSV(String firstName, String lastName, String jobTitle)
{
    return String.Format("\"{0}\",\"{1}\",\"{2}\"", firstName, lastName, jobTitle);
}

I'll leave the way how to read the data back in as an exercise to you. ;-)

Community
  • 1
  • 1
CodeCaster
  • 147,647
  • 23
  • 218
  • 272
1

As you are writing the employee objects with WriteLine, the underlying ToString() is being invoked. What you have to do first is to customize that ToString() methods to fit your needs, in this way:

public class Employee
{
    public string FirstName;
    public string LastName;
    public string JobTitle;

    // all other declarations here
    ...........

    // Override ToString()
    public override string ToString()
    { 
         return string.Format("'{0}', '{1}', '{2}'", this.FirstName, this.LastName, this.JobTitle);
    }
}

This way, your writing code still keeps clean and readable.

By the way, there is not a reverse equivalent of ToSTring, but to follow .Net standards, I suggest you to implement an Employee's method like:

public static Employee Parse(string)
{
        // your code here, return a new Employee object
}
1

There are many, many ways to store data in a file. This code demonstrates 4 methods that are pretty easy to use. But the point is that you should probably be splitting up your data into separate pieces rather than storing them as one long string.

public class MyPublicData
{
  public int id;
  public string value;
}

[Serializable()]
class MyEncapsulatedData
{
  private DateTime created;
  private int length;
  public MyEncapsulatedData(int length)
  {
     created = DateTime.Now;
     this.length = length;
  }
  public DateTime ExpirationDate
  {
     get { return created.AddDays(length); }
  }
}

class Program
{
  static void Main(string[] args)
  {
     string testpath = System.IO.Path.Combine(
        Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "TestFile");

     // Method 1: Automatic XML serialization
     // Requires that the type being serialized and all its serializable members are public
     System.Xml.Serialization.XmlSerializer xs = 
        new System.Xml.Serialization.XmlSerializer(typeof(MyPublicData));
     MyPublicData o1 = new MyPublicData() {id = 3141, value = "a test object"};
     MyEncapsulatedData o2 = new MyEncapsulatedData(7);
     using (System.IO.StreamWriter w = new System.IO.StreamWriter(testpath + ".xml"))
     {
        xs.Serialize(w, o1);
     }

     // Method 2: Manual XML serialization
     System.Xml.XmlWriter xw = System.Xml.XmlWriter.Create(testpath + "1.xml");
     xw.WriteStartElement("MyPublicData");
     xw.WriteStartAttribute("id");
     xw.WriteValue(o1.id);
     xw.WriteEndAttribute();
     xw.WriteAttributeString("value", o1.value);
     xw.WriteEndElement();
     xw.Close();

     // Method 3: Automatic binary serialization
     // Requires that the type being serialized be marked with the "Serializable" attribute
     using (System.IO.FileStream f = new System.IO.FileStream(testpath + ".bin", System.IO.FileMode.Create))
     {
        System.Runtime.Serialization.Formatters.Binary.BinaryFormatter bf = 
           new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
        bf.Serialize(f, o2);
     }

     // Demonstrate how automatic binary deserialization works
     // and prove that it handles objects with private members
     using (System.IO.FileStream f = new System.IO.FileStream(testpath + ".bin", System.IO.FileMode.Open))
     {
        System.Runtime.Serialization.Formatters.Binary.BinaryFormatter bf =
           new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
        MyEncapsulatedData o3 = (MyEncapsulatedData)bf.Deserialize(f);
        Console.WriteLine(o3.ExpirationDate.ToString());
     }

     // Method 4: Manual binary serialization
     using (System.IO.FileStream f = new System.IO.FileStream(testpath + "1.bin", System.IO.FileMode.Create))
     {
        using (System.IO.BinaryWriter w = new System.IO.BinaryWriter(f))
        {
           w.Write(o1.id);
           w.Write(o1.value);
        }
     }

     // Demonstrate how manual binary deserialization works
     using (System.IO.FileStream f = new System.IO.FileStream(testpath + "1.bin", System.IO.FileMode.Open))
     {
        using (System.IO.BinaryReader r = new System.IO.BinaryReader(f))
        {
           MyPublicData o4 = new MyPublicData() { id = r.ReadInt32(), value = r.ReadString() };
           Console.WriteLine("{0}: {1}", o4.id, o4.value);
        }
     }
  }
}
BlueMonkMN
  • 25,079
  • 9
  • 80
  • 146
  • I can not chat in the chat room for some reason. but i did write you back under the comments. – shan Apr 27 '12 at 14:54
  • @shan So instead of writing a single line, use one of the methods described in this answer. They all write the values separately instead of as a combined string. – BlueMonkMN Apr 27 '12 at 21:10
  • can you go back over to the chat room we was in – shan Apr 27 '12 at 21:20