473,383 Members | 1,818 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,383 software developers and data experts.

Updating Label Value and Recursing Through Directories

http://msdn.microsoft.com/en-us/library/806sc8c5.aspx

The URL above gives sample code for use within a Console Application. What
I would like to do is use this code within a Windows Form. That part is
easy. The part that I am having trouble with is using the code in a form
and having a Label's Text property update as a new directory or file is
found.

What I keep getting is the work being done before it is shown to the user
via the Form.Show() method actually shows the form. I want the results to
be displayed as it is happening.

Can someone provide me with some guidance please?

Thank you!
Edwin

Jun 27 '08 #1
4 1869
On May 13, 12:49*pm, "Edwin Velez" <ed...@nospam.nospamwrote:
http://msdn.microsoft.com/en-us/library/806sc8c5.aspx

The URL above gives sample code for use within a Console Application. *What
I would like to do is use this code within a Windows Form. *That part is
easy. *The part that I am having trouble with is using the code in a form
and having a Label's Text property update as a new directory or file is
found.

What I keep getting is the work being done before it is shown to the user
via the Form.Show() method actually shows the form. *I want the results to
be displayed as it is happening.

Can someone provide me with some guidance please?

Thank you!
Edwin
Hi,

You have to create a new thread, then from the thread you can update
the label text (you HAVE to use Control.Invoke) to refresh the text.

Take a look in the archives of this NG for Control.Invoke
Jun 27 '08 #2
On May 13, 12:49 pm, "Edwin Velez" <ed...@nospam.nospamwrote:
http://msdn.microsoft.com/en-us/library/806sc8c5.aspx

The URL above gives sample code for use within a Console Application. What
I would like to do is use this code within a Windows Form. That part is
easy. The part that I am having trouble with is using the code in a form
and having a Label's Text property update as a new directory or file is
found.

What I keep getting is the work being done before it is shown to the user
via the Form.Show() method actually shows the form. I want the results to
be displayed as it is happening.

Can someone provide me with some guidance please?

Thank you!
Edwin
I am not sure if this is going to work.. but you can try calling

Application.DoEvents() after setting the labels text property.
Jun 27 '08 #3
On Tue, 13 May 2008 10:55:31 -0700, Ignacio Machin ( .NET/ C# MVP )
<ig************@gmail.comwrote:
On May 13, 12:49Â*pm, "Edwin Velez" <ed...@nospam.nospamwrote:
>[...]
What I keep getting is the work being done before it is shown to the
user
via the Form.Show() method actually shows the form. Â*I want the results
to
be displayed as it is happening.

You have to create a new thread, then from the thread you can update
the label text (you HAVE to use Control.Invoke) to refresh the text.

Take a look in the archives of this NG for Control.Invoke
In addition to Ignacio's very good advice, you may want to consider only
updating the Label.Text property at regular intervals. Either every 500
ms, every 1000 iterations, etc. (just to mention some examples).
Attempting to update the Label with every single file or directory will
unnecessarily constrain the speed of the actual work being done (that is,
the recursion through the directory structure), as your program will spend
much of its time changing the visual display of the Label as its Text
property changes (it won't show every possible Text value on-screen, but
it will spend a lot of time trying to :) ).

Pete
Jun 27 '08 #4
Hi Edwin,

Thank you for posting here!

I notice that you post the same issue in the
microsoft.public.dotnet.framework.windowforms newsgroup, which I have
replied to. For your convenience, I include the reply here.

=========================================
Based on my understanding, you want to display the results to Labels while
counting the directories and files under a given foler. If I'm off base,
please feel free to let me know.

By default, a Windows Forms Application runs on a single thread, i.e. the
UI thread, which manages all the UI objects and UI painting stuff. So when
a long calculation is performing, the UI will be blocked, and the text of
the Label won't be update until the calculation finished.

To make the UI thread free for painting the interface, we can transfer the
heavy calculation work into a separate thread. Here, we have many ways for
the threading stuff.

.NET 2.0 has introduced a BackgroundWorker component which provides a
concise multiple-threads programming model and is very easy to use. If
you're using .NET 2.0, I suggest you use the BackgroundWorker component in
your application.

In detail, call the BackgroundWorker's RunWorkerAsync method to raise the
DoWork event. In the DoWork event handler, perform the time-consuming work.
While doing the work, call the ReportProgress method to raise the
ProgressChanged event. In the ProgressChanged event handler, update the
two Labels. When the background work is done, the RunWorkerCompleted event
is fired. We also need to udpate the Labels in the RunWorkerCompleted event
handler.

The following is a sample. It requires you add two Labels and a Button on
the Form.

public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)
{
BackgroundWorker backgroundWorker1 = new BackgroundWorker();
backgroundWorker1.WorkerReportsProgress = true;
backgroundWorker1.DoWork += new
DoWorkEventHandler(backgroundWorker1_DoWork);
backgroundWorker1.ProgressChanged += new
ProgressChangedEventHandler(backgroundWorker1_Prog ressChanged);
backgroundWorker1.RunWorkerCompleted += new
RunWorkerCompletedEventHandler(backgroundWorker1_R unWorkerCompleted);
backgroundWorker1.RunWorkerAsync();
}

