Load data by Thread - c#

C#:
I want to load big data from Database and in loading progress i want display available to DatagridView. I use IDataReader and BackgroundWorker. But in hard try some way, i get error.
I want when Execute Script to server, the data receive will have Schema information, and it will dynamic to create structure of DatagridView and base from that structure the available data will add to grid row by row and User can see this changed.
My code is below, but error. Any answer to help my I deal, i thanks very much!
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace WindowsFormsApplication1
{
partial class Form1
{
string conectionString = "";
IDbConnection connection;
BackgroundWorker worker;
BindingSource binding;
IDbCommand GetExecuteCommand()
{
string commandText = "select * from dbo.B20DmBp";
SqlCommand command = new SqlCommand();
command.Connection = (SqlConnection)this.connection;
command.CommandText = commandText;
command.CommandType = CommandType.Text;
return command;
}
public Form1()
{
InitializeComponent();
Initialize();
RegisterHandler();
}
void Initialize()
{
worker = new BackgroundWorker();
worker.WorkerSupportsCancellation = true;
worker.WorkerReportsProgress = true;
binding = new BindingSource();
this.dataGridView1.DataSource = binding;
connection = new SqlConnection(conectionString);
}
void RegisterHandler()
{
worker.DoWork += new DoWorkEventHandler(worker_DoWork);
worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(worker_RunWorkerCompleted);
worker.ProgressChanged += new ProgressChangedEventHandler(worker_ProgressChanged);
}
void worker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
DataTable table = this.binding.DataSource as DataTable;
IDataReader reader = e.UserState as IDataReader;
table.Rows.Add(this.BuildDataRow(reader));
this.binding.ResetBindings(false);
}
void worker_DoWork(object sender, DoWorkEventArgs e)
{
IDbCommand command = e.Argument as IDbCommand;
BackgroundWorker worker2 = sender as BackgroundWorker;
try
{
command.Connection.Open();
IDataReader reader = command.ExecuteReader();
while (reader.Read())
{
if (worker.CancellationPending)
{
e.Cancel = true;
}
else
{
worker.ReportProgress(0, reader);
}
}
reader.Close();
command.Connection.Close();
}
catch (Exception)
{
throw;
}
finally
{
command.Connection.Close();
}
}
void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
throw new NotImplementedException();
}
void StartExecute()
{
this.binding.DataSource = new DataTable();
this.worker.RunWorkerAsync(this.GetExecuteCommand());
}
void CancelExecute()
{
if (this.worker.WorkerSupportsCancellation)
{
this.worker.CancelAsync();
}
}
DataRow BuildDataRow(IDataReader reader)
{
DataTable table = this.binding.DataSource as DataTable;
if (table.Columns.Count == 0)
{
foreach (DataRow row in reader.GetSchemaTable().Rows)
{
string columnName = row["ColumnName"].ToString();
table.Columns.Add(columnName);
}
this.binding.ResetBindings(true);
}
DataRow row2 = table.NewRow();
foreach (DataRow row in reader.GetSchemaTable().Rows)
{
string columnName = row["ColumnName"].ToString();
row2[columnName] = reader[columnName];
}
return row2;
}
private void button1_Click(object sender, EventArgs e)
{
this.StartExecute();
}
private void button2_Click(object sender, EventArgs e)
{
this.CancelExecute();
}
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.dataGridView1 = new System.Windows.Forms.DataGridView();
this.button1 = new System.Windows.Forms.Button();
this.button2 = new System.Windows.Forms.Button();
((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).BeginInit();
this.SuspendLayout();
//
// dataGridView1
//
this.dataGridView1.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
this.dataGridView1.Location = new System.Drawing.Point(35, 26);
this.dataGridView1.Name = "dataGridView1";
this.dataGridView1.Size = new System.Drawing.Size(240, 150);
this.dataGridView1.TabIndex = 0;
//
// button1
//
this.button1.Location = new System.Drawing.Point(35, 194);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(75, 23);
this.button1.TabIndex = 1;
this.button1.Text = "button1";
this.button1.UseVisualStyleBackColor = true;
this.button1.Click += new System.EventHandler(this.button1_Click);
//
// button2
//
this.button2.Location = new System.Drawing.Point(127, 194);
this.button2.Name = "button2";
this.button2.Size = new System.Drawing.Size(75, 23);
this.button2.TabIndex = 2;
this.button2.Text = "button2";
this.button2.UseVisualStyleBackColor = true;
this.button2.Click += new System.EventHandler(this.button2_Click);
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(323, 262);
this.Controls.Add(this.button2);
this.Controls.Add(this.button1);
this.Controls.Add(this.dataGridView1);
this.Name = "Form1";
this.Text = "Form1";
((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).EndInit();
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.DataGridView dataGridView1;
private System.Windows.Forms.Button button1;
private System.Windows.Forms.Button button2;
}
}

Are cross thread access error occurs?
if yes, you can resolve as in topic: http://msdn.microsoft.com/en-us/library/ms171728%28VS.80%29.aspx

Related

CheckedChanged not triggering

