从文本文件中获取字符串行,并在标签中显示该文本
本文关键字:文本 标签 显示 文件 获取 字符串 | 更新日期: 2023-09-27 18:18:41
我正在学习c#,并创建这个程序来学习更多。
我的程序捕获您输入的信息并将其保存到一个文本文件中。在这一部分,是好的,但我有问题加载文件,并显示其中的信息。
例如,在程序中,我有用于用户输入其家庭信息的文本框:
文本框:
妈妈文本框:
兄弟文本框:
文本框输入类似于:
爸爸文本框:MyDad
妈妈文本框:MyMom
兄弟文本框:MyBrother
当文件的创建过程开始时,我在文件中有我想要的输出:
<我>我爸MyMom
MyBrother
好的,现在我需要从文件中加载这些信息并将其写入另一个标签中,例如:
你的爸爸是:根据例子,我想在这里显示"MyDad"
您的母亲是:根据示例,我希望这里显示"MyMother"
您的兄弟是:根据示例,我希望这里显示"MyBrother"
在显示文件信息的按钮的click事件中,我用这个来检查文件是否被创建,如果是,读取它:我>
string path = @"C:'Users'Hypister'Desktop'Family.txt";
if (File.Exists(path))
{
using (StreamReader sr = File.OpenText(path))
{
//Here I need the function to get the lines and show it in respective labels.
}
}
else
{
MessageBox.Show("The file doesn't exists. Data cannot be loaded.");
}
但是我无法从文件中找到爸爸、妈妈和哥哥的台词。
我希望有人能回答这个问题,帮助我获得更多的知识。提前感谢大家!
我为您编写了一个示例,一个很好的c#文件参考是http://msdn.microsoft.com/en-us/library/ezwyzy7b.aspx,供将来参考。
有3个文本框3个标签和一个按钮都是默认名称
这里是源代码,希望它有帮助:)
private void button1_Click(object sender, EventArgs e)
{
List<string> family = new List<string>();
family.Add(textBox1.Text);
family.Add(textBox2.Text);
family.Add(textBox3.Text);
family.ToArray();
using (System.IO.StreamWriter file = new System.IO.StreamWriter(@"C:'Users'OEM'Desktop'stackoverflow'test.txt"))
{
foreach (string line in family)
{
file.WriteLine(line);
}
}
string[] familyout = System.IO.File.ReadAllLines(@"C:'Users'OEM'Desktop'stackoverflow'test.txt");
/* this works just fine unless you have alot of labels, the code not commented out below this works better
label1.Text = familyout[0];
label2.Text = familyout[1];
label3.Text = familyout[2];
*/
int i = 0;
foreach (Control lbl in this.Controls)
{
if (lbl is Label)
{
lbl.Text = familyout[i];
i++;
}
}
}