Invoke create handle from a backgroundworker - c#

i'm working to populate a listview with a loop in a backgroundworker and the background worker was run initially from a 2nd active form. To picture it i've open a form1 then open another form (form2) that was use to run a form1.backgroundworker runasync.
Form1 with the backgroundworker - at the back
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
BackgroundWorker wk = new BackgroundWorker { WorkerReportsProgress = true };
listView1.View = View.Details;
DataTable dtdt = new DataTable();
dtdt = qr.history();
for (int i = 0; i < dtdt.Rows.Count; i++)
{
DataRow dr = dtdt.Rows[i];
ListViewItem listitem = new ListViewItem(dr["custnum"].ToString());
listitem.SubItems.Add(dr["custname"].ToString().Trim());
listitem.SubItems.Add(dr["ratecable"].ToString().Trim());
listitem.SubItems.Add(dr["rateinternet"].ToString().Trim());
listitem.SubItems.Add(dr["rateext"].ToString().Trim());
listitem.SubItems.Add(dr["status"].ToString().Trim());
listitem.SubItems.Add(dr["classname"].ToString().Trim());
listitem.SubItems.Add(dr["SVCstadd"].ToString().Trim());
listitem.SubItems.Add(dr["SVCctadd"].ToString().Trim());
listitem.SubItems.Add(dr["svctelno"].ToString().Trim());
listitem.SubItems.Add(dr["bilstadd"].ToString().Trim());
listitem.SubItems.Add(dr["bilctadd"].ToString().Trim());
listitem.SubItems.Add(dr["billtel"].ToString().Trim());
listitem.SubItems.Add(dr["billtel2"].ToString().Trim());
listitem.SubItems.Add(dr["fax"].ToString().Trim());
listitem.SubItems.Add(dr["zoneno"].ToString().Trim());
listitem.SubItems.Add(dr["zoneName"].ToString().Trim());
listitem.SubItems.Add(dr["bookno"].ToString().Trim());
listitem.SubItems.Add(dr["seqno"].ToString().Trim());
listitem.SubItems.Add(dr["Balance"].ToString().Trim());
listitem.SubItems.Add(dr["balance1"].ToString().Trim());
listitem.SubItems.Add(dr["balance2"].ToString().Trim());
listitem.SubItems.Add(dr["balance3"].ToString().Trim());
listitem.SubItems.Add(dr["billamnt"].ToString().Trim());
listitem.SubItems.Add(dr["maxdate"].ToString().Trim());
qr.lsi = listitem;
//error {"Invoke or BeginInvoke cannot be called on a control until the window handle has been created."}
this.BeginInvoke(new MethodInvoker(delegate { additemtoLV(listitem); }));
}
System.Threading.Thread.Sleep(100);
}
private delegate void additemtoLVdelegat(ListViewItem ls);
public void additemtoLV(ListViewItem ls)
{
if (IsHandleCreated)
{
BeginInvoke(new additemtoLVdelegat(additemtoLV), ls);
}
else
{
listView1.Items.Add(ls);
}
}
Form2 -use to call form1.backgroundworker - in front of form1 - note form1 is already open
private void Close_Click(object sender, EventArgs e)
{
form1 f1 = new form1 ();
f1.backgroundWorker1.RunWorkerAsync();
this.Close();
}

According to your code, form1 is not opened. You have to call Form.Show and wait for Form.Load.
form1 f1 = new form1 ();
f1.backgroundWorker1.RunWorkerAsync();
I suggest that you start background worker in Form1_Load
private void Form1_Load(object sender, EventArgs e)
{
backgroundWorker1.RunWorkerAsync();
}
And show Form1 to allow Form1_Load be fired.
private void Close_Click(object sender, EventArgs e)
{
form1 f1 = new form1();
f1.Show();
}

Related

How can I refresh One form when the other form is closed?

I have been developing project in c#.
It has 2 form and these are connected with between each other.
I want to do that when second form is closed, first form refresh.
If I use Thread's Sleep program will be tired. I want to do this with closing events. How can I do ?(Like java's repaint)
Codes are below:
Form1
public static Form1 form;
public Form1()
{
InitializeComponent();
form = this;
}
private void button11_Click(object sender, EventArgs e)
{
Form2 yeniform = new Form2();
yeniform.Show();
}
Form2(Close Button)
private void button1_Click(object sender, EventArgs e)
{
Form1.form.Invalidate();
Form1.form.Refresh();
this.Close();
}
Bind Form_Closing event in your first form.
//Form1
private void button11_Click(object sender, EventArgs e)
{
Form2 yeniform = new Form2();
yeniform.FormClosing += new FormClosingEventHandler(this.Form2_FormClosing);
yeniform.Show();
}
private void Form2_FormClosing(object sender, FormClosingEventArgs e)
{
//Do your stuff here.
}
' button in the second form which is to be closed
' form1 is the form which is to be re loaded when form 2 is closed
private void btn_close_Click(object sender, EventArgs e)
form1.close() 'unload form 1 before closing form2
form1.show() ' form 1 reloading
unload(me) 'closing form2
end sub
This is a working sample. In parent form
private void barButtonItem1_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
{
VendorsAddForm f = new VendorsAddForm();
f.StartPosition = FormStartPosition.CenterScreen;
f.FormClosed += new FormClosedEventHandler(child_FormClosed);
f.Show();
}
void child_FormClosed(object sender, FormClosedEventArgs e)
{
this.Refresh();
var query = dbContext.AccountObjects.Where(p => p.IsVendor == true).ToList();
accountObjectsBindingSource.DataSource = new BindingList<AccountObject>(query);
}
Note: child form is VendorsAddForm
Thank to https://www.daniweb.com/posts/jump/1302760 , I learned from there.