I am trying to create a winform application. Accidentally I found that Radiobutton.Checked event is fired when we programmatically assign true to RadioButton.Checked. But it is not fired when we programmatically assign false to Radiobutton.Checked. But it fires, when we manually checked/unchecked it. Here is a sample Code. Copy it,compile it and run it to check
using System.Windows.Forms;
using System;
using System.ComponentModel;
using System.Windows;
namespace Temp
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
//radioButton1.Checked = true;
//radioButton2.Checked = true;
radioButton1.Checked = false;
radioButton2.Checked = false;
}
private void radioButton1_CheckedChanged(object sender, EventArgs e)
{
System.Windows.Forms.RadioButton tempRB = (System.Windows.Forms.RadioButton)sender;
MessageBox.Show(tempRB.Name + " : " + (tempRB.Checked ? "Checked" : "Unchecked"));
//radioButton2.Checked = !radioButton1.Checked;
}
}
partial class Form1
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.button1 = new System.Windows.Forms.Button();
this.groupBox1 = new System.Windows.Forms.GroupBox();
this.radioButton1 = new System.Windows.Forms.RadioButton();
this.radioButton2 = new System.Windows.Forms.RadioButton();
this.groupBox1.SuspendLayout();
this.SuspendLayout();
//
// button1
//
this.button1.Location = new System.Drawing.Point(173, 84);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(75, 23);
this.button1.TabIndex = 1;
this.button1.Text = "button1";
this.button1.UseVisualStyleBackColor = true;
this.button1.Click += new System.EventHandler(this.button1_Click);
//
// groupBox1
//
this.groupBox1.Controls.Add(this.radioButton2);
this.groupBox1.Controls.Add(this.radioButton1);
this.groupBox1.Location = new System.Drawing.Point(385, 56);
this.groupBox1.Name = "groupBox1";
this.groupBox1.Size = new System.Drawing.Size(200, 100);
this.groupBox1.TabIndex = 2;
this.groupBox1.TabStop = false;
this.groupBox1.Text = "groupBox1";
//
// radioButton1
//
this.radioButton1.AutoSize = true;
this.radioButton1.Location = new System.Drawing.Point(21, 28);
this.radioButton1.Name = "radioButton1";
this.radioButton1.Size = new System.Drawing.Size(85, 17);
this.radioButton1.TabIndex = 0;
this.radioButton1.Text = "radioButton1";
this.radioButton1.UseVisualStyleBackColor = true;
this.radioButton1.CheckedChanged += new System.EventHandler(this.radioButton1_CheckedChanged);
//
// radioButton2
//
this.radioButton2.AutoSize = true;
this.radioButton2.Location = new System.Drawing.Point(21, 52);
this.radioButton2.Name = "radioButton2";
this.radioButton2.Size = new System.Drawing.Size(85, 17);
this.radioButton2.TabIndex = 1;
this.radioButton2.Text = "radioButton2";
this.radioButton2.UseVisualStyleBackColor = true;
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(663, 261);
this.Controls.Add(this.groupBox1);
this.Controls.Add(this.button1);
this.Name = "Form1";
this.Text = "Form1";
this.groupBox1.ResumeLayout(false);
this.groupBox1.PerformLayout();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.Button button1;
private System.Windows.Forms.GroupBox groupBox1;
private System.Windows.Forms.RadioButton radioButton2;
private System.Windows.Forms.RadioButton radioButton1;
}
static class Temp
{
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
}
Can anybody give an explanation about this. And also help me on how to fire RadioButton.Checked event when it got assigned false programmatically.
Note: I am using .net 3.5,Windows 10.
EDIT:
I am adding slightly modified code. In this "Uncheck" button didn't trigger anything. But "Check Both" triggers two times CheckedChanged event. Check this code
using System.Windows.Forms;
using System;
using System.ComponentModel;
using System.Windows;
namespace Temp
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
radioButton1.Checked = false;
radioButton2.Checked = false;
}
private void button2_Click(object sender, EventArgs e)
{
radioButton1.Checked = true;
radioButton2.Checked = true;
}
private void radioButton1_CheckedChanged(object sender, EventArgs e)
{
System.Windows.Forms.RadioButton tempRB = (System.Windows.Forms.RadioButton)sender;
MessageBox.Show(tempRB.Name + " : " + (tempRB.Checked ? "Checked" : "Unchecked"));
//radioButton2.Checked = !radioButton1.Checked;
}
}
partial class Form1
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.button1 = new System.Windows.Forms.Button();
this.groupBox1 = new System.Windows.Forms.GroupBox();
this.radioButton1 = new System.Windows.Forms.RadioButton();
this.radioButton2 = new System.Windows.Forms.RadioButton();
this.button2 = new System.Windows.Forms.Button();
this.groupBox1.SuspendLayout();
this.SuspendLayout();
//
// button1
//
this.button1.Location = new System.Drawing.Point(173, 84);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(75, 23);
this.button1.TabIndex = 1;
this.button1.Text = "UnCheck";
this.button1.UseVisualStyleBackColor = true;
this.button1.Click += new System.EventHandler(this.button1_Click);
//
// button2
//
this.button2.Location = new System.Drawing.Point(173, 132);
this.button2.Name = "button2";
this.button2.Size = new System.Drawing.Size(75, 23);
this.button2.TabIndex = 3;
this.button2.Text = "Check Both";
this.button2.UseVisualStyleBackColor = true;
this.button2.Click += new System.EventHandler(this.button2_Click);
//
// groupBox1
//
this.groupBox1.Controls.Add(this.radioButton2);
this.groupBox1.Controls.Add(this.radioButton1);
this.groupBox1.Location = new System.Drawing.Point(385, 56);
this.groupBox1.Name = "groupBox1";
this.groupBox1.Size = new System.Drawing.Size(200, 100);
this.groupBox1.TabIndex = 2;
this.groupBox1.TabStop = false;
this.groupBox1.Text = "groupBox1";
//
// radioButton1
//
this.radioButton1.AutoSize = true;
this.radioButton1.Location = new System.Drawing.Point(21, 28);
this.radioButton1.Name = "radioButton1";
this.radioButton1.Size = new System.Drawing.Size(85, 17);
this.radioButton1.TabIndex = 0;
this.radioButton1.Text = "radioButton1";
this.radioButton1.UseVisualStyleBackColor = true;
this.radioButton1.CheckedChanged += new System.EventHandler(this.radioButton1_CheckedChanged);
//
// radioButton2
//
this.radioButton2.AutoSize = true;
this.radioButton2.Location = new System.Drawing.Point(21, 52);
this.radioButton2.Name = "radioButton2";
this.radioButton2.Size = new System.Drawing.Size(85, 17);
this.radioButton2.TabIndex = 1;
this.radioButton2.Text = "radioButton2";
this.radioButton2.UseVisualStyleBackColor = true;
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(663, 261);
this.Controls.Add(this.groupBox1);
this.Controls.Add(this.button1);
this.Controls.Add(this.button2);
this.Name = "Form1";
this.Text = "Form1";
this.groupBox1.ResumeLayout(false);
this.groupBox1.PerformLayout();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.Button button2;
private System.Windows.Forms.Button button1;
private System.Windows.Forms.GroupBox groupBox1;
private System.Windows.Forms.RadioButton radioButton2;
private System.Windows.Forms.RadioButton radioButton1;
}
static class Temp
{
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
}

