C# how to show available data one by one in textbox - c#

Hi I am using HtmlAgilityPack to scrap some data from web using c# . Here is the code :
private void button1_Click(object sender, EventArgs e)
{
var url = this.textBox1.Text;
var webGet = new HtmlWeb();
var document = webGet.Load(url);
var metaTags = document.DocumentNode.SelectNodes("//meta");
if (metaTags != null)
{
foreach (var tag in metaTags)
{
var name = tag.Attributes["name"].Value;
var content = tag.Attributes["content"].Value;
this.textBox2.Text = name + " : " + content;
}
}
}
its getting a link from textbox1 and showing the output to textbox2 . Its showing the last available data . I can concate the available data but it will show all data at once. Actually I want to show one data when it is available while others are being processed so that user can realize the scrapping progress.Would anyone please help ??

Assuming the first half of your code is correct, this will show the data one-by-one. Most likely, the foreach loop is executing too quickly for you to notice the "one-by-one" effect.
You could apply an artificial delay if you need to display each result long enough for someone to read. Maybe with a Timer or something similar.
An alternative is to use a multi-line textbox (for example a RichTextBox) and place each result on a new-line. Or a ComboBox, which won't take up as much room. These options allow you to keep the data, without having to overwrite it.

You can user Timer control to delay the display of next value in the loop.
You can also use BackgroundWorker to get this done. However this would add complexity to your code. Please look at Beginners Guide to Threading in .NET: Part 5
Or you can use Thread.Sleep(xx) which will delay the execution for the milliseconds you specify.
Thread.Sleep(2000);
this.textBox2.Text += name + " : " + content + Environment.NewLine;

Related

Passing Variable from one WPF Window to Another (C#)

I really feel bad for having to ask this. The answer should probably be obvious; however, I have searched here and on Google to no avail.
I am quite new to WPF. With Windows Forms, I recall it was quite easy to pass data between Windows, but I cannot figure it out with my WPF application.
I am simply building an application for myself that will allow me to access and insert data in a MySQL database. When the button I have added to view all the records in a table is clicked, I want a new window to open. This window will simply display all the data; the table will be selected in MainWindow.
The problem I have is this: I need someway for the secondary window (View) to know which table was selected. I will probably use a ListBox control for table selection, but at the end of the day it really does not matter. Eventually, the value will be stored as a string in a variable. I need the View window to be able to access this string so it knows which table to query. In example:
// Main Window
private void viewButton_Click(object sender, RoutedEventArgs e)
{
var table = "DS";
View viewWindow = new View();
viewWindow.Show();
}
// View Window
private void windowLoad(object sender, RoutedEventArgs e)
{
DatabaseConnection myConnection = new DatabaseConnection();
List<string>[] result = myConnection.Select(table);
text.Text = MainWindow.test + (result[0][0] + " " + result[1][0] + " " + result[2][0] + " " + result[3][0]);
}
All I need to do is to pass the value of table (which will vary in the final application based on user input), to View. For example, I need it so that in the above code, the following would be executed:
List<string>[] result = myConnection.Select("DS");
I feel like this should be obvious and easy, but I am not sure how to accomplish this. I would sincerely appreciate any help.
You can pass a variable through constructor, like this
public View(string table)
{
this.table = table;
}
And when you initialize your window:
var table = "DS";
View viewWindow = new View(table);
viewWindow.Show();

Select one string line in a list

I'm trying to simply select one string line out a long list strings that are held on a server and seperated with a pipe character. This string is grabbed by a php script and the string line is a list of all the media and folders I have on my server.
In my code I'm getting this information and returning it with the following code:
using (var client = new WebClient())
{
result = client.DownloadString("http://server.foo.com/images/getDirectoryList.php");
}
textBox1.Text = string.Join(Environment.NewLine, result.Split('|'));
And it looks like this:
But when I try to simply click on one of them, my cursor simply just goes to where I've clicked. Like this, I tried to select md-harrier.jpg and my cursor just ends up at the end of jpg:
What I'm really wanting is pictured below. I click on Koala.jpg and the whole thing is highlighted and I have the ability to store the name of what it is I've just clicked on. TO achieve that screen shot I had to click next to Koala.jpg and then drag my mouse along.
Is there anyway I can achieve what I want to achieve?
The key thing to note about this is that I will have no idea how many files will be on the server, nor what they will be called. My php script is grabbing this information and displaying it in my winform text box using the code I have wrote above.
as Simon said you need a ListBox, a ListBox fits here because it allows you to select a line, and you can register to the event of SelectedIndexChanged and store the name that was selected.
to initiate the values do
using (var client = new WebClient())
{
result = client.DownloadString("http://bender.holovis.com/images/getDirectoryList.php");
}
listBox1.Items.AddRange(result.Split('|'));
listBox1.SelectedIndexChanged += new System.EventHandler(this.listBox1_SelectedIndexChanged);
and on the selectedItemChanged:
string currVal;
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
currVal = (string)listBox1.SelectedItem;
}
As you said you have no reason to use TextBox,then by using ListBox you can achieve that in this way;
using (var client = new WebClient())
{
result = client.DownloadString("http://bender.holovis.com/images/getDirectoryList.php");
}
string[] names=result.Split('|');
foreach(string name in names)
{
if(name!="|"&&name!=" ")
{
listbox.Items.Add(name);
}
}
Additionally,if you would like to store selected item in a variable subscribe to ListBox's SelectionChangedEvent and store the selection index in a variable in this way;
int selection=;
private void ListBox1_SelectionIndexChanged(object sender,EventArgs e)
{
selection=ListBox1.SelectedIndex;
}

