I have created a project in C# windows form application. I am using .Net framework version 4.0 and Visual studio 2010. Project contains Save and load File button. And also some textboxes.
I created a text file like this
Serial Number = 1
Type Number = 500
Test Engineer = jay
Date = 03/05/2018
Time = 16:17:20 PM
Test1 = 1.00
Test2 = 1.76
.
.
.
Test18 = 4.66
Code for Load File button:
private void btn_LoadFile_Click(object sender, EventArgs e)
{
OpenFileDialog fdlg = new OpenFileDialog();
if (fdlg.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
System.IO.StreamReader sr = new
System.IO.StreamReader(fdlg.FileName);
string[] lines = sr.ReadToEnd().Split('\n');
tb_SerialNo.Text = lines[0];
tb_TypeNo.Text = lines[1];
tb_TestEngineer.Text = lines[2];
tb_Date.Text = lines[3];
tb_Test1.Text = lines[4];
tb_Test2.Text = lines[5];
}
}
When I run above code, I got value in Serial no textbox is Serial Number = 1
but I want 1
in textbox. Same Type Number
Tex box Type Number = 500
but here also I want 500
in Type number textbox.
When you split by new line, lines[0]
will store Serial Number = 1
. Here you need to split it again by =
.
If you try and print values of each element from string array, you will understand what changes you need to do in your code.
private void btn_LoadFile_Click(object sender, EventArgs e)
{
OpenFileDialog fdlg = new OpenFileDialog();
if (fdlg.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
System.IO.StreamReader sr = new
System.IO.StreamReader(fdlg.FileName);
string[] lines = sr.ReadToEnd().Split('\n'); //To make your code more readable, you can use "Environment.NewLine" instead of '\n'
Console.WriteLine(lines[0]); //Here it will give "Serial Number = 1"
// you need to store 1 in tb_SerialNo.Text, so split lines[0] with =
//Have you tried with this.
string[] splitWithEqualTo = lines[0].Split('=');
tb_SerialNo.Text = splitWithEqualTo [1];
//Similar kind of logic you can apply for other text boxes.
}
}
To fix your issue, you can try with the followings
Console.WriteLine(lines[0]); // This will print "Serial Number = 1"
string[] slitLine = lines[0].Split('=');
Console.WriteLine(slitLine[0]); //This will print "Serial Number"
Console.WriteLine(slitLine[1]); //This will print 1, this is what you need to store in tb_SerialNo.Text, right?
This is not the solution, but you will understand what changes you need to do in your code.