Home > Net >  How to append a new line in a textbox when receiving data from an API in C# WinForms
How to append a new line in a textbox when receiving data from an API in C# WinForms

Time:02-23

I'm trying to retrieve data from https://ip-api.com. I have requested multiple variables and would like to append each line of different data. I have a textbox and have requested multiple variables in the same link request.

Let me provide an example of what I have right now.

WebClient wc = new WebClient();
string results = wc.DownloadString("http://ip-api.com/line/?fields=status,message,continent,continentCode,country,countryCode,region,regionName,city,district,zip,lat,lon,timezone,offset,currency,isp,org,as,asname,reverse,mobile,proxy,hosting,query");
textBox1.Text = results;

The output comes as this

successNorth AmericaNAUnited StatesUScensoredForPrivacy

I would prefer it look like this

success
North America
NA
United States
US
CensoredForPrivacy

How can I do this with the way I have provided or is there another way?

CodePudding user response:

The WebClient method DownloadString will append LF newline characters (\n) but a TextBox requires CRLF newline characters (\r\n).

This can be solved by splitting at \n then using AppendText(Environment.NewLine)

string results = wc.DownloadString("http://ip-api.com/line/?fields=status,message,continent,continentCode,country,countryCode,region,regionName,city,district,zip,lat,lon,timezone,offset,currency,isp,org,as,asname,reverse,mobile,proxy,hosting,query");
string[] headers = results.split("\n");
foreach(string s in headers) {
    textBox1.AppendText(s);
    textBox1.AppendText(Environment.NewLine);
}
  • Related