How to remove and stop a thread based on its entry in a Listview/List?

I have some code that starts a new thread every time a button is clicked. Each new thread draws a randomly colored circle in a random location in a primitive graphics engine and is added to a Listview. The link to this engine is https://github.com/NAIT-CNT/GDIDrawer.
I need to find a way to remove and abort a thread based on whatever Listview item the user clicks.
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using GDIDrawer;
using System.Threading;
namespace ica7
{
public partial class Form1 : Form
{
CDrawer _gdi = new CDrawer();
List<Thread> _threads = new List<Thread>();
Random _rng = new Random();
Point _coords;
int _diameter;
bool _isRunning;
public Form1()
{
InitializeComponent();
_diameter = 10;
_isRunning = true;
btnStopThreads.Enabled = false;
}
private Color RandomColor()
{
return Color.FromArgb(_rng.Next(256), _rng.Next(256), _rng.Next(256));
}
private void DrawCircle(int diameter, Point coords, CDrawer gdi)
{
gdi.AddCenteredEllipse(coords, diameter, diameter, RandomColor());
}
private void btnStartThread_Click(object sender, EventArgs e)
{
btnStopThreads.Enabled = true;
Thread t = new Thread(() =>
{
int diameter = _diameter;
while (_isRunning)
{
_coords.X = _rng.Next(800);
_coords.Y = _rng.Next(600);
DrawCircle(diameter, _coords, _gdi);
Thread.Sleep(10);
}
});
_threads.Add(t);
ListViewItem lvi = new ListViewItem(t.ToString());
lboxThreads.Items.Add(lvi);
t.Start();
}
private void btnStopThreads_Click(object sender, EventArgs e)
{
_threads.ElementAt(lboxThreads.SelectedIndex).Abort();
lboxThreads.Items.RemoveAt(lboxThreads.SelectedIndex);
}
private void trackBar1_Scroll(object sender, EventArgs e)
{
_diameter = trackBar1.Value;
}
private void Form1_FormClosed(object sender, FormClosedEventArgs e)
{
_threads.ForEach(x => x.Abort());
}
}
}
Here is the designer file, in case it's needed:
namespace ica7
{
partial class Form1
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
this.btnStartThread = new System.Windows.Forms.Button();
this.btnStopThreads = new System.Windows.Forms.Button();
this.lboxThreads = new System.Windows.Forms.ListBox();
this.trackBar1 = new System.Windows.Forms.TrackBar();
this.lblTbMin = new System.Windows.Forms.Label();
this.lblTbMax = new System.Windows.Forms.Label();
this.timer1 = new System.Windows.Forms.Timer(this.components);
((System.ComponentModel.ISupportInitialize)(this.trackBar1)).BeginInit();
this.SuspendLayout();
//
// btnStartThread
//
this.btnStartThread.ForeColor = System.Drawing.SystemColors.ActiveCaptionText;
this.btnStartThread.Location = new System.Drawing.Point(9, 11);
this.btnStartThread.Name = "btnStartThread";
this.btnStartThread.Size = new System.Drawing.Size(121, 23);
this.btnStartThread.TabIndex = 0;
this.btnStartThread.Text = "Start a Thread";
this.btnStartThread.UseVisualStyleBackColor = true;
this.btnStartThread.Click += new System.EventHandler(this.btnStartThread_Click);
//
// btnStopThreads
//
this.btnStopThreads.ForeColor = System.Drawing.SystemColors.ActiveCaptionText;
this.btnStopThreads.Location = new System.Drawing.Point(9, 40);
this.btnStopThreads.Name = "btnStopThreads";
this.btnStopThreads.Size = new System.Drawing.Size(121, 23);
this.btnStopThreads.TabIndex = 1;
this.btnStopThreads.Text = "Stop Selected Thread";
this.btnStopThreads.UseVisualStyleBackColor = true;
this.btnStopThreads.Click += new System.EventHandler(this.btnStopThreads_Click);
//
// lboxThreads
//
this.lboxThreads.FormattingEnabled = true;
this.lboxThreads.Location = new System.Drawing.Point(138, 11);
this.lboxThreads.Name = "lboxThreads";
this.lboxThreads.Size = new System.Drawing.Size(303, 134);
this.lboxThreads.TabIndex = 2;
//
// trackBar1
//
this.trackBar1.Location = new System.Drawing.Point(9, 69);
this.trackBar1.Maximum = 50;
this.trackBar1.Minimum = 10;
this.trackBar1.Name = "trackBar1";
this.trackBar1.Size = new System.Drawing.Size(121, 45);
this.trackBar1.TabIndex = 3;
this.trackBar1.Value = 10;
this.trackBar1.Scroll += new System.EventHandler(this.trackBar1_Scroll);
//
// lblTbMin
//
this.lblTbMin.AutoSize = true;
this.lblTbMin.Location = new System.Drawing.Point(6, 101);
this.lblTbMin.Name = "lblTbMin";
this.lblTbMin.Size = new System.Drawing.Size(19, 13);
this.lblTbMin.TabIndex = 4;
this.lblTbMin.Text = "10";
//
// lblTbMax
//
this.lblTbMax.AutoSize = true;
this.lblTbMax.Location = new System.Drawing.Point(111, 101);
this.lblTbMax.Name = "lblTbMax";
this.lblTbMax.Size = new System.Drawing.Size(19, 13);
this.lblTbMax.TabIndex = 5;
this.lblTbMax.Text = "50";
//
// timer1
//
this.timer1.Tick += new System.EventHandler(this.timer1_Tick);
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.BackColor = System.Drawing.SystemColors.ActiveCaptionText;
this.ClientSize = new System.Drawing.Size(453, 157);
this.Controls.Add(this.lblTbMax);
this.Controls.Add(this.lblTbMin);
this.Controls.Add(this.trackBar1);
this.Controls.Add(this.lboxThreads);
this.Controls.Add(this.btnStopThreads);
this.Controls.Add(this.btnStartThread);
this.ForeColor = System.Drawing.SystemColors.ActiveCaption;
this.Name = "Form1";
this.Text = "Form1";
this.FormClosed += new System.Windows.Forms.FormClosedEventHandler(this.Form1_FormClosed);
((System.ComponentModel.ISupportInitialize)(this.trackBar1)).EndInit();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.Button btnStartThread;
private System.Windows.Forms.Button btnStopThreads;
private System.Windows.Forms.ListBox lboxThreads;
private System.Windows.Forms.TrackBar trackBar1;
private System.Windows.Forms.Label lblTbMin;
private System.Windows.Forms.Label lblTbMax;
private System.Windows.Forms.Timer timer1;
}
}
If there are superior ways of doing any of this, please let me know. This is my first foray into threads. This is homework.

