简体   繁体   中英

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);

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}");   

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM