Changing label text on button click that also executes other methods - c#

I am trying to update a label on my windows form with statistics from another methods execution that scrapes a webpage and creates a zip file of the links and creates a sitemap page. Preferably this button would run the scraping operations and report the statistics properly. Currently the scraping process is working fine but the label I want to update with statistics data is not changing on the button click. Here is what my code looks like now:
protected void btn_click(object sender, EventArgs e)
{
//Run scrape work
scrape_work(sender, e);
//Run statistics work
statistics(sender, e);
}
protected void scrape_work(object sender, EventArgs e)
{
//Scraping work (works fine)
}
protected void statistics(object sender, EventArgs e)
{
int count = 0;
if (scriptBox.Text != null)
{
count += 1;
}
var extra = eventsBox.Text;
var extraArray = extra.Split('\n');
foreach (var item in extraArray)
{
count += 1;
}
//scrapeNumLbl is label I want to display text on
scrapeNumLbl.Text = count.ToString();
}
Would I have to use threading for this process or is there some other way I can get this process to work? I have already tried this solution but was having the same issue where the code runs but the label does not update. Any help would be greatly appreciated, this minor thing has been bugging me for hours now.

I eventually solved this by writing the path to the zip file to a label button on the form rather than sending it right to download on the client's browser on button click. The issue was that the request was ending after the zip file was sent for download. To ensure that both methods ran at the proper time I moved the call to the scrape_work method to inside of of statistics
In order for the path to be clickable and the file to download properly I had to make the "label" in the form a LinkButton in the .aspx page
<asp:LinkButton ID="lblDownload" runat="server" CssClass="xclass" OnClick="lblDownload_Click"></asp:LinkButton>
And made the lblDownload_Click run like the following:
Response.Clear();
Response.BufferOutput = false;
Response.ContentType = "application/zip";
Response.AddHeader("content-disposition", "attachment; filename=zipFiles.zip");
string folder = Server.MapPath("~/zip");
string endPath = folder + "/zipFiles.zip";
Response.TransmitFile(endPath);
Response.End();
Running it this way the page reloads with the new labels properly written and the zip file available to download as well.

ASSUMING THIS CODE IS RUNNING SYNCHRONOUSLY (you aren't threading the scraping in a call I don't see), Are you sure you are reaching the code that sets the label text? I simplified your code as below (removing the iteration over the array and just setting the label text to a stringified integer) and am not having any trouble changing the text of a label.
namespace SimpleTest
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
scrape_work(sender, e);
statistics(sender, e);
}
protected void scrape_work(object sender, EventArgs e)
{
//Scraping work (works fine)
}
protected void statistics(object sender, EventArgs e)
{
int count = 666;
scrapeNumLbl.Text = count.ToString();
}
}
}
Result:

Related

Program for learning foreign words C#

