Sorry for my Bad English
I am trying to Design a Win Form in C# which will get some Data from a database while It's loading
I want to use a progress bar to show reading data progress
I tried this code (and also many others)
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
this.Show();
progressBar1.Value = 10;
int n;
n = 50;//number of records in DB ,
double progress = 0;
double progstep = 25 / n;
for (int i = 1; i <= n; i++)
{
//getting
if (progress <= 100)
progressBar1.Value = (int)progress;
}
progressBar1.Value = 35;
n = 100;//number of records in DB for another data reading from DB ,
progress = 35;
progstep = 65 / n;
for (int i = 1; i <= n; i++)
{
//getting data from DB
dataGridView1.Rows.Add(....);//Adding that data to a datagrid -- parametrs removed.
progress += progress;
if (progress <= 100)
progressBar1.Value = (int)progress;
}
}
But , Problem is , Form will wait , until data reading progress be completed and I can see just a full progress bar and all data loaded.
What Should I do too fix this?
Thanks
Since this is winforms, i'd recommend using a BackgroundWorker.
Basic example:
Which would then kickoff:
Then the Progress changed event would fire to update the UI safely:
This is simple mockup to show you how to work with backround worker:
First in your
OnLoad
create background worker and attach 2 events to it:Add a
backgroundWorker1
to your form.Then add a
YourForm_Shown
eventAdd on form's contructor after
InitializeComponent()
And last add the voids of
backgroundWorker1
and
Take a look at BackgroundWorker control. During form load invoke
and override event DoWork to do the dirty work (load data from db) and ProgressChanged to update progress bar. In the event body (lets say the event signature will be something like this):