BackgroundWorker hide form window upon completion

I'm having some trouble with hiding a form when a BackgroundWorker process is completed.
private void submitButton_Click(object sender, EventArgs e)
{
processing f2 = new processing();
f2.MdiParent = this.ParentForm;
f2.StartPosition = FormStartPosition.CenterScreen;
f2.Show();
this.Hide();
backgroundWorker1.RunWorkerAsync();
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
// loop through and upload our sound bits
string[] files = System.IO.Directory.GetFiles(System.Environment.GetFolderPath(System.Environment.SpecialFolder.MyDocuments) + "\\wav", "*.wav", System.IO.SearchOption.AllDirectories);
foreach (string soundBit in files)
{
System.Net.WebClient Client = new System.Net.WebClient();
Client.Headers.Add("Content-Type", "audio/mpeg");
byte[] result = Client.UploadFile("http://mywebsite.com/upload.php", "POST", soundBit);
}
}
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
formSubmitted f3 = new formSubmitted();
f3.MdiParent = this.ParentForm;
f3.StartPosition = FormStartPosition.CenterScreen;
f3.Show();
this.Hide();
}
Basically, after the 'submit' button is pressed, the application begins to upload the files to the webserver via a php script. Once the upload is complete, the RunWorkerCompleted method is triggered, opening the formSubmitted form. The issue I'm having is that the processing form does not close once the backgroundworker is complete and the formSubmitted opens directly on top of the processing form - as opposed to what I want, having the processing form close and then open the formSubmitted form.
Well actually you are never closing processing form:
try following:
private processing _processingForm;
private void submitButton_Click(object sender, EventArgs e)
{
_processingForm = new processing();
_processingForm.MdiParent = this.ParentForm;
_processingForm.StartPosition = FormStartPosition.CenterScreen;
_processingForm.Show();
this.Hide(); //HIDES THE CURRENT FORM CONTAINING SUBMIT BUTTON
backgroundWorker1.RunWorkerAsync();
}
Now on completion hide processing form:
private void backgroundWorker1_RunWorkerCompleted(object sender,
RunWorkerCompletedEventArgs e)
{
formSubmitted f3 = new formSubmitted();
f3.MdiParent = this.ParentForm;
f3.StartPosition = FormStartPosition.CenterScreen;
_processingForm.Close();//CLOSE processing FORM
f3.Show();
this.Hide();//this REFERS TO THE FORM CONTAINING WORKER OBJECT
}

Automatically hide one form in C# after many second and show another form

I need to hide current form after many second and then show any form
I'm writing this code but it doesn't work.
namespace tempprj
{
public partial class ProfileFrm : Telerik.WinControls.UI.RadForm
{
public ProfileFrm()
{
InitializeComponent();
}
private void ProfileFrm_Load(object sender, EventArgs e)
{
Frm2 child = new Frm2();
Thread.Sleep(3000);
this.Hide();
child.ShowDialog();
}
}
}
Thread.Sleep(3000);
is going to prevent your project from doing anything at all for 3 seconds (not counting other threads) and freeze the UI. I suggest using the standard .NET timer.
http://msdn.microsoft.com/en-us/library/system.windows.forms.timer.aspx
This is a solution to my question:
private void ProfileFrm_Load(object sender, EventArgs e)
{
timer1.Tick += new EventHandler(timer1_Tick);
timer1.Enabled = true;
timer1.Interval = 4000;
timer1.Start();
}
private void timer1_Tick(object sender, EventArgs e)
{
timer1.Stop();
this.Hide();
Frm2 f = new Frm2();
f.ShowDialog();
}

progressbar and Data loading

