Question:
How do you load a webpage into a textbox in C#?
Cristian
2010-09-21 18:04:59 UTC
I'm having issues with this I just want to load the source of a webpage for example google.com into a textbox (txtsource.text) so you can see the source in the textbox....
Three answers:
Ratchetr
2010-09-21 18:30:26 UTC
This might get you started:

try

{

   var uri = new Uri("http://www.yahoo.com");

   var req = HttpWebRequest.Create(uri);



   var response = req.GetResponse();



   StreamReader sr =new StreamReader( response.GetResponseStream());



   string text = sr.ReadToEnd();

   text = text.Replace("\n", "\r\n");

   sourceTextBox.Text = text;

   response.Close();

}

catch (Exception ex)

{

   Debug.WriteLine("HTTPRequestRunner exception: " + ex.Message);

}



Assumes the text box is named sourceTextBox. sourceTextBox needs to have multiline property set to true, and you'll want scroll bars, of course.



I added the line:

text = text.Replace("\n", "\r\n");

because yahoo only puts line feeds in their source. TextBox won't put in line breaks unless you use have carriage return/linefeed.

TextBox has other limitations that might make the raw HTML response hard to read. A rich text box might be better, but more work.



The catch block should do something more useful than what I did here.



Biggest drawback here is that if you put this in, say, a button click handler, it will freeze your UI until yahoo gets around to sending you your page. Not usually a big deal if you have a good internet connection and Yahoo is having a good day. But on a bad day, that could freeze up your UI for a long period of time, which is bad.



To do it right, you should make this an async request. The button click (or whatever) event kicks off the request, but returns right away. When the request finishes, you update the UI:

var response = req.BeginGetResponse(func,state);

return;



But that gets a bit complicated, and is way beyond the scope of this answer ;-)
Carl
2010-09-21 18:11:47 UTC
I've never tried to have a program get the source directly. If I want the source, I use my browser to view the source code and save it to a text file myself. You could do that if all you're interested in is one specific page. If you need your program to parse several pages, though, you'd want to have it get the source directly, and while I'm sure there's a way to do that in C#, I don't have any experience with that.
2016-04-21 00:29:02 UTC
The easiest way is to use a Range Validator control. Notice: In order to make the field required, you have to add a Required Field validator. i.e. the code above considers that an empty textbox has valid data. Hope this helps


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...