简体   繁体   中英

C# Saving multiple textbox's, into one .txt file

Ok, first of all, im a beginer in C# (beginer in programing at all), and after a quite search on google, i couldnt find a solution on this one.

So, what i need to do is this: I have 14 text boxes and a few checkbox's:

Name, Birth Date, Place of birth and some other information of one person for example... I have one Save button that will save all that information in one .txt or .rtf file. Every time i enter those information's in textBox's, it will save it as file named by text entered in textBoxName.

For example:

textBoxName: Petar Milutinovic;
textBoxBirth: 01.11.1991;
textBoxCity: Paracin;

And when i click on Save button, it will save all those information on a file called Petar Milutinovic (same name as textBoxName) in this form:

Name: Petar Milutinovic;
Date of Birth: 01.11.1991;
City: Paracin;

Oh boy... I'm realy sorry for English spelling, its not my main (you noticed that one...). This problem have been quite a pain this days...

You can (should) create properties for each of those fields first like so:

private string Name
{
    // now you avoid a bunch of references to txtName.Text potentially 
    // throughout your form code.  This makes things more simple if you
    // want to swap out UI elements later on.
    get { return txtName.Text; } 
}

private DateTime DateOfBirth
{
    get { return /*selected date*/; } } 
}

// more properties for each field

Now you just open a file and start writing:

private void WriteDataFile( filepath )
{
    // Note: You should handle potential IO errors in a try/catch block
    using( FileStream fs = File.Open( filepath, FileMode.Create )
    using( StreamWriter sw = new StreamWriter( fs ) )
    {
        sw.WriteLine( String.Format( "Name: {0}", this.Name ) );
        sw.WriteLine( String.Format( "Date of Birth: {0}", this.DateOfBirth ) );
        // etc.
    } 
}

Do you need to be able to read the contents of the txt file or is it just for storage? if it's the latter you could consider creating a serializable class that encapsulates all your properties (eg Person, Employee etc...) and then bind these fields to the form fields. Then you only need to serialize the class/object into and store it into a text file rather than having to sw.Writeline each individual field.

I think the easiest way (since you are a beginner) would be to create a string array that can hold 14 elements since you have 14 textboxes.

string[] contents = new string[14];
contents[0] = "Name: " + textBoxName.Text;
contents[1] = "City: " + textBoxCity.Text;
contents[2] = "Date of Birth: " + textBoxBirth.Text;
...

Then you can save it directly to file with:

System.IO.File.WriteAllLines(textBoxName.Text + ".txt", contents);

Of course there are other more efficient ways to do this but I think this way is the most understandable.

(I forgot about your checkboxes, but you can accomplish the same goal with this concept)

EDIT:

For checkboxes or radio buttons you can use the Checked (or CheckState) property.

You could do something like:

contents[0] = checkBox.Checked ? "1" : "0";
contents[1] = radioButton.Checked ? "1" : "0";

where 1 represents true and 0 represents false. These values can be anything you like, as long as you read it back correctly.

Since you're new to programming in general, I'll tell you what I should have heard when I was a beginner: do it all the OO (Object Oriented) way. Someday you may be advanced enough to look at things like Functional programming, but until then, OO is the way to follow, it helps a lot.

So what is this OO thing? Well, everything is an object.

This means you are creating a Person object. And how do you do that? Defining a Class .

Here's how it works:

class Person
{
    public Person(string name,
                  string age,
                  string city)
    {
        this.Name = name;
        this.Age = age;
        this.City = city;
    }

    public string Name { get; private set; }
    public string Age { get; private set; }
    public string City { get; private set; }

    public void SerializeToFile()
    {
        //Do the serialization (saving the person to a file) here.
    }
}

Then (for example in the "save" button), you create a Person from the values in the text fields and save it like so:

private void buttonSave_Click(object sender, EventArgs e)
{
    Person p = new Person(textBoxName.Text,
                          textBoxAge.Text,
                          textBoxCity.Text);
    p.SerializeToFile();
}

This all may seem strange, but now you can do many things in a cleaner way, like maybe saving the person to a database or passing it as an argument without messy, fragmented and hard to mantain code.

As a sidenote, this also allows inheritance:

class Employee : Person
{
    public string Job { get; private set; }
}

See, that class has the same code of the person class, but also a Job property. As a bonus to the clean code, you can pass an Employee to a method that takes a Person as an argument, because an employee "is a" person.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM