Pratim
Pratim

Reputation: 11

How to add multiple textBox values in a text file (.txt) in c#?

I have used this code, but it is only saving the value for the textBox1. The other two values are not saving. Please check the input and output scenario.

Input:

Name: aaa
College: bbb
Roll: 111

Output:

Name: aaa
College:
Roll:

string[] contents = new string[3];

contents[0] = "Name: " + textBox1.Text;
contents[1] = "College: " + textBox2.Text;
contents[2] = "Roll: " + textBox3.Text;

File.WriteAllLines(@"C:\Users\...\test.txt", contents, Encoding.UTF8);

Upvotes: 0

Views: 412

Answers (1)

Access Denied
Access Denied

Reputation: 9461

I tested your code and it works as expected. Your code is correct. There are two reasons you see problems:

  1. Your textboxes are blank.
  2. You are looking at incorrect file.

Try to print values to debug console, maybe other textboxes are indeed blank.

string[] contents = new string[3];        
contents[0] = $"Name: {textBox1.Text}";
System.Diagnostics.Debug.WriteLine($"text1: {textBox1.Text}");
contents[1] = $"College: {textBox2.Text}";
System.Diagnostics.Debug.WriteLine($"text2: {textBox2.Text}");
contents[2] = $"Roll: {textBox3.Text}";
System.Diagnostics.Debug.WriteLine($"text3: {textBox3.Text}");   

Upvotes: 1

Related Questions