Nlog write log to RichTextBox error

I'm using Nlog in my project, and now there's a problem, here it is:
I want to write logs into a RichTextBox, everything is OK at first, but when I clear the lines in RTB, and then restart to write logs, it goes wrong, it will not show any line in the RTB.
But, if I use
log.Error("Error\n"); // there is a "\n" in the end
instead of
log.Error("Error");
it will be OK, I don't know why is that...
any clue of this? thanks very much for any suggestion.
BTW I'm using Win7 X64, VS 2013, C# WinForm, .NET 4.0, NLog 3.2.0
using System;
using System.Windows.Forms;
using NLog;
using NLog.Targets;
namespace RTBLogDemo
{
public partial class LogForm : Form
{
#region Designer
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
this.logRichTextBox = new System.Windows.Forms.RichTextBox();
this.btnStart = new System.Windows.Forms.Button();
this.btnStop = new System.Windows.Forms.Button();
this.btnClear = new System.Windows.Forms.Button();
this.logTimer = new System.Windows.Forms.Timer(this.components);
this.SuspendLayout();
//
// logRichTextBox
//
this.logRichTextBox.Dock = System.Windows.Forms.DockStyle.Bottom;
this.logRichTextBox.Location = new System.Drawing.Point(0, 173);
this.logRichTextBox.Name = "logRichTextBox";
this.logRichTextBox.Size = new System.Drawing.Size(656, 299);
this.logRichTextBox.TabIndex = 0;
this.logRichTextBox.Text = "";
//
// btnStart
//
this.btnStart.Location = new System.Drawing.Point(100, 48);
this.btnStart.Name = "btnStart";
this.btnStart.Size = new System.Drawing.Size(75, 39);
this.btnStart.TabIndex = 1;
this.btnStart.Text = "start";
this.btnStart.UseVisualStyleBackColor = true;
this.btnStart.Click += new System.EventHandler(this.btnStart_Click);
//
// btnStop
//
this.btnStop.Location = new System.Drawing.Point(261, 48);
this.btnStop.Name = "btnStop";
this.btnStop.Size = new System.Drawing.Size(75, 39);
this.btnStop.TabIndex = 2;
this.btnStop.Text = "stop";
this.btnStop.UseVisualStyleBackColor = true;
this.btnStop.Click += new System.EventHandler(this.btnStop_Click);
//
// btnClear
//
this.btnClear.Location = new System.Drawing.Point(417, 48);
this.btnClear.Name = "btnClear";
this.btnClear.Size = new System.Drawing.Size(75, 39);
this.btnClear.TabIndex = 3;
this.btnClear.Text = "Clear";
this.btnClear.UseVisualStyleBackColor = true;
this.btnClear.Click += new System.EventHandler(this.btnClear_Click);
//
// logTimer
//
this.logTimer.Tick += new System.EventHandler(this.logTimer_Tick);
//
// LogForm
//
this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 15F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(656, 472);
this.Controls.Add(this.btnClear);
this.Controls.Add(this.btnStop);
this.Controls.Add(this.btnStart);
this.Controls.Add(this.logRichTextBox);
this.Name = "LogForm";
this.Text = "Log Form";
this.Load += new System.EventHandler(this.LogForm_Load);
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.RichTextBox logRichTextBox;
private System.Windows.Forms.Button btnStart;
private System.Windows.Forms.Button btnStop;
private System.Windows.Forms.Button btnClear;
private System.Windows.Forms.Timer logTimer;
#endregion
public LogForm()
{
InitializeComponent();
}
private Logger log;
private void logTimer_Tick(object sender, EventArgs e)
{
log.Error("Error"); // WRONG
// log.Error("Error\n"); // OK
}
private void btnStart_Click(object sender, EventArgs e)
{
logTimer.Start();
}
private void btnStop_Click(object sender, EventArgs e)
{
logTimer.Stop();
}
private void btnClear_Click(object sender, EventArgs e)
{
logRichTextBox.Clear();
}
private void InitLogger()
{
RichTextBoxTarget target = new RichTextBoxTarget();
target.Layout = "${date:format=HH\\:MM\\:ss} ${logger} ${message}";
target.ControlName = logRichTextBox.Name;
target.FormName = this.Name;
target.UseDefaultRowColoringRules = true;
target.AutoScroll = true;
target.MaxLines = 50;
NLog.Config.SimpleConfigurator.ConfigureForTargetLogging(target, LogLevel.Trace);
log = LogManager.GetCurrentClassLogger();
}
private void LogForm_Load(object sender, EventArgs e)
{
InitLogger();
}
}
}

BackgroundWorker's RunWorkerCompleted is triggered twice