I am in the process of writing a vocabulary program. C # Windows Form.
Description of the program operation:
Use the buttons to select the location of text files with the words "PL" and "ENG". (two separate files)
Click the start button to start the program
the first word from the board appears in the label
I'm translating the word into the textbox and the Messagebox "OK" or "WRONG" pops up
And here a problem arises. The program instead of every time I wait until I introduce a new word to the textbox, it loops, the questions in the label are changed and MessageBox displays.
How best to do this to make the program work correctly? `` `[
private void sprawdzButton_Click(object sender, EventArgs e)
{
BazaSlow.bazaPolskichSlowek = _fileReader.Read(adresPlikuPL);
BazaSlow.bazaAngielskichSlowek = _fileReader.Read(adresPlikuANG);
string odpowiedz = odpTextBox.Text;
int i = 0;
while (i < BazaSlow.bazaPolskichSlowek.Length)
{
trescSlowkaLabel.Text = BazaSlow.bazaPolskichSlowek[i];
if (odpowiedz.Equals(BazaSlow.bazaAngielskichSlowek[i].ToLower()))
{
MessageBox.Show("OK");
}
else
{
MessageBox.Show("ŹLE");
}
i++;
}
}
This approach will not quite work.
If you use WinForms then you can do it via events. I'll quickly use english variable names since I don't speak your language.
This could be one approach to do it: I used the "TextChanged" event from the textBox.
string[] wordsLanguage1;
string[] wordsLanguage2;
int currentIndex = 0;
private void Form1_Load(object sender, EventArgs e)
{
wordsLanguage1 = System.IO.File.ReadAllLines("somePath1");
wordsLanguage2 = System.IO.File.ReadAllLines("somePath2");
}
private void ReportAndCheckInput(string input)
{
if (input.ToLower().Equals(wordsLanguage2[currentIndex].ToLower())) {
//right translation
currentIndex++;
label1.Text = wordsLanguage1[currentIndex];
textBox1.Text = "";
}
else
{
//wrong translation
}
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
ReportAndCheckInput(textBox1.Text);
}
Now this approach uses the TextChanged event. So the ReportAndCheckInput method will be called on every text-change. That means that your Feedback would pop up on every keystroke which would not be nice. You could use any other event instead of TextChanged. For example a button click. Another solution would be to use a label for your feedback and not a message box. Then the user would never have to click anything but woudl instantly see whether or not he was correct.

System.FormatException occurred in mscorlib.dll when converting it int32

I know, i know there are lots and lots of questions asking on here about this error, each with their own response, but its easier to work off a response regarding your own code rather than someone else's
I have been working on this program for some time for a college assignment, and as soon as i started putting in the class to calculate the totals of things it now crashes,
I don't know where to look so i'll post my main code
enter code here
namespace Till
public partial class MainWindow : Window
{
Calculator calc = new Calculator();
public MainWindow()
{
InitializeComponent();
}
public bool User;
public bool tillopen = false;
private void button_Click(object sender, RoutedEventArgs e)
{
//button clone thingy
Button btn = (Button)sender;
label.Content = label.Content + btn.Content.ToString();
Console.Beep(); // makes the buttons beep
}
private void clear_Click(object sender, RoutedEventArgs e)
{
// Clear
label.Content = "";
}
private void Button_Submit_Click(object sender, RoutedEventArgs e)
{
// submit
listView.Items.Add(label.Content);
label.Content = "";
calc.setSoldItems(Convert.ToInt32(label.Content)); /// it breaks on this line///
}
private void button13_Click(object sender, RoutedEventArgs e)
{
//void sale
label.Content = "";
listView.Items.Clear();
}
private void button15_Click(object sender, RoutedEventArgs e)
{
//pound
label.Content = "1.00";
}
private void button12_Click(object sender, RoutedEventArgs e)
{
//till open close
tillopen = true;
}
private void button16_Click(object sender, RoutedEventArgs e)
{
Login m = new Login();
m.Show();
this.Close();
}
private void button14_Click(object sender, RoutedEventArgs e)
{
label.Content = "2.00"; // 2 pound
}
private void button17_Click(object sender, RoutedEventArgs e)
{
label.Content = calc.finish();
}
}
I have tried to re-create the error in another WPF (converting a to an int32) and it works fine, i know this is an issue with my code itself, i have tried using other machine and using different versions of visual studio itself, so we came to the assumption its this code itself and not a broken dll file
So before I sit down with my Teacher and spend all day going though my code step by step im asking around for help in order to save both of our time, This assignment is due in in 3 weeks, and it decides to break on me now.
thankies
To replicate this error, i press a number button on my Windows form, them hit the submit button i created (which starts the conversion) If a copy of my class which handles all of this is needed im happy to post it
In the method button_click, you have assigned value as
label.Content = label.Content + btn.Content.ToString();
which is a string value to the label and the values are concatenated instead of add.
and when you are reading it, you are converting it in Int32. which will give exception as it will not contain any integer value to it.
You can add the value like this:
label.Content = (Convert.ToInt32(label.Content) + Convert.ToInt32(btn.Content)).ToString();
and check before converting if the label has blank values in it, if it has do not convert them, and only convert the value if it has some values it will not give any error. Also do not assign any values other that numerical digits.
You are calculating:
Convert.ToInt32(label.Content)
but on the line before you set:
label.Content = "";
so this means you are calculating
Convert.ToInt32("")
which gives you a FormatException.
Perhaps you should use the value of label.Content before you overwrite it?

Open form if page in webBrowser contains string

I'm quite new to C# and I'm working on a form that logs into a website, navigates to a specific page and then it should check if that page contains the words "Registered Plus" (This all in a webBrowser) Now I got this all working, except for the last part. I have been thinking and searching for hours about how to make my application check if the current webpage contains "Registered Plus"... This is my code for the button so far:
private void btnReboot_Click(object sender, EventArgs e)
{
webBrowser1.Document.GetElementsByTagName("input").GetElementsByName("username")[0].SetAttribute("value", usernameBox.Text);
webBrowser1.Document.GetElementsByTagName("input").GetElementsByName("password")[0].SetAttribute("value", passwordBox.Text);
webBrowser1.Document.GetElementsByTagName("input").GetElementsByName("submit")[0].InvokeMember("click");
webBrowser1.Navigate("http://website.com/login.php?action=login");
}
Does anyone know how to make it check if this page: http://website.com/login.php?action=login contains "Registered Plus" ? Or maybe a tutorial about how to do something similar to this? Thanks alot in advance. Have been stuck on this part for quite a while now..
UPDATE:
Got a comment telling me about DocumentText.Contains, tried this:
private void btnReboot_Click(object sender, EventArgs e)
{
webBrowser1.Document.GetElementsByTagName("input").GetElementsByName("username")[0].SetAttribute("value", usernameBox.Text);
webBrowser1.Document.GetElementsByTagName("input").GetElementsByName("password")[0].SetAttribute("value", passwordBox.Text);
webBrowser1.Document.GetElementsByTagName("input").GetElementsByName("submit")[0].InvokeMember("click");
webBrowser1.Navigate("http://darkbox.nl/usercp.php?action=usergroups");
if (webBrowser1.DocumentText.Contains("Registered Plus"))
{
label3.Text = "You're plus";
}
else
{
label3.Text = "You're not plus";
}
}
However it still tells me "You're not plus"
Am I doing it right this way? Or..
I am not able to test the code right now, but the big issue is that the call to the webBrowser1.Navigate is executed asynchroniously. Just like when you request it in IE or Chrome, it takes anywhere from a second to a minute for the page to load (or give an error.) On the other hand, your C# code takes barely a millisecond to move from the Navigate request to the next line of code.
You need to fire off your code checking the Document once the Navigate() method returns an event indicating it is done.
private bool shouldEvaluateReponse = false;
private void btnReboot_Click(object sender, EventArgs e)
{
webBrowser1.Document.GetElementsByTagName("input").GetElementsByName("username")[0].SetAttribute("value", usernameBox.Text);
webBrowser1.Document.GetElementsByTagName("input").GetElementsByName("password")[0].SetAttribute("value", passwordBox.Text);
webBrowser1.Document.GetElementsByTagName("input").GetElementsByName("submit")[0].InvokeMember("click");
shouldEvaluateResponse = true;
webBrowser1.Navigate("http://darkbox.nl/usercp.php?action=usergroups");
}
public void WebBrowser1_Navigated(object sender, WebBrowserNavigatedEventArgs e)
{
//ignore this method if the flag isn't set.
if (!shouldEvaluateResponse) return;
//reset the flag so this method doesn't keep executing
shouldEvaluateResponse = false;
if (webBrowser1.DocumentText.Contains("Registered Plus"))
{
label3.Text = "You're plus";
}
else
{
label3.Text = "You're not plus";
}
}

Process.Start to open multiple web pages

I am currently using a simple button to open a webpage.
void ReportingClick(object sender, EventArgs e)
{
System.Diagnostics.Process.Start("http://www.google.ca");
}
What I want to do is get it to open 3 pages at once with the one click and I am having a hard time getting it to work. I have tried multiple Process.start lines
void ReportingClick(object sender, EventArgs e)
{
System.Diagnostics.Process.Start("http://www.google.ca");
System.Diagnostics.Process.Start("http://www.gmail.com");
System.Diagnostics.Process.Start("http://www.stackoverflow.com");
}
and even adding multiple pages into the handler.
void ReportingClick(object sender, EventArgs e)
{
System.Diagnostics.Process.Start("http://www.google.ca","http://www.gmail.com","http://www.s tackoverflow.com")
}
It will only open the last page in the list in both cases. Any ideas?
If IE is open, your code works fine and opens each link in a new tab, if not, I was able to make it work by making the app wait for 1 sec before calling the second page to open:
void ReportingClick(object sender, EventArgs e)
{
System.Diagnostics.Process.Start("http://www.google.ca");
System.Threading.Thread.Sleep(1000);
System.Diagnostics.Process.Start("http://www.gmail.com");
System.Threading.Thread.Sleep(1000);
System.Diagnostics.Process.Start("http://www.stackoverflow.com");
}

c# web browser url update

I have created a web browser in c#
this was what i get when i opened my web browser and typed google. Then i searched google for something
the result was like this
But the url wasn't updated in address bar. How to update the address bar when user click on a link on any website in my web browser
In the first image the url was google.com
In the second image url was https://www.google.co.in/#hl=en&output=search&sclient=psy-ab like that some thing but it wasn't updated
You must update the textbox on top with the URL of the WebBrowserControl, using the webBrowser1_Navigating event.
private void webBrowser1_Navigating(object sender, WebBrowserNavigatingEventArgs e)
{
textbox1.text = webBrowser1.Url.ToString();
}
Check http://msdn.microsoft.com/en-us/library/system.windows.forms.webbrowser_events.
I think you can use Navigating event to detect when user starts search or navigates to another page.
The Form_Load must contain this:
private void Form1_Load(object sender, EventArgs e)
{
web = new WebBrowser();
web.Navigated += web_Navigated;
}
and this function:
private void web_Navigated(object sender, WebBrowserNavigatedEventArgs e)
{
textBox1.Text = web.Url.ToString();
}

Categories