pass parameters to webbrowser control during foreach loop does not work

I have a WebBrowser Control on a C# Windows Form which gets a few parameter. Because of some Ajax Content the webbrowser raise the DocumentCompleted multiple times. In addition to that the webpage where I fill some values in form fields (this is what mean with passing parameters to control) loads not very fast i have a timer which runs every 2 secs to try to fill the values. So far so good but now I have different values which I need to pass to the form and the website needs to be loaded again.
I am having those values in a list which I go through using a foreach loop. The problem is that the foreachloop is too fast so that the webbrowser control only gets the last value of that list.
I hope you guys understand what I mean. Do you have some recommendations/tips/tricks what I should do to fix this?
Thanks!
EDIT: Below is the code of the foreach which triggers the Timer at the end which then goes through the process of loading the page, passing parameters and so on...
foreach (string routeFrom in lstRoutesFrom)
{
string routeTo = lstRoutesTo[lstRoutesFrom.IndexOf(routeFrom)].ToString();
//Prepare Data...
this.requestAirportFrom = routeFrom;
this.requestAirportTo = routeTo;
string dd = "13";
string mm = "07";
string yyyy = "2012";
string date = dd + "/" + mm + "/" + yyyy;
this.requestDate = date;
this.globalStep = 0;
listAirline.Clear();
listArrAirports.Clear();
listArrTime.Clear();
listDepAirports.Clear();
listDepTime.Clear();
listFlightNumbers.Clear();
listFlightPrices.Clear();
btnTimer.Enabled = true;
}
Your foreach is not 'too fast', it's simply incorrect.
foreach (string routeFrom in lstRoutesFrom) // this gets multiple 'routeFrom' values
{
//Prepare Data...
this.requestAirportFrom = routeFrom; // and now (over)write all to the same place
....
}
Only the last routeFrom is saved in the (1) this.requestAirportFrom location.
Based on your question : The problem is that the foreachloop is too fast so that the webbrowser control only gets the last value of that list.
WebBrowser Control have DocumentCompleted Event you can make use of it to pass one item at a time
See example on MSDN

TextBlock refuses ~70% of the time to make a hyperlink