void backgroundWorker1_RunWorkerCompleted(object sender,
RunWorkerCompletedEventArgs e)
{
// Display the results to the Labels.
label1.Text = string.Format("Directories: {0}", directories);
label2.Text = string.Format("Files: {0}", files);
}

void backgroundWorker1_ProgressChanged(object sender,
ProgressChangedEventArgs e)
{
// Display the results to the Labels.
label1.Text = string.Format("Directories: {0}", directories);
label2.Text = string.Format("Files: {0}", files);
}

void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
try
{
string directory = "directorypath";
DirectoryInfo dir = new DirectoryInfo(directory);

if (!dir.Exists)
{
throw new DirectoryNotFoundException("The directory
does not exist.");
}

FileSystemInfo[] infos = dir.GetFileSystemInfos();

BackgroundWorker worker = sender as BackgroundWorker;
ListDirectoriesAndFiles(worker, infos);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
finally
{
}
}

static long files = 0;
static long directories = 0;

private void ListDirectoriesAndFiles(BackgroundWorker worker,
FileSystemInfo[] FSInfo)
{
if (FSInfo == null)
{
throw new ArgumentNullException("FSInfo");
}

foreach (FileSystemInfo i in FSInfo)
{
if (i is DirectoryInfo)
{
directories++;
DirectoryInfo dInfo = (DirectoryInfo)i;
ListDirectoriesAndFiles(worker,
dInfo.GetFileSystemInfos());
}
else if (i is FileInfo)
{
files++;
}
if (directories % 10 == 0)
{
// report the work progress
// because we only want to raise the ProgressChanged
event to update the labels
// and don't care the percent of the work that has been
done in this scenario,
// we pass 0 to the ReportProgress method.
worker.ReportProgress(0);
}
}
}
}

For more information on the BackgroundWorker component, please refer to the
following MSDN document:
http://msdn.microsoft.com/en-us/libr...backgroundwork
er.aspx
================================================== =====

If you have any question, please reply to that thread and I will follow up
with you in time.

Thank you for using our MSDN Managed Newsgroup Support Service!

Sincerely,
Linda Liu
Microsoft Online Community Support

Delighting our customers is our #1 priority. We welcome your comments and
suggestions about how we can improve the support we provide to you. Please
feel free to let my manager know what you think of the level of service
provided. You can send feedback directly to my manager at:
ms****@microsoft.com.

==================================================
Get notification to my posts through email? Please refer to
http://msdn.microsoft.com/subscripti...ult.aspx#notif
ications.

Note: The MSDN Managed Newsgroup support offering is for non-urgent issues
where an initial response from the community or a Microsoft Support
Engineer within 1 business day is acceptable. Please note that each follow
up response may take approximately 2 business days as the support
professional working with you may need further investigation to reach the
most efficient resolution. The offering is not appropriate for situations
that require urgent, real-time or phone-based interactions or complex
project analysis and dump analysis issues. Issues of this nature are best
handled working with a dedicated Microsoft Support Engineer by contacting
Microsoft Customer Support Services (CSS) at
http://msdn.microsoft.com/subscripti...t/default.aspx.
==================================================
This posting is provided "AS IS" with no warranties, and confers no rights.
Jun 27 '08 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

5
by: Raffi | last post by:
Hi folks, I'm new to JavaScript and need some help. I have a form with a select field. Depending on what is selected in this field, I want to display or not display another select field. For...
10
by: sqlboy2000 | last post by:
Hello all, I have something very simple going on here and I'm scratching my head as to what the problem is. There are 4 items in my project, 2 webforms, a user control, and a module: ...
5
by: Mark R. Dawson | last post by:
Hi all, I may be missing something with how databinding works but I have bound a datasource to a control and everything is great, the control updates to reflect the state of my datasource when I...
0
by: Michael Kellogg | last post by:
I have a problem wherein a query that updates a GridView doesn't seem to really stay in sync with a label I have above the GridView. I have a GridView object that I'm updating with information...
5
by: teclioness | last post by:
Hi, I am using gridview and sql datasource for select and update. When I click on edit link against the records, the row is shows in edit mode. When I make a change to it, the change is not...
0
by: Mike P | last post by:
I have a formview which has exactly the same parameters as a detailsview, but I get an error when I try to update when editing the formview. Here are my update parameters : <UpdateParameters>...
3
by: sreemakam | last post by:
Hello, I am a li'l new to perl scripting and I am trying to write a script which can give me the result in a particular format. I need to generate all the directories as well as the subdirectories...
4
by: =?Utf-8?B?QmFyYmFyYSBBbGRlcnRvbg==?= | last post by:
I setup a simple gridview as a utility just to do some updates, nothing fancy just wanted easy UI to make updates. When I select ‘Edit’, I get the fields I want to edit. I edit them and click...
1
by: cerilocke | last post by:
I have a repeater in which I have a hidden field (input type = hidden), a textbox (asp:TextBox), a checkbox (input type = checkbox) and a label (asp:Label). I have bound all four items to the same...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.