i have Windows Form in C# having Datagridview with large no. of records from database and some comboboxes,textbox and buttons.
so,i used another form having progressbar and backgroundworker so that data loading of mainform does not iritate enduser.
public partial class FirstForm : Form
{
MainForm mf;
public FirstForm()
{
InitializeComponent();
backgroundWorker1.RunWorkerAsync();
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
mf = new MainForm(); //inside constructor,code of data loading in gridview
mf.Update();
}
private void timer1_Tick(object sender, EventArgs e)
{
if (p1.Value < p1.Maximum) //p1 name for progressbar
p1.Value++;
else
{
timer1.Enabled = false;
this.Hide();
mf.Show();
}
}
}
but when main form is displayed,it is blank and after 2/3 seconds datagridview and other controls appear.
how to solve this..?
or suggest other ideas to solve this problem.
Remove your code in Firstform and write mine in
programs.cs
static void Main()
{
Application.EnableVisualStyles();
Application.CurrentCulture = System.Globalization.CultureInfo.InvariantCulture;
Application.SetCompatibleTextRenderingDefault(false);
System.ComponentModel.BackgroundWorker bw = new System.ComponentModel.BackgroundWorker();
bw.DoWork += new System.ComponentModel.DoWorkEventHandler(bw_DoWork);
bw.WorkerSupportsCancellation = true;
MainForm = new MainForm(); // creating main form
bw.RunWorkerAsync();
frm.Inittiate(); // Add this method to first form to loading and initiating
bw.CancelAsync(); // ending splashing
Application.Run(frm);
}
static void bw_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
{
AFirstForm splashForm = new FirstForm();
splashForm.TopMost = true;
splashForm.Show();
while (!(sender as System.ComponentModel.BackgroundWorker).CancellationPending)
{
splashForm.Refresh();
}
splashForm.Close();
e.Result = splashForm;
}

How to stop System.Timers.Timer

I'm using Windows Forms to start a System.Timers.Timer to fire an event every 3 seconds. When I close the form the process keeps firing, and that's fine. The problem happens when I reopen the form to stop the timer on click of a button btnSendOff_Click.
System.Timers.Timer sendTimer = new System.Timers.Timer();
sendTimer.Elapsed += new ElapsedEventHandler(sendProcessTimerEvent);
sendTimer.Interval = 3000;
private void sendProcessTimerEvent(object sender, EventArgs e)
{
MessageBox.Show("Send 3 sec");
}
private void btnSendOn_Click(object sender, EventArgs e)
{
sendTimer.Start();
}
private void btnSendOff_Click(object sender, EventArgs e)
{
sendTimer.Stop();
}
There will be more asynchronous timers on this form. How can I stop this timer when I reopen the form?
The form should not be creating a new timer every time you create a new instance of the form if it needs to keep running after the form closes. The way you have declared the timer, it will create another one each time the form is created. You should put the timer on a different form or declare it in some global module and only make the form activate or deactivate the timer. If the timer needs to keep running when the form is closed, the form should not be the one owning or creating the timer. If the timer doesn't need to keep running when the form is closed, then you should be using a Forms.Timer instead of a System.Timer.
Edit: Add Sample Code
static class Program
{
public static System.Timers.Timer sendTimer;
public static System.Text.StringBuilder accumulatedText;
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
sendTimer = new System.Timers.Timer();
accumulatedText = new System.Text.StringBuilder("Started at " + DateTime.Now.ToLongTimeString() + Environment.NewLine);
sendTimer.Interval = 3000;
sendTimer.Elapsed += new System.Timers.ElapsedEventHandler(sendProcessTimerEvent);
Application.Run(new MainForm());
}
static void sendProcessTimerEvent(object sender, System.Timers.ElapsedEventArgs e)
{
accumulatedText.AppendLine("Pinged at " + DateTime.Now.ToLongTimeString());
}
}
class MainForm : Form
{
ToolStrip mainToolStrip = new ToolStrip();
public MainForm()
{
mainToolStrip.Items.Add("Log Control").Click += new EventHandler(MainForm_Click);
Controls.Add(mainToolStrip);
}
void MainForm_Click(object sender, EventArgs e)
{
Form1 frm = new Form1();
frm.ShowDialog();
}
}
class Form1 : Form
{
private Button button1 = new Button();
private TextBox text1 = new TextBox();
public Form1()
{
button1.Dock = DockStyle.Bottom;
button1.Text = Program.sendTimer.Enabled ? "Stop": "Start";
button1.Click += new EventHandler(button1_Click);
text1 = new TextBox();
text1.Dock = DockStyle.Fill;
text1.Multiline= true;
text1.ScrollBars = ScrollBars.Vertical;
text1.Text = Program.accumulatedText.ToString();
Controls.AddRange(new Control[] {button1, text1});
}
void button1_Click(object sender, EventArgs e)
{
Program.sendTimer.Enabled = !Program.sendTimer.Enabled;
button1.Text = Program.sendTimer.Enabled ? "Stop" : "Start";
}
}

Categories

Resources