I have created a small project with a progress bar to test how BackgroundWorker does its job. So the progress bar goes from 0 to 100%. But now what I want to do is to trigger another BackgroundWorker after the first one finishes its job. The second BackgroundWorker simply has to display a MessageBox. I have put the second worker's RunWorkerAsync() event at the end of the first worker's RunWorkerCompleted() event. To make sure the first worker's method is completed.
Strange thing that happens is that my second worker's DoWork() event is triggered twice.
This is a simplified version of the error I am getting in my main program.
Can anyone spot the issue?
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace backgroundworker
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
bw1 = new BackgroundWorker();
bw1.DoWork += new DoWorkEventHandler(bw1_DoWork);
bw1.ProgressChanged += new ProgressChangedEventHandler(bw1_ProgressChanged);
bw1.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bw1_RunWorkerCompleted);
bw1.WorkerReportsProgress = true;
bw1.WorkerSupportsCancellation = true;
bw2.DoWork += new DoWorkEventHandler(bw2_DoWork);
bw2.ProgressChanged += new ProgressChangedEventHandler(bw2_ProgressChanged);
bw2.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bw2_RunWorkerCompleted);
}
private void bw1_DoWork(object sender, DoWorkEventArgs e)
{
for (int i = 0; i < 100; i++)
{
Thread.Sleep(50);
bw1.ReportProgress(i);
if (bw1.CancellationPending)
{
e.Cancel = true;
bw1.ReportProgress(0);
return;
}
}
bw1.ReportProgress(100);
}
private void bw1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
progressBar1.Value = e.ProgressPercentage;
lblStatus.Text = "Processing......" + progressBar1.Value.ToString() + "%";
}
private void bw1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if (e.Cancelled)
{
lblStatus.Text = "Task Cancelled.";
}
else if (e.Error != null)
{
lblStatus.Text = "Error while performing background operation.";
}
else
{
lblStatus.Text = "Task Completed...";
}
btnStartAsyncOperation.Enabled = true;
btnCancel.Enabled = false;
bw2.RunWorkerAsync();
}
private void btnStartAsyncOperation_Click(object sender, EventArgs e)
{
btnStartAsyncOperation.Enabled = false;
btnCancel.Enabled = true;
bw1.RunWorkerAsync();
}
private void btnCancel_Click(object sender, EventArgs e)
{
if (bw1.IsBusy)
{
bw1.CancelAsync();
}
}
private void bw2_DoWork(object sender, DoWorkEventArgs e)
{
}
private void bw2_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
}
private void bw2_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
MessageBox.Show("Second task is done too.");
}
}
}
Update: Form1.Designer.cs
namespace backgroundworker
{
partial class Form1
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.progressBar1 = new System.Windows.Forms.ProgressBar();
this.lblStatus = new System.Windows.Forms.Label();
this.bw1 = new System.ComponentModel.BackgroundWorker();
this.btnStartAsyncOperation = new System.Windows.Forms.Button();
this.btnCancel = new System.Windows.Forms.Button();
this.bw2 = new System.ComponentModel.BackgroundWorker();
this.SuspendLayout();
//
// progressBar1
//
this.progressBar1.Location = new System.Drawing.Point(12, 154);
this.progressBar1.Name = "progressBar1";
this.progressBar1.Size = new System.Drawing.Size(1164, 100);
this.progressBar1.TabIndex = 1;
//
// lblStatus
//
this.lblStatus.AutoSize = true;
this.lblStatus.Font = new System.Drawing.Font("Microsoft Sans Serif", 15.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.lblStatus.Location = new System.Drawing.Point(469, 42);
this.lblStatus.Name = "lblStatus";
this.lblStatus.Size = new System.Drawing.Size(70, 25);
this.lblStatus.TabIndex = 2;
this.lblStatus.Text = "label1";
//
// bw1
//
this.bw1.WorkerReportsProgress = true;
this.bw1.WorkerSupportsCancellation = true;
this.bw1.DoWork += new System.ComponentModel.DoWorkEventHandler(this.bw1_DoWork);
this.bw1.ProgressChanged += new System.ComponentModel.ProgressChangedEventHandler(this.bw1_ProgressChanged);
this.bw1.RunWorkerCompleted += new System.ComponentModel.RunWorkerCompletedEventHandler(this.bw1_RunWorkerCompleted);
//
// btnStartAsyncOperation
//
this.btnStartAsyncOperation.Location = new System.Drawing.Point(12, 109);
this.btnStartAsyncOperation.Name = "btnStartAsyncOperation";
this.btnStartAsyncOperation.Size = new System.Drawing.Size(160, 39);
this.btnStartAsyncOperation.TabIndex = 3;
this.btnStartAsyncOperation.Text = "Start";
this.btnStartAsyncOperation.UseVisualStyleBackColor = true;
this.btnStartAsyncOperation.Click += new System.EventHandler(this.btnStartAsyncOperation_Click);
//
// btnCancel
//
this.btnCancel.Location = new System.Drawing.Point(1024, 109);
this.btnCancel.Name = "btnCancel";
this.btnCancel.Size = new System.Drawing.Size(152, 39);
this.btnCancel.TabIndex = 4;
this.btnCancel.Text = "Cancel";
this.btnCancel.UseVisualStyleBackColor = true;
this.btnCancel.Click += new System.EventHandler(this.btnCancel_Click);
//
// bw2
//
this.bw2.DoWork += new System.ComponentModel.DoWorkEventHandler(this.bw2_DoWork);
this.bw2.ProgressChanged += new System.ComponentModel.ProgressChangedEventHandler(this.bw2_ProgressChanged);
this.bw2.RunWorkerCompleted += new System.ComponentModel.RunWorkerCompletedEventHandler(this.bw2_RunWorkerCompleted);
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(1188, 272);
this.Controls.Add(this.btnCancel);
this.Controls.Add(this.btnStartAsyncOperation);
this.Controls.Add(this.lblStatus);
this.Controls.Add(this.progressBar1);
this.Name = "Form1";
this.Text = "Form1";
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.ProgressBar progressBar1;
private System.Windows.Forms.Label lblStatus;
private System.ComponentModel.BackgroundWorker bw1;
private System.Windows.Forms.Button btnStartAsyncOperation;
private System.Windows.Forms.Button btnCancel;
private System.ComponentModel.BackgroundWorker bw2;
}
}
You have registered the completed event on the designer.
this.bw1.RunWorkerCompleted += new System.ComponentModel.RunWorkerCompletedEventHandler(this.bw1_RunWorkerCompleted‌​);
this.bw2.RunWorkerCompleted += new System.ComponentModel.RunWorkerCompletedEventHandler(this.bw2_RunWorkerCompleted‌​);
And then you registered it again on code behind.
bw1.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bw1_RunWorkerCompleted);
bw2.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bw2_RunWorkerCompleted);
You need to remove ones of them.

