Problems Updating label Value

D

directory

hey guys,

I've got a weird one for ya....i have a form which takes user input in
the form of textbox's etc. It then grabs some details from a file and
updates some of the labels with some info like numbers etc.

Anyway, i'm just updating the field properties like lblnumber.Text =
variable1;

Now the weird thing is that...when i run the app and it cycles through
some loops it never updates the values of those fields...even though
they havent thrown an error. So I checked if the loop was even running
by adding a messagebox.showpop up and sure enough its def running but
the text labels and textboxes dont change.

Any ideas why?
 
P

Peter Duniho

[...]
Now the weird thing is that...when i run the app and it cycles through
some loops it never updates the values of those fields...even though
they havent thrown an error. So I checked if the loop was even running
by adding a messagebox.showpop up and sure enough its def running but
the text labels and textboxes dont change.

Any ideas why?

The two most common reasons this happens:

* The code is using the wrong form instance. Usually because the
programmer gets the form instance by calling "new Form1()" (where
"Form1" is the name of the form class). You need to make sure you are
using the instance that already exists, rather than creating a new one.

* The code is trying to access the form from the wrong thread.
This is much less common in .NET 2.0 and later, because when you are
running under the debugger you get an MDA exception telling you that
you're doing this, and that it's wrong to do so.

So, assuming you're using .NET 2.0 or later, I'd put my money on the
first option.

If neither apply, then you need to post a concise-but-complete example
of code that demonstrates your problem.

Pete
 
S

Steven Rowland

Hi! Yeah this seems really weird...Okay so its not updating any of the
text fields when I run it..it seems to be something to do with teh
while loop because when i comment out the while loop statements...the
first field...total counts does indeed update.

Any ideas?


public frmMainPage()
{
InitializeComponent();
}

private void quitToolStripMenuItem_Click(object sender,
EventArgs e)
{
Close();

}

private void panel1_Paint(object sender, PaintEventArgs e)
{

}

