C# 将多个文本框保存到一个 .txt 文件中

发布于 2024-10-05 16:14:04 字数 585 浏览 0 评论 0原文

好吧,首先,我是 C# 的初学者(完全是编程的初学者),在 google 上进行了一番搜索后,我找不到这个问题的解决方案。

所以,我需要做的是: 我有 14 个文本框和一些复选框:

姓名、出生日期、出生地点以及一个人的一些其他信息,例如...我有一个“保存”按钮,可以将所有信息保存在一个 .txt 或 .rtf 文件中。每次我在文本框中输入这些信息时,它都会将其保存为以文本框名称中输入的文本命名的文件。

例如:

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

当我单击“保存”按钮时,它会将所有这些信息保存在名为 Petar Milutinovic(与 textBoxName 名称相同)的文件中,格式如下:

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

哦天哪...我真的很抱歉英语拼写,它不是我的主要(你注意到了那个......)。这几天这个问题真是让人头疼啊……

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...

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

我做我的改变 2024-10-12 16:14:04

我认为最简单的方法(因为你是初学者)是创建一个可以容纳 14 个元素的字符串数组,因为你有 14 个文本框。

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

然后你可以直接将其保存到文件中:

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

当然还有其他更有效的方法来做到这一点,但我认为这种方法是最容易理解的。

(我忘记了你的复选框,但你可以用这个概念实现相同的目标)

编辑:

对于复选框或单选按钮,你可以使用 Checked (或 CheckState)属性。

你可以这样做:

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

其中 1 代表 true,0 代表 false。这些值可以是您喜欢的任何值,只要您正确读回即可。

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.

风情万种。 2024-10-12 16:14:04

您可以(应该)首先为每个字段创建属性,如下所示:

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

现在您只需打开一个文件并开始编写:

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.
    } 
}

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.
    } 
}
轻拂→两袖风尘 2024-10-12 16:14:04

你需要能够读取txt文件的内容还是只是为了存储?如果是后者,您可以考虑创建一个可序列化的类来封装所有属性(例如,Person、Employee 等...),然后将这些字段绑定到表单字段。然后,您只需将类/对象序列化并将其存储到文本文件中,而不必 sw.Writeline 每个单独的字段。

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 (e.g. 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.

甩你一脸翔 2024-10-12 16:14:04

由于您总体上是编程新手,因此我将告诉您我在初学者时应该听到的内容:以 OO(面向对象)方式进行操作。有一天,您可能已经足够先进,可以了解函数式编程之类的东西,但在那之前,面向对象才是遵循的方法,它有很大帮助。

那么 OO 是什么东西呢?好吧,一切都是对象。

这意味着您正在创建一个 Person 对象。你如何做到这一点?定义一个

它的工作原理如下:

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.
    }
}

然后(例如在“保存”按钮中),您根据文本字段中的值创建一个 Person 并像这样保存它:

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

这一切可能看起来很奇怪,但现在您可以以更简洁的方式做很多事情,比如将人保存到数据库中或将其作为参数传递,而无需混乱、支离破碎且难以维护的代码。

作为旁注,这也允许继承:

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

看,该类具有与 person 类相同的代码,而且还有一个 Job 属性。作为干净代码的奖励,您可以将 Employee 传递给采用 Person 作为参数的方法,因为员工“是一个”人。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文