Really really odd problem, in short, I'm doing a foreach over every word in a textblock, if that word starts with for example "#" I want to make a username hyperlink out of it. However in about 70% of the cases it replaces the text fine, but it just doesn't become a hyperlink.
Partial code:
private void UserControl_Loaded(object sender, RoutedEventArgs e)
{
var kaas = Tweet.Split(' ');
foreach (string a in kaas)
{
if (a.StartsWith("#"))
{
Hyperlink uname = new Hyperlink();
uname.NavigateUri = new Uri("http://twitter.com/" + "xarinatan");
uname.RequestNavigate += new RequestNavigateEventHandler(Hyperlink_RequestNavigateEvent);
uname.Inlines.Add("ASDAS");
TweetBlock.Inlines.Add(uname);
//TweetBlock.Inlines.Add(Username(a));
TweetBlock.Inlines.Add(" ");
}
}
}
Above code turns all instances that start with "#" into "ASDAS" but fails most of the time to properly convert it to a hyperlink, HOWEVER it DOES convert it SOMETIMES.
It's completely beyond me how it only works sometimes, instead of all the time or not at all.
All suggestions are welcome!
edit: To clarify, it -always- replaces the text with 'ASDAS', but in 70% of the cases it doesn't become a hyperlink.
My friend found the answer. Somehow inlines being added as string causes sporadic behavior, they have to be added as a 'Run'.
Fix can be found here: https://github.com/zahndy/o3o/commit/68b50f8c0ea106bcc709d3f69658b28da9c8a9d4#diff-3
Thanks all for the suggestions!

Windows Phone Emulator Functions Properly, Debugging or Deploying to Device Does Not

I am developing a very simple application that parses an XML feed, does some formatting and then displays it in a TextBlock. I've added a hyperLink (called "More..) to the bottom of the page (ideally this would be added to the end of the TextBlock after the XML has been parsed) to add more content by changing the URL of the XML feed to the next page.
The issue I'm experiencing is an odd one as the program works perfectly when in the Windows Phone 7 Emulator, but when I deploy it to the device or debug on the device, it works for the first click of the "More..." button, but the ones after the first click just seem to add empty space into the application when deployed or debugged from the device.
I'm using a Samsung Focus (NoDo) and originally thought this may have had to do with the fact that I may not have had the latest developer tools. I've made sure that I am running the latest version of Visual Studio and am still running into the issue.
Here are some snippets of my code to help out.
I've declared the clickCount variable here:
public partial class MainPage : PhoneApplicationPage
//set clickCount to 2 for second page
int clickCount = 2;
Here is the snippet of code I use to parse the XML file:
void client_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
if (e.Error == null)
{
ListBoxItem areaItem = null;
StringReader stream = new StringReader(e.Result);
XmlReader reader = XmlReader.Create(stream);
string areaName = String.Empty;
while (reader.Read())
{
if (reader.NodeType == XmlNodeType.Element)
{
if (reader.Name == "example")
{
areaName = reader.ReadElementContentAsString();
areaItem = new ListBoxItem();
areaItem.Content = areaName;
textBlock1.Inlines.Add(areaName);
textBlock1.Inlines.Add(new LineBreak());
}
}
}
}
}
and the code for when the hyperLink button is clicked:
private void hyperlinkButton1_Click(object sender, RoutedEventArgs e)
{
int stringNum = clickCount;
//URL is being incremented each time hyperlink is clicked
string baseURL = "http://startofURL" + stringNum + ".xml";
Uri url = new Uri(baseURL, UriKind.Absolute);
WebClient client = new WebClient();
client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(client_DownloadStringCompleted);
client.DownloadStringAsync(url);
//increment page number
clickCount = clickCount + 1;
}
It feels like there's a little more debugging to do here.
Can you test where exactly this is going wrong?
is it the click that is not working on subsequent attempts?
is it the HTTP load which is failing?
is it the adding of inline text which is failing?
Looking at it, I suspect it's the last thing. Can you check that your TextBlock is expecting Multiline text? Also, given what you've written (where you don't really seem to be making use of the Inline's from the code snippet I've seen), it might be easier to append add the new content to a ListBox or a StackPanel rather than to the inside of the TextBlock - ListBox's especially have some benefit in terms of Virtualizing the display of their content.

Categories

Resources