private void btnStart_Click(object sender, EventArgs e)
{
// Save Form Variables upon startclick

String Name = this.txtName.Text;
String Email = this.txtEmail.Text;
String Url = this.txtURL.Text;
string Comment = this.txtComment.Text;
int test = 0;
int ctr = 0;
string read = null;
string UrlGrab = null;
string postvar = "&newname=" + Name + "&newmail=" + Email
+ "&newloc=65&newurl=" + Url + "&newtext=" + Comment;
int TotalCount;

// Grab the URL totals out of the method
TotalCount = staticclass.Counter();
this.lblTotalCount.Text = Convert.ToString(TotalCount);

// Set progress bar maximums
progressBar1.Maximum = TotalCount;

// Open Stream
StreamReader tr = File.OpenText("url.txt");


// Start the loop

while (test == 0)
{
string textcount = Convert.ToString(ctr);
this.txtsucess.Text = textcount;


// Increment Counter Variable
ctr++;

// grab the first line from file
read = tr.ReadLine();

// assign value of grab to a string

UrlGrab = read;


// Set Post Variables Tuned For Achim Winkler
byte[] buffer =
Encoding.ASCII.GetBytes("&newname=" + Name + "&newmail=" + Email +
"&newloc=65&newurl=" + Url + "&newtext=" + Comment);

// Initialise HTTP Request and Method

HttpWebRequest WebReq =
(HttpWebRequest)WebRequest.Create(UrlGrab);

// Set WebRequest Method ie post or Get

WebReq.Method = "POST";

// Set the content typeof the form

WebReq.ContentType = "application/x-www-form-
urlencoded";

//The length of the buffer (postvars) is used as
contentlength.

WebReq.ContentLength = buffer.Length;

//We open a stream for writing the postvars

Stream PostData = WebReq.GetRequestStream();

//Now we write, and afterwards, we close.
Closing is always important!

PostData.Write(buffer, 0, buffer.Length);
PostData.Close();

//Get the response handle, we have no true
response yet!

HttpWebResponse WebResp =
(HttpWebResponse)WebReq.GetResponse();

//Let's show some information about the
response

// Console.WriteLine(WebResp.StatusCode);
// Console.WriteLine(WebResp.Server);

//Now, we read the response (the string), and
output it.

Stream Answer = WebResp.GetResponseStream();

StreamReader _Answer = new
StreamReader(Answer);

// Console.WriteLine(_Answer.ReadToEnd());

// Update Status Bar

progressBar1.Value = progressBar1.Value +
1;


// Update exit part of loop
if (read == "end")
{
test++;
}



}

// close the text readerstream
tr.Close();


[...]
Now the weird thing is that...when i run the app and it cycles through
some loops it never updates the values of those fields...even though
they havent thrown an error. So I checked if the loop was even running
by adding a messagebox.showpop up and sure enough its def running but
the text labels and textboxes dont change.
Any ideas why?

The two most common reasons this happens:

* The code is using the wrong form instance. Usually because the
programmer gets the form instance by calling "new Form1()" (where
"Form1" is the name of the form class). You need to make sure you are
using the instance that already exists, rather than creating a new one.

* The code is trying to access the form from the wrong thread.
This is much less common in .NET 2.0 and later, because when you are
running under the debugger you get an MDA exception telling you that
you're doing this, and that it's wrong to do so.

So, assuming you're using .NET 2.0 or later, I'd put my money on the
first option.

If neither apply, then you need to post a concise-but-complete example
of code that demonstrates your problem.

Pete
 
M

Marc Gravell

First off; "using"... look into it ;-p Actually, since you aren't
closing everything cleanly, there could be some kind of saturation
going on here? How many urls are we talking about?

Second - WebClient; could possibly make your http work a *lot* simpler
- but sometimes it over-manages (i.e. doesn't provide access to some
obscure facet that you want).

Re the code... are you sure it is running to completion? i.e. if you
put a MessageBox.Show right at the end, does that display? Basically,
the form cannot redraw itself while it is busy with your method, so if
your method takes an age to run, nothing interesting will happen on
the form until it is complete. In such circumstances, a
BackgroundWorker or similar may be in order, along with some
this.Invoke(...) calls to update UI components (although
BackgroundWorker.ReportProgress would be enough for progressbar1).

Marc
 
P

Peter Duniho

Steven said:
Hi! Yeah this seems really weird...Okay so its not updating any of the
text fields when I run it..it seems to be something to do with teh
while loop because when i comment out the while loop statements...the
first field...total counts does indeed update.

I believe that Marc's observation hits the nail on the head. I presume
that the issue here is that the text labels don't update while the loop
is running; presumably if your loop eventually reads the "end" line and
exits, the labels are finally updated (to the last value they were set to).

This is because until your btnStart_Click() method returns, no UI
updating will be done.

As a quick hack to test the theory, you can add a call to
Control.Update() (using the "txtsuccess" control instance) or
Application.DoEvents(), which would allow the update to be made visible
on the screen. However, this technique is a very bad idea for an actual
application someone will use.

Better would be to put the code that's taking a long time into a
BackgroundWorker thread, just as Marc suggest. From there, you can use
Control.Invoke() or Control.BeginInvoke() to update text labels, and the
ReportProgress event to allow the progress bar to be updated.

By the way, the fact that you are doing all of this processing inside of
a loop executed in the Click event handler of a control is essential to
the problem description. Your original post was not clear on this
point; I hope you can see from this how important it is to at least be
very specific about the situation, if not post code (as you did in the
follow-up).

Pete
 
S

Steven Rowland

Thanks guys!

Looks like ive got alot of hacking around to do then :)

Its funny...a textbook can really only show you so much. Until you
actually get into the technology and applying it all these sort of
little problems dont crop up. Clearly, C# textbooks cant teach you to
be a great programmer or to design really good logic.

Thanks for bearing with my newbie questions :)

steve
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top