winforms - Producing a progress bar while loading in C# -
i have below code shows message text box while loading:
private void button3_click_1(object sender, eventargs e) { int i; backgroundworker bw = new backgroundworker(); bw.workerreportsprogress = true; bw.workersupportscancellation = true; bw.dowork += new doworkeventhandler(bw_dowork); bw.progresschanged += new progresschangedeventhandler(bw_progresschanged); bw.runworkercompleted += new runworkercompletedeventhandler(bw_runworkercompleted); msgform = new form2(); //form2 showing message "please wait..." try { bw.runworkerasync(combobox15.text); msgform.startposition = formstartposition.centerparent; msgform.showdialog(); } catch (exception ex) { messagebox.show(ex.message); } } void bw_dowork(object sender, doworkeventargs e) { string prtadd = e.argument.tostring(); loading(prtadd); //this function of loading. } void bw_runworkercompleted(object sender, runworkercompletedeventargs e) { msgform.close(); }
my loading takes 2-3 minutes. so, if show static message box, user think maybe program hang somewhere.
i improve adding progress bar while loading. can guys me?
something this, perhaps?
public partial class form1 : form { private form2 _frm2; public form1() { initializecomponent(); } private void button1_click(object sender, eventargs e) { var bw = new backgroundworker(); bw.workerreportsprogress = true; bw.workersupportscancellation = true; bw.dowork += bwondowork; bw.runworkercompleted += bwonrunworkercompleted; bw.runworkerasync(); _frm2 = new form2(bw); _frm2.startposition = formstartposition.centerparent; _frm2.showdialog(); } private void bwonrunworkercompleted(object sender, runworkercompletedeventargs runworkercompletedeventargs) { if (_frm2 != null) { _frm2.close(); } } private void bwondowork(object sender, doworkeventargs doworkeventargs) { var bw = sender backgroundworker; var = 0; while (i < 100 && !bw.cancellationpending) { bw.reportprogress(i); thread.sleep(100); i++; } } } public partial class form2 : form { private backgroundworker _bw; public form2() { initializecomponent(); } public form2(backgroundworker bw) : this() { _bw = bw; _bw.progresschanged += bwonprogresschanged; } private void bwonprogresschanged(object sender, progresschangedeventargs progresschangedeventargs) { progressbar1.value = progresschangedeventargs.progresspercentage; } private void button1_click(object sender, eventargs e) { _bw.cancelasync(); } }
Comments
Post a Comment