The project compiles perfectly, but I get an unhandled exception and have no idea why

I get an unhandled exception that says:
System.NullReferenceException: Object reference not set to an instance of an object.
at Eagle_Eye_Class_Finder.GetSchedule.GetDataFromNumber(String ID) in C:\Users\Joshua Banks\Desktop\EET Project\Eagle Eye Class Finder\GetSchedule.cs:line 24
at Eagle_Eye_Class_Finder.Form1.button2_Click(Object sender, EventArgs e) in C:\Users\Joshua Banks\Desktop\EET Project\Eagle Eye Class Finder\Form1.cs:line 196
at System.Windows.Forms.Control.OnClick(EventArgs e)
at System.Windows.Forms.Button.OnClick(EventArgs e)
at System.Windows.Forms.Button.PerformClick()
at System.Windows.Forms.Form.ProcessDialogKey(Keys keyData)
at System.Windows.Forms.Control.ProcessDialogKey(Keys keyData)
at System.Windows.Forms.TextBoxBase.ProcessDialogKey(Keys keyData)
at System.Windows.Forms.Control.PreProcessMessage(Message& msg)
at System.Windows.Forms.Control.PreProcessControlMessageInternal(Control target, Message& msg)
at System.Windows.Forms.Application.ThreadContext.PreTranslateMessage(MSG& msg)
Here is my get schedule class:
using System;
using System.IO;
using System.Data;
using System.Text;
using System.Drawing;
using System.Data.OleDb;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Drawing.Printing;
using System.Collections.Generic;
namespace Eagle_Eye_Class_Finder
{
public class GetSchedule
{
public string GetDataFromNumber(string ID)
{
IDnumber[] IDnumbers = new IDnumber[3];
foreach (IDnumber IDCandidateMatch in IDnumbers)
{
if (IDCandidateMatch.ID == ID)
{
StringBuilder myData = new StringBuilder();
myData.AppendLine(IDCandidateMatch.Name);
myData.AppendLine(": ");
myData.AppendLine(IDCandidateMatch.ID);
myData.AppendLine(IDCandidateMatch.year);
myData.AppendLine(IDCandidateMatch.class1);
myData.AppendLine(IDCandidateMatch.class2);
myData.AppendLine(IDCandidateMatch.class3);
myData.AppendLine(IDCandidateMatch.class4);
//return myData;
return myData.ToString();
}
}
return "";
}
public GetSchedule()
{
IDnumber[] IDnumbers = new IDnumber[3];
IDnumbers[0] = new IDnumber() { Name = "Joshua Banks", ID = "900456317", year = "Senior", class1 = "TEET 4090", class2 = "TEET 3020", class3 = "TEET 3090", class4 = "TEET 4290" };
IDnumbers[1] = new IDnumber() { Name = "Sean Ward", ID = "900456318", year = "Junior", class1 = "ENGNR 4090", class2 = "ENGNR 3020", class3 = "ENGNR 3090", class4 = "ENGNR 4290" };
IDnumbers[2] = new IDnumber() { Name = "Terrell Johnson", ID = "900456319", year = "Sophomore", class1 = "BUS 4090", class2 = "BUS 3020", class3 = "BUS 3090", class4 = "BUS 4290" };
}
public class IDnumber
{
public string Name { get; set; }
public string ID { get; set; }
public string year { get; set; }
public string class1 { get; set; }
public string class2 { get; set; }
public string class3 { get; set; }
public string class4 { get; set; }
public static void ProcessNumber(IDnumber myNum)
{
StringBuilder myData = new StringBuilder();
myData.AppendLine(myNum.Name);
myData.AppendLine(": ");
myData.AppendLine(myNum.ID);
myData.AppendLine(myNum.year);
myData.AppendLine(myNum.class1);
myData.AppendLine(myNum.class2);
myData.AppendLine(myNum.class3);
myData.AppendLine(myNum.class4);
MessageBox.Show(myData.ToString());
}
}
}
}
Here is my Form 1 class:
using System;
using System.IO;
using System.Data;
using System.Text;
using System.Drawing;
using System.Data.OleDb;
using System.Collections;
using System.Windows.Forms;
using System.ComponentModel;
using System.Drawing.Printing;
using System.Collections.Generic;
namespace Eagle_Eye_Class_Finder
{
/// This form is the entry form, it is the first form the user will see when the app is run.
///
public class Form1 : System.Windows.Forms.Form
{
private System.Windows.Forms.TextBox textBox1;
private System.Windows.Forms.ProgressBar progressBar1;
private System.Windows.Forms.PictureBox pictureBox1;
private System.Windows.Forms.Button button2;
private System.Windows.Forms.DateTimePicker dateTimePicker1;
private IContainer components;
private Timer timer1;
private BindingSource form1BindingSource;
public static Form Mainform = null;
// creates new instance of second form
YOURCLASSSCHEDULE SecondForm = new YOURCLASSSCHEDULE();
public Form1()
{
InitializeComponent();
// TODO: Add any constructor code after InitializeComponent call
}
/// Clean up any resources being used.
protected override void Dispose(bool disposing)
{
if (disposing)
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(Form1));
this.textBox1 = new System.Windows.Forms.TextBox();
this.progressBar1 = new System.Windows.Forms.ProgressBar();
this.pictureBox1 = new System.Windows.Forms.PictureBox();
this.button2 = new System.Windows.Forms.Button();
this.dateTimePicker1 = new System.Windows.Forms.DateTimePicker();
this.timer1 = new System.Windows.Forms.Timer(this.components);
this.form1BindingSource = new System.Windows.Forms.BindingSource(this.components);
((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.form1BindingSource)).BeginInit();
this.SuspendLayout();
//
// textBox1
//
this.textBox1.BackColor = System.Drawing.SystemColors.ActiveCaption;
this.textBox1.DataBindings.Add(new System.Windows.Forms.Binding("Text", this.form1BindingSource, "Text", true, System.Windows.Forms.DataSourceUpdateMode.OnValidation, null, "900456317"));
this.textBox1.Location = new System.Drawing.Point(328, 280);
this.textBox1.Name = "textBox1";
this.textBox1.Size = new System.Drawing.Size(208, 20);
this.textBox1.TabIndex = 2;
this.textBox1.TextChanged += new System.EventHandler(this.textBox1_TextChanged);
//
// progressBar1
//
this.progressBar1.Location = new System.Drawing.Point(258, 410);
this.progressBar1.MarqueeAnimationSpeed = 10;
this.progressBar1.Name = "progressBar1";
this.progressBar1.Size = new System.Drawing.Size(344, 8);
this.progressBar1.TabIndex = 3;
this.progressBar1.Click += new System.EventHandler(this.progressBar1_Click);
//
// pictureBox1
//
this.pictureBox1.BackColor = System.Drawing.SystemColors.ControlLightLight;
this.pictureBox1.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
this.pictureBox1.Image = ((System.Drawing.Image)(resources.GetObject("pictureBox1.Image")));
this.pictureBox1.Location = new System.Drawing.Point(680, 400);
this.pictureBox1.Name = "pictureBox1";
this.pictureBox1.Size = new System.Drawing.Size(120, 112);
this.pictureBox1.TabIndex = 4;
this.pictureBox1.TabStop = false;
this.pictureBox1.Click += new System.EventHandler(this.pictureBox1_Click);
//
// button2
//
this.button2.Font = new System.Drawing.Font("Mistral", 15.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.button2.Image = ((System.Drawing.Image)(resources.GetObject("button2.Image")));
this.button2.Location = new System.Drawing.Point(699, 442);
this.button2.Name = "button2";
this.button2.Size = new System.Drawing.Size(78, 28);
this.button2.TabIndex = 5;
this.button2.Text = "OK";
this.button2.Click += new System.EventHandler(this.button2_Click);
//
// dateTimePicker1
//
this.dateTimePicker1.Location = new System.Drawing.Point(336, 104);
this.dateTimePicker1.Name = "dateTimePicker1";
this.dateTimePicker1.Size = new System.Drawing.Size(200, 20);
this.dateTimePicker1.TabIndex = 6;
this.dateTimePicker1.ValueChanged += new System.EventHandler(this.dateTimePicker1_ValueChanged);
//
// timer1
//
this.timer1.Tick += new System.EventHandler(this.timer1_Tick);
//
// form1BindingSource
//
this.form1BindingSource.DataSource = typeof(Eagle_Eye_Class_Finder.Form1);
//
// Form1
//
this.AcceptButton = this.button2;
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.BackgroundImage = ((System.Drawing.Image)(resources.GetObject("$this.BackgroundImage")));
this.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch;
this.ClientSize = new System.Drawing.Size(856, 556);
this.Controls.Add(this.dateTimePicker1);
this.Controls.Add(this.button2);
this.Controls.Add(this.pictureBox1);
this.Controls.Add(this.progressBar1);
this.Controls.Add(this.textBox1);
this.Name = "Form1";
this.Text = "Eagle Eye Class Finder";
this.Load += new System.EventHandler(this.Form1_Load);
((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.form1BindingSource)).EndInit();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
/// The main entry point for the application.
[STAThread]
static void Main()
{
Application.Run(new Form1());
}
public void Form1_Load(object sender, System.EventArgs e)
{
}
public void textBox1_TextChanged(object sender, System.EventArgs e)
{
//allows only numbers to be entered in textbox
string Str = textBox1.Text.Trim();
double Num;
bool isNum = double.TryParse(Str, out Num);
if (isNum)
Console.ReadLine();
else
MessageBox.Show("Enter A Valid ID Number!");
}
public void button2_Click(object sender, System.EventArgs e)
{
string text = textBox1.Text;
Mainform = this;
this.Hide();
GetSchedule myScheduleFinder = new GetSchedule();
string result = myScheduleFinder.GetDataFromNumber(text);
if (!string.IsNullOrEmpty(result))
{
MessageBox.Show(result);
}
else
{
MessageBox.Show("Enter A Valid ID Number!");
}
}
public void dateTimePicker1_ValueChanged(object sender, System.EventArgs e)
{
}
public void pictureBox1_Click(object sender, System.EventArgs e)
{
}
public void progressBar1_Click(object sender, EventArgs e)
{
//this.progressBar1 = new System.progressBar1();
//progressBar1.Maximum = 200;
//progressBar1.Minimum = 0;
//progressBar1.Step = 20;
}
private void timer1_Tick(object sender, EventArgs e)
{
//if (progressBar1.Value >= 200 )
//{
//progressBar1.Value = 0;
//}
//return;
//}
//progressBar1.Value != 20;
}
}
}
Here is my form 2 class:
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
namespace Eagle_Eye_Class_Finder
{
/// <summary>
/// Summary description for Form2.
/// </summary>
public class YOURCLASSSCHEDULE : System.Windows.Forms.Form
{
public System.Windows.Forms.LinkLabel linkLabel1;
public System.Windows.Forms.LinkLabel linkLabel2;
public System.Windows.Forms.LinkLabel linkLabel3;
public System.Windows.Forms.LinkLabel linkLabel4;
private Button button1;
/// Required designer variable.
public System.ComponentModel.Container components = null;
public YOURCLASSSCHEDULE()
{
//
InitializeComponent();
// TODO: Add any constructor code after InitializeComponent call
}
/// Clean up any resources being used.
protected override void Dispose(bool disposing)
{
if (disposing)
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(YOURCLASSSCHEDULE));
this.linkLabel1 = new System.Windows.Forms.LinkLabel();
this.linkLabel2 = new System.Windows.Forms.LinkLabel();
this.linkLabel3 = new System.Windows.Forms.LinkLabel();
this.linkLabel4 = new System.Windows.Forms.LinkLabel();
this.button1 = new System.Windows.Forms.Button();
this.SuspendLayout();
//
// linkLabel1
//
this.linkLabel1.BackColor = System.Drawing.SystemColors.ActiveCaption;
this.linkLabel1.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
this.linkLabel1.Font = new System.Drawing.Font("Times New Roman", 14.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.linkLabel1.LinkArea = new System.Windows.Forms.LinkArea(0, 7);
this.linkLabel1.LinkBehavior = System.Windows.Forms.LinkBehavior.HoverUnderline;
this.linkLabel1.Location = new System.Drawing.Point(41, 123);
this.linkLabel1.Name = "linkLabel1";
this.linkLabel1.Size = new System.Drawing.Size(288, 32);
this.linkLabel1.TabIndex = 1;
this.linkLabel1.TabStop = true;
this.linkLabel1.Text = "Class 1";
this.linkLabel1.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
this.linkLabel1.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.linkLabel1_LinkClicked);
//
// linkLabel2
//
this.linkLabel2.BackColor = System.Drawing.SystemColors.ActiveCaption;
this.linkLabel2.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
this.linkLabel2.Font = new System.Drawing.Font("Times New Roman", 14.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.linkLabel2.LinkBehavior = System.Windows.Forms.LinkBehavior.HoverUnderline;
this.linkLabel2.Location = new System.Drawing.Point(467, 123);
this.linkLabel2.Name = "linkLabel2";
this.linkLabel2.Size = new System.Drawing.Size(288, 32);
this.linkLabel2.TabIndex = 2;
this.linkLabel2.TabStop = true;
this.linkLabel2.Text = "Class 2";
this.linkLabel2.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
this.linkLabel2.VisitedLinkColor = System.Drawing.Color.Navy;
this.linkLabel2.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.linkLabel2_LinkClicked);
//
// linkLabel3
//
this.linkLabel3.BackColor = System.Drawing.SystemColors.ActiveCaption;
this.linkLabel3.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
this.linkLabel3.Font = new System.Drawing.Font("Times New Roman", 14.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.linkLabel3.LinkBehavior = System.Windows.Forms.LinkBehavior.HoverUnderline;
this.linkLabel3.Location = new System.Drawing.Point(41, 311);
this.linkLabel3.Name = "linkLabel3";
this.linkLabel3.Size = new System.Drawing.Size(288, 32);
this.linkLabel3.TabIndex = 3;
this.linkLabel3.TabStop = true;
this.linkLabel3.Text = "Class 3";
this.linkLabel3.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
this.linkLabel3.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.linkLabel3_LinkClicked);
//
// linkLabel4
//
this.linkLabel4.BackColor = System.Drawing.SystemColors.ActiveCaption;
this.linkLabel4.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
this.linkLabel4.Font = new System.Drawing.Font("Times New Roman", 14.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.linkLabel4.LinkBehavior = System.Windows.Forms.LinkBehavior.HoverUnderline;
this.linkLabel4.Location = new System.Drawing.Point(467, 311);
this.linkLabel4.Name = "linkLabel4";
this.linkLabel4.Size = new System.Drawing.Size(288, 32);
this.linkLabel4.TabIndex = 4;
this.linkLabel4.TabStop = true;
this.linkLabel4.Text = "Class 4";
this.linkLabel4.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
this.linkLabel4.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.linkLabel4_LinkClicked);
//
// button1
//
this.button1.BackColor = System.Drawing.SystemColors.ActiveCaptionText;
this.button1.FlatAppearance.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(0)))), ((int)(((byte)(0)))), ((int)(((byte)(64)))));
this.button1.FlatStyle = System.Windows.Forms.FlatStyle.Popup;
this.button1.Font = new System.Drawing.Font("Pristina", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.button1.ForeColor = System.Drawing.SystemColors.ActiveCaption;
this.button1.ImageAlign = System.Drawing.ContentAlignment.TopCenter;
this.button1.Location = new System.Drawing.Point(358, 206);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(101, 25);
this.button1.TabIndex = 5;
this.button1.Text = "Go Back";
this.button1.UseVisualStyleBackColor = false;
this.button1.Click += new System.EventHandler(this.button1_Click);
//
// YOURCLASSSCHEDULE
//
this.AutoScaleBaseSize = new System.Drawing.Size(6, 15);
this.BackgroundImage = ((System.Drawing.Image)(resources.GetObject("$this.BackgroundImage")));
this.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch;
this.ClientSize = new System.Drawing.Size(790, 482);
this.Controls.Add(this.button1);
this.Controls.Add(this.linkLabel4);
this.Controls.Add(this.linkLabel3);
this.Controls.Add(this.linkLabel2);
this.Controls.Add(this.linkLabel1);
this.Font = new System.Drawing.Font("OldDreadfulNo7 BT", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.Name = "YOURCLASSSCHEDULE";
this.Text = "Your Classes";
this.Load += new System.EventHandler(this.Form2_Load);
this.ResumeLayout(false);
}
#endregion
public void Form2_Load(object sender, System.EventArgs e)
{
// if (text == "900456317")
// {
//}
}
public void linkLabel1_LinkClicked(object sender, System.Windows.Forms.LinkLabelLinkClickedEventArgs e)
{
System.Diagnostics.Process.Start("http://www.georgiasouthern.edu/map/");
}
private void linkLabel2_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
System.Diagnostics.Process.Start("http://www.georgiasouthern.edu/map/");
}
private void linkLabel3_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
System.Diagnostics.Process.Start("http://www.georgiasouthern.edu/map/");
}
private void linkLabel4_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
System.Diagnostics.Process.Start("http://www.georgiasouthern.edu/map/");
}
private void button1_Click(object sender, EventArgs e)
{
Form1 form1 = new Form1();
form1.Show();
this.Hide();
}
}
}
The problem is on this if statement:
IDnumber[] IDnumbers = new IDnumber[3];
foreach (IDnumber IDCandidateMatch in IDnumbers)
{
if (IDCandidateMatch.ID == ID)
You created array with three elements, but all elements are null. When you loop through them, the reference to IDCandidateMatch.ID generates the NullReferenceException.
Compiling perfectly has nothing to do with Exceptions. I would suggest looking at the stacktrace on the Exception, trying to find the line where the error is occuring, and going from there.
It looks like line 24 of GetSchedule.cs is a good place to start!
You're creating 2 different arrays, one in the constructor and another one in the method. if you move the line
IDnumber[] IDnumbers = new IDnumber[3];
outside of the method, and delete the identical one in the constructor it should work

Categories

Resources