0

在 Form1 我有 2 个文本框(姓和名)。当我按下“注册”按钮时,我通过 TextWriter 将它们写入文件。每行包含姓和名,因此每行有2个字段。

在 Form2 中,我想通过询问参数来编辑它们。例如,在 Form2 中,我有一个 TextBox。如果我在文本框中输入的姓氏等于我文件中的一个,我想在 Form1 的正确文本框中显示姓氏和名字,并且在编辑姓氏或名字后,我想通过按下“注册”在正确的位置覆盖上一行“ 按钮。

感谢用户 Medinoc,我这样编写文件:

ref class MyClass
{
public:
    String^ cognome;
    String^ nome;
};

//...

List<MyClass^>^ primo = gcnew List<MyClass^>();

//...

MyClass^ myObj = gcnew MyClass();
myObj->cognome = textBox1->Text;
myObj->nome = textBox2->Text;
primo->Add(myObj);

//...

TextWriter ^tw = gcnew StreamWriter(L"primoAnno.txt", true);
for each(MyClass^ obj in primo)
{
    //You can use any character or string as separator,
    //as long as it's not supposed to appear in the strings.
    //Here, I used pipes.
    tw->Write(obj->cognome);
    tw->Write(L"|");
    tw->Write(obj->nome);
}
tw->Close();

MyClass^ ParseMyClass(String^ line)
{
    array<String^>^ splitString = line->Split(L'|');
    MyClass^ myObj = gcnew MyClass();
    myObj->cognome = splitString[0];
    myObj->nome = splitString[1];
    return myObj;
}

希望我足够清楚。我不是英格兰人。提前致谢!!

4

1 回答 1

0

它仍然是经典的文本文件编辑行为:

您需要的是在文件中搜索特定行的功能;以及修改特定行的另一个功能。那将类似于删除代码

寻找:

MyClass^ FindMyClass(String^ surnameToFind)
{
    MyClass^ found = nullptr;
    TextReader^ tr = gcnew StreamReader(L"primoAnno.txt");
    String^ line;
    while(found == nullptr && (line=tr->ReadLine()) != nullptr)
    {
        MyClass^ obj = ParseMyClass(line);
        if(obj->cognome == surnameToFind)
            found = surnameToFind;
    }
    tr->Close();
}

更新:

MyClass^ objToUpdate = gcnew MyClass;
objToUpdate->cognome = textBox1->Text;
objToUpdate->nome = textBox2->Text;

TextWriter^ tw = gcnew StreamWriter(L"primoAnno2.txt", true);
TextReader^ tr = gcnew StreamReader(L"primoAnno.txt");
String^ line;
bool updated = false;
while((line=tr->ReadLine()) != nullptr)
{
    MyClass^ obj = ParseMyClass(line);
    if(obj->cognome == objToUpdate->cognome)
    {
        line = objToUpdate->cognome + L"|" + objToUpdate->nome;
        updated = true;
    }
    tw->WriteLine(line);
}
//If the surname was not in the file at all, add it.
if(!updated)
{
    line = objToUpdate->cognome + L"|" + objToUpdate->nome;
    tw->WriteLine(line);
}
tr->Close();
tw->Close();
File::Delete(L"primoAnno.txt");
File::Move(L"primoAnno2.txt", L"primoAnno.txt");
于 2013-07-05T07:46:40.833 回答