Question

for example i have an app with 3 text-boxes (not multi line) and a notepad txt file with 3 lines. when i click a button, the app must fill each line with a line of textbox for example i have a .txt file like this :

zzzzzzzzzzz  
yyyyyyyyyy  
nnnnnnnnn

and i want a textbox1 show "zzzzzzzzzzz" , textbox2 show "yyyyyyyyy" , and textbox3 show "nnnnnnnn". so how can i do this in C# ?

Was it helpful?

Solution

Explanation:
you can use built-in method ReadAllLines() of File class to read the all lines from your file.

Example: System.IO.File.ReadAllLines(filePath);

ReadAllLines() return the String Array of all lines from file ,so you can store them for later use.

Example : String [] allLines= System.IO.File.ReadAllLines(filePath);

Now take each line from StringArray and assign it to TextBox Control.

Example: textBox1.Text = allLines[0];

Code :

    String [] allLines = System.IO.File.ReadAllLines(filePath);
    if(allLines.Length > 0)
    textBox1.Text = allLines[0];

    if(allLines.Length > 1)
    textBox2.Text = allLines[1];

    if(allLines.Length > 2)
    textBox3.Text = allLines[2];

OTHER TIPS

string[] lines = File.ReadAllLines("YourPath");
textbox1.Text = lines.ElementAtOrDefault(0);
textbox2.Text = lines.ElementAtOrDefault(1);
textbox3.Text = lines.ElementAtOrDefault(2);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top