473,804 Members | 3,526 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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 1891
On May 13, 12:49*pm, "Edwin Velez" <ed...@nospam.n ospamwrote:
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.n ospamwrote:
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.DoE vents() 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.n ospamwrote:
>[...]
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.publi c.dotnet.framew ork.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 BackgroundWorke r 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 BackgroundWorke r component in
your application.

In detail, call the BackgroundWorke r'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 RunWorkerComple ted event
is fired. We also need to udpate the Labels in the RunWorkerComple ted 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()
{
InitializeCompo nent();
}

private void button1_Click(o bject sender, EventArgs e)
{
BackgroundWorke r backgroundWorke r1 = new BackgroundWorke r();
backgroundWorke r1.WorkerReport sProgress = true;
backgroundWorke r1.DoWork += new
DoWorkEventHand ler(backgroundW orker1_DoWork);
backgroundWorke r1.ProgressChan ged += new
ProgressChanged EventHandler(ba ckgroundWorker1 _ProgressChange d);
backgroundWorke r1.RunWorkerCom pleted += new
RunWorkerComple tedEventHandler (backgroundWork er1_RunWorkerCo mpleted);
backgroundWorke r1.RunWorkerAsy nc();
}

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

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

void backgroundWorke r1_DoWork(objec t sender, DoWorkEventArgs e)
{
try
{
string directory = "directorypath" ;
DirectoryInfo dir = new DirectoryInfo(d irectory);

if (!dir.Exists)
{
throw new DirectoryNotFou ndException("Th e directory
does not exist.");
}

FileSystemInfo[] infos = dir.GetFileSyst emInfos();

BackgroundWorke r worker = sender as BackgroundWorke r;
ListDirectories AndFiles(worker , infos);
}
catch (Exception ex)
{
Console.WriteLi ne(ex.Message);
}
finally
{
}
}

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

private void ListDirectories AndFiles(Backgr oundWorker worker,
FileSystemInfo[] FSInfo)
{
if (FSInfo == null)
{
throw new ArgumentNullExc eption("FSInfo" );
}

foreach (FileSystemInfo i in FSInfo)
{
if (i is DirectoryInfo)
{
directories++;
DirectoryInfo dInfo = (DirectoryInfo) i;
ListDirectories AndFiles(worker ,
dInfo.GetFileSy stemInfos());
}
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.ReportPr ogress(0);
}
}
}
}

For more information on the BackgroundWorke r 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****@microsof t.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
5880
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 example first field asks the user if they drive, if the user selects "NO" the form doesn't change. If they select "YES", another field appears with different makes to chose from. If they change back to "NO" the second field dissapears again.
10
5826
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: WebForm1.aspx ChangeValue.aspx WebUserControl1.ascx Module1.vb
5
12535
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 update the datasource - awesome, but I have an issue with updating from a different thread. Here is my datasource, a person class that raises the PropertyChanged event: class Person : INotifyPropertyChanged {
0
1380
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 whenever my user enters a job number into a textbox and hits a button. There is a SQLDataSource object on the page that does the retrieval of the data, and the job number parameter for its query is bound to the textbox "Text" value. In the button...
5
5434
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 updated and no errors returned. Here is the source.. Please help. <asp:GridView ID="gvEvidence" runat="server" AllowPaging="True" AllowSorting="True"
0
1200
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> <asp:Parameter Name="ProductTypeID" Type="Int32" /> <asp:Parameter Name="OpportunityTypeID" Type="Int32" />
3
2150
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 that contain only c files in them in an order say starting with one directory follwed by its sub directories etc. Hope this is clear! Can somebody help me with the Perl script?? Thanks, sreemakam
4
8765
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 ‘Update’, the page returns to its original state (prior to clicking Edit) and no updates occur in the DB. What am I missing? I included the html code below. -- Thank-you, Barbara Alderton <body>
1
2018
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 bit field in a dataset, and when the items are first bound, all four are correctly databound. For example, if the stored procedure returns 1 for the value of the field, the value of the hidden field is True, the text that appears in the textbox...
0
9708
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10589
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10085
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
7625
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 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 a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6857
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5527
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5663
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4302
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
2999
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.