I have a button which when pressed closes the current form and opens a new form of the same class - i.e. so it opens a new form in it original state.
I have another button which has the same functionality, however I try to call a function in the code so when the new form opens it runs importGantt() a function of the form.
The problem I have is that when I click the button it closes the current form and opens a new one, as expected, however it does not call the importGantt() function until I close the application.
Any ideas?
Much appreciated.
private void browseFileToolStripMenuItem_Click(object sender, EventArgs e)
{
clearAndImport();
}
private void clearAndImport()
{
this.Hide();
Dashboard dashboard = new Dashboard();
dashboard.ShowDialog();
dashboard.importGantt();
this.Close();
}
private void importGantt()
{
// Edit Interface
btnImport.Visible = false;
dataCapPlan.Visible = true;
dataMilestones.Visible = true;
pnlGantt.Visible = true;
Graphics ganttGraphics = pnlGantt.CreateGraphics();
// Draw axis
// Import Files
fileCapPlan.Title = "Select Capital Plan File";
fileCapPlan.Filter = "Excel Workbook (.xlsx)|*.xlsx";
DialogResult resCapPlan = fileCapPlan.ShowDialog();
if (resCapPlan == DialogResult.OK)
{
cnStr = cnStr + fileCapPlan.FileName;
}
else
{
MessageBox.Show("Error: Unable to import file");
}
fileMilestones.Title = "Select Milestones File";
fileMilestones.Filter = "Excel Workbook (.xlsx)|*.xlsx";
DialogResult resMilestones = fileMilestones.ShowDialog();
if (resMilestones == DialogResult.OK)
{
cnStr2 = cnStr2 + fileMilestones.FileName;
}
else
{
MessageBox.Show("Error: Unable to import file");
}
// Use OleDb connection to import Excel data
using (OleDbConnection cn = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + cnStr + ";Extended Properties=" + "'EXCEL 12.0 Xml;HDR=YES'"))
{
using (OleDbDataAdapter adapter = new OleDbDataAdapter(sqlSelectAll, cn))
{
adapter.Fill(dtCapPlan);
dataCapPlan.DataSource = dtCapPlan;
dataCapPlan.AutoResizeColumns();
}
}
using (OleDbConnection cn = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + cnStr2 + ";Extended Properties=" + "'EXCEL 12.0 Xml;HDR=YES'"))
{
using (OleDbDataAdapter adapter = new OleDbDataAdapter(sqlSelectAll, cn))
{
adapter.Fill(dtMilestones);
dataMilestones.DataSource = dtMilestones;
dataMilestones.AutoResizeColumns();
}
}
// Draw Gantt Chart
foreach (DataRow rowCapPlan in dtCapPlan.Rows)
{
id = rowCapPlan["Program ID"].ToString();
foreach (DataRow rowMilestone in dtMilestones.Rows)
{
if (id == rowMilestone["Program ID"].ToString())
{
// calculate space in days from todays date and the milestone date
msDate = Convert.ToDateTime(rowMilestone["Milestone Date"]);
msTimespan = msDate - calDate;
msIntDate = (int)msTimespan.TotalDays + 1;
tTimespan = tDate - calDate;
tIntDate = (int)tTimespan.TotalDays + 1;
ganttPlotSpace = msIntDate - tIntDate;
// Draw each milestone or gateway which is not yet complete
if (rowMilestone["% Complete"].ToString() != "100")
{
taskname = rowMilestone["Task Name"].ToString();
if (taskname == "Gateway 1" || taskname == "Gateway 2" || taskname == "Gateway 3" || taskname == "Gateway 4" || taskname == "Gateway 5")
{
Rectangle gw = new Rectangle(startx + ganttPlotSpace, starty - 4, 2, 11);
ganttGraphics.DrawRectangle(gwPen, gw);
ganttGraphics.FillRectangle(gwBrush, gw);
}
else
{
Rectangle ms = new Rectangle(startx + ganttPlotSpace + 1, starty, 2, 2);
ganttGraphics.DrawRectangle(msPen, ms);
ganttGraphics.FillRectangle(msBrush, ms);
}
ganttGraphics.DrawLine(linePen, startx - 10, starty - 11, pnlGantt.Right, starty - 11);
}
}
}
starty = starty + 22;
}
ganttGraphics.DrawLine(linePen, startx - 10, starty + 11, pnlGantt.Right, starty + 11);
}
image with gantt
image after clearAndImport method (FIXED by user)
As per Brij guidance:
Okay, so with the guidance this almost works, the code is now as follows...
This now opens the new form and runs the import method, however, it seems to be running it on a loop. I.e. it runs successfully displaying the gantt, but then tries to run the import gantt method again.
bool clear;
public Dashboard(bool clear = false)
{
InitializeComponent();
dataCapPlan.ColumnHeaderMouseClick += new DataGridViewCellMouseEventHandler(dataCapPlan_ColumnHeaderMouseClick);
this.clear = clear;
this.Load += new EventHandler(Dashboard_Load);
}
private void Dashboard_Load(object sender, EventArgs e)
{
if (this.clear)
{
this.importGantt();
}
}
// Clear and import method
private void clearAndImport()
{
this.Hide();
Dashboard dashboard = new Dashboard();
dashboard.clear = true;
dashboard.ShowDialog();
this.Close();
}
I think the method that you are referring is below:
private void clearAndImport()
{
this.Hide();
Dashboard dashboard = new Dashboard();
dashboard.ShowDialog();
dashboard.importGantt();
this.Close();
}
You are calling dashboard.ShowDialog(). So until you close the "Dashboard" form, next line of code (dashboard.importGantt()) won't get called. I suggest you call importGantt() in constructor or Load event of Dashboard form. You could change the sequence of code as well by moving dashboard.importGantt() above dashboard.ShowDialog().
As per your comment, I suggest, modify the constructor of Dashboard class to accept a boolean parameter and make it optional (defaulting to false). If true is passed, then only call importGantt(). So it will be like:
public Dashboard(bool clear = false)
{
InitializeComponent();
if(clear)
{
this.importGantt();
}
}
and the you clearAndImport() method will be like:
private void clearAndImport()
{
this.Hide();
Dashboard dashboard = new Dashboard(true);
dashboard.ShowDialog();
this.Close();
}
As per my last comment, try this:
bool clear = false;
public Dashboard(bool clear = false)
{
InitializeComponent();
this.clear = clear;
this.Load += new EventHandler(Dashboard_Load);
}
void Dashboard_Load(object sender, EventArgs)
{
if(this.clear)
{
this.importGantt();
}
}
Try dashboard.Show(); instead of dashboard.ShowDialog();
using (var dashboard = new Dashboard())
{
dashboard.Show(); // Show the form
dashboard.importGantt(); // Call
dashboard.Close(); // Close it when you're done...
}
Related
So I have this program I made a couple of years ago that helps me process and correct data I have for my work. I run it once an year and forget about it till the next year.
I have a big data file (usually over 800k+ rows and 5 columns) that have to go through various checks for data correctness. I bind the file via an excel spreadsheet into the datagridview like this:
public DataTable ReadExcel(string fileName, string fileExt)
{
string conn = string.Empty;
DataTable dtexcel = new DataTable();
if (fileExt.CompareTo(".xlsx") == 0)
{
conn = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fileName + ";Extended Properties='Excel 12.0;HDR=NO';"; //for above excel 2007
}
using (OleDbConnection con = new OleDbConnection(conn))
{
try
{
OleDbDataAdapter oleAdpt = new OleDbDataAdapter("SELECT * FROM [Sheet1$]", con); //here we read data from sheet1
oleAdpt.Fill(dtexcel); //fill excel data into dataTable
}
catch { }
}
return dtexcel;
}
Also I load the file using this:
private void loadExcelTable_Click(object sender, EventArgs e)
{
string filePath = string.Empty;
string fileExt = string.Empty;
OpenFileDialog file = new OpenFileDialog(); //open dialog to choose file
if (file.ShowDialog() == DialogResult.OK) //if there is a file choosen by the user
{
filePath = file.FileName; //get the path of the file
fileExt = System.IO.Path.GetExtension(filePath); //get the file extension
textBox1.Text = filePath; //display the path to the file in the loadFile text box
if (fileExt.CompareTo(".xls") == 0 || fileExt.CompareTo(".xlsx") == 0)
{
try
{
this.Cursor = Cursors.WaitCursor;
phoneGridView1.VirtualMode = true;
phoneGridView1.Visible = true;
phoneGridView1.DataSource = ReadExcel(filePath, fileExt);
this.Cursor = Cursors.Default;
MessageBox.Show("Файлът зареден успешно!", "Success!", MessageBoxButtons.OK); //custom message for successful file loading
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString());
}
}
else
{
MessageBox.Show("Моля изберете .xlsx файл.", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Error); //custom messageBox to show error
}
}
}
After everything is loaded, I press the button and various checks on the data start happening internally (lots of ifs involved).
Last year when I did this, everything went smoothly and the checks went out for about 3h on the whole file. THIS YEAR something changed. I dont know if it is from some VS2019 update or something, but the internal checks were taking way way way more time. I let the file sit for a whole week and it didnt even check half of it.
My questions are: is there a way to get things working as before? Did some update during that year changed the way the datagridview processes data?
I didnt do any changes to the code between my last working and now. The only thing that was changed was that I changed my GPU, but I dont believe this can cause such a huge drop in performance (I upgraded, no downgraded).
Any kind of help with this issue will be much appreciated.
Sample code of internal checks for data validation:
private void checkEmail(string email, int i)
{
//counts the symbols after the # symbol
string afterSymbol = email.Substring(email.LastIndexOf('#') + 1);
int lenght = afterSymbol.Length;
if (email.Contains("#") && email.Contains(".") && lenght >= 5)
{
phoneGridView1.Rows[i].Cells[4].Value = "01";
}
else
{
phoneGridView1.Rows[i].Cells[4].Value = "02";
}
phoneGridView1.Update();
}
Button_click function: All functions that are called here consists of various segments like the code segment above that checks the data in the datagridview
private void checks_Click(object sender, EventArgs e)
{
if (phoneGridView1.Rows.Count != 0)
{
int maxRows = phoneGridView1.RowCount;
int maxColumns = phoneGridView1.ColumnCount;
string fieldValue;
DataTable Codes1 = Codes(textBox2.Text);
Codes1.PrimaryKey = new DataColumn[] { Codes1.Columns["Column1"] };
this.Cursor = Cursors.WaitCursor;
if (Codes1.Rows.Count >0)
{
//Check each row if it contains one of the appointed values
for (int i = 1; i < maxRows; i++)
{
fieldValue = phoneGridView1.Rows[i].Cells[3].Value.ToString();
//Checks if the value in the row is the email
if (phoneGridView1.Rows[i].Cells[2].Value.ToString() == "3")
{
checkEmail(fieldValue, i);
}
//Checks if the value in the row is GSM number
if (phoneGridView1.Rows[i].Cells[2].Value.ToString() == "5")
{
checkGSM(fieldValue, i);
}
//Check if the telephone number is correct
if (phoneGridView1.Rows[i].Cells[2].Value.ToString() == "1")
{
checkTelephone(fieldValue, i, Codes1);
}
//Check if the fax number is correct
if (phoneGridView1.Rows[i].Cells[2].Value.ToString() == "2")
{
checkFax(fieldValue, i, Codes1);
}
//Check if the web page is correct
if (phoneGridView1.Rows[i].Cells[2].Value.ToString() == "6")
{
checkWeb(fieldValue, i);
}
if (phoneGridView1.Rows[i].Cells[4].Value.ToString() == string.Empty)
{
phoneGridView1.Rows[i].Cells[4].Value = "19";
}
}
this.Cursor = Cursors.Default;
MessageBox.Show("Успешно проверени данни!", "Success!", MessageBoxButtons.OK);
}
else
{
MessageBox.Show("Моля въведете файл със кодовете на населените места!", "Error!", MessageBoxButtons.OK);
}
}
else
{
MessageBox.Show("Моля въведете файл за проверка!", "Error!", MessageBoxButtons.OK);
}
}
I've been working on a bit of software in c# and it was going nicely but as of yesterday evening I noticed that it was throwing a memory exception error at the point when it loads an image.
I tried to decrease the image size but then realised that 'declaring rats' was being printed repeatedly to the console, where it should only occur once.
Digging a little deeper with some break points I found that it enters the drawing constructor at allRats = new Drawing(HousePicBox, DekuPicBox, BakuPicBox); //THIS HAS BECOME RECURSIVE, WTF
yet it doesn't seem to run the code within the constructor, but jumps back to the start of form1().
I have included all of the code within the files which the Program Counter touches.
//---------------------------------------------------FORM1.CS-------------------------------------------------------------
using System;
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;
// This is the code for your desktop app.
// Press Ctrl+F5 (or go to Debug > Start Without Debugging) to run your app.
namespace XMLRats5
{
public partial class Form1 : Form
{
// These are here as they are referred to by various functions for different reasons
string MazakSourceURL = "http://mtconnect.mazakcorp.com:5609"; // Gives us a human friendly reference to the HTML
string NISTSourceURL = "https://smstestbed.nist.gov/vds/current"; // Gives us a human friendly reference to the HTML
public PollTimer statusPoller;
public static Drawing allRats;
ImageRat Deku;
ImageRat Bakugo;
NISTDataSet CurrentNIST;
MazakDataSet CurrentMazak;
public Form1()
{
Console.WriteLine("Declaring Rats..."); // Is being called recursively :( ?????????????
ImageRat.Deku = new Rat(false, 0, 0, true, 0); // Declares Deku
ImageRat.Bakugo = new Rat(false, 800, 0, true, 0); // Declares Bakugo
Console.WriteLine("Initialising");
InitializeComponent(); // Constructs the graphics which make up the 'state 0'
Console.WriteLine("Declaring image");
allRats = new Drawing(HousePicBox, DekuPicBox, BakuPicBox); //THIS HAS BECOME RECURSIVE, WTF
Console.WriteLine("Clearing Image");
allRats.ClearRats();
Console.WriteLine("Displaying House");
HousePicBox.Show();
//allRats.DrawRats(ImageRat.deku.Awake, ImageRat.bakugo.Awake);
Console.WriteLine("Form 1 Initiated, please proceed.");
}
private void NISTDataLinkLabel_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
// This link takes you to the 'current' NIST testbed data feed page
System.Diagnostics.Process.Start(NISTSourceURL);
}
private void MAZAKDataLinkLabel_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
// This link takes you to the raw XML published by Mazaks HCN6800 labelled 5609
System.Diagnostics.Process.Start(MazakSourceURL);
}
public void StatusCheckButton_Click(object sender, EventArgs e) // Here we should check that the machine tools are feeding live data
{
// Clear the rat picture boxes as they 'stick' when already shown
DekuPicBox.Hide();
BakuPicBox.Hide();
string MazakStatus = "Unchecked";
string NISTStatus = "Unchecked";
try
{
CurrentMazak = MTFunctions.PollMazak();
MazakStatus = CurrentMazak.Status;
if (MazakStatus == "AVAILABLE") { ImageRat.Deku.Awake = true; }
}
catch (Exception MazakLookupFailed)
{
Console.WriteLine("Could not retrieve Mazak Data", MazakLookupFailed);
MazakStatus = "Lookup Failed"; // This will later refer to the xml path for running status
}
try
{
CurrentNIST = MTFunctions.PollNIST();
NISTStatus = CurrentNIST.Status;
if (NISTStatus == "AVAILABLE") { ImageRat.Bakugo.Awake = true; }
}
catch (Exception NISTLookupFailed)
{
Console.WriteLine("Could not Retrieve NIST Data: ", NISTLookupFailed);
NISTStatus = "Lookup Failed";
ImageRat.Bakugo.Awake = false;
}
string MessageString = " Mazak : " + MazakStatus + "\n NIST : " + NISTStatus;
if ((ImageRat.Deku.Awake == true) & (ImageRat.Bakugo.Awake == true)) // Both Online
{
HousePicBox.Image = XMLRats5.Properties.Resources.bothsleep; // SLeeping rat shows machine online but not feeding data
} // Empty Box
if ((ImageRat.Deku.Awake == true) & (ImageRat.Bakugo.Awake == false)) // NIST offline
{
HousePicBox.Image = XMLRats5.Properties.Resources.bakusleep;
DekuPicBox.Show(); // Not neccessary but prevents bugs
} // Put Bakug in box, deku out
if ((ImageRat.Deku.Awake == false) & (ImageRat.Bakugo.Awake == true)) // Mazak Offline
{
HousePicBox.Image = XMLRats5.Properties.Resources.dekuSleep;
BakuPicBox.Show(); // Not neccessary but prevents bugs
} // Put deku in box, bakugo out
if ((ImageRat.Deku.Awake == false) & (ImageRat.Bakugo.Awake == false)) // Both Offline
{
HousePicBox.Image = XMLRats5.Properties.Resources.nosleep;
} // Put rats in box
MessageBox.Show(MessageString, "Machine Status"); // We need to pass information gained through XPath to first argument
}
public void WakeRatsButton_Click(object sender, EventArgs e)
{
MessageBox.Show("This 'wakes the rats' (Begins data stream)");
// We need to poll Mazak and NIST here to determine which images to draw.
MazakDataSet checkM = MTFunctions.PollMazak();
NISTDataSet checkN = MTFunctions.PollNIST();
if (checkM.Status == "AVAILABLE")
{
ImageRat.Deku.Awake = true;
DekuPicBox.Show();
}
else { ImageRat.Deku.Awake = false; }
if (checkN.Status == "AVAILABLE")
{
BakuPicBox.Show();
ImageRat.Bakugo.Awake = true;
}
else { ImageRat.Bakugo.Awake = false; }
allRats.DrawRats(ImageRat.Deku.Awake, ImageRat.Bakugo.Awake); // Should move the boys out of the box
// Here the draw function successfully relocates the rats, so why does this not work from the timer?
statusPoller = new PollTimer(2000, true); //Initiate a timer driven function which polls the data sets
// Timer Driven function draws rats
}
public void DebugInstructionsLabel_Click(object sender, EventArgs e)
{ }
public void titleLabel_Click(object sender, EventArgs e) { }
public void SleepRatsButton_Click(object sender, EventArgs e)
{
MessageBox.Show("This 'puts the rats to bed' (Closes data stream)");
try // Stop Polling timer function
{
statusPoller.Stop();
statusPoller.Dispose();
Console.Write("Stream closed successfully");
}
catch { Console.WriteLine("Could not stop polling. Were the rats actually 'awake'?"); }
// Draw rats in house
DekuPicBox.Hide(); // Rat is no longer active
BakuPicBox.Hide(); // Rat is no longer active
HousePicBox.Image = XMLRats5.Properties.Resources.nosleep; // Show empty box
//allRats.Paint();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void HousePicBox_Click(object sender, EventArgs e)
{
}
private void DekuPicBox_Click(object sender, EventArgs e)
{
// Proves that problem with movement is because DekuPicBox needs to be changed, not allRats.dekuPic....
System.Drawing.Point DekuCoord = new System.Drawing.Point(ImageRat.Deku.PosX, ImageRat.Deku.PosY); // Create a 'System Point' for Deku
DekuPicBox.Location = DekuCoord;
Console.WriteLine("~~~~~~~~Deku moved to " + DekuCoord + " ~~~~~~~~");
}
private void BakuPicBox_Click(object sender, EventArgs e)
{
System.Drawing.Point BakuCoord = new System.Drawing.Point(ImageRat.Bakugo.PosX, ImageRat.Bakugo.PosY); // Create a 'System Point' for Deku
BakuPicBox.Location = BakuCoord;
Console.WriteLine("~~~~~~~~Bakugo moved to " + BakuCoord + " ~~~~~~~~");
}
public void Refresh(int boi) // Better bloody relocate those pics boii
{
if (boi == 0)
{
System.Drawing.Point BakuCoord = new System.Drawing.Point(ImageRat.Bakugo.PosX, ImageRat.Bakugo.PosY); // Create a 'System Point' for Deku
DekuPicBox.Location = BakuCoord;
}
else
{
System.Drawing.Point DekuCoord = new System.Drawing.Point(ImageRat.Deku.PosX, ImageRat.Deku.PosY); // Create a 'System Point' for Deku
DekuPicBox.Location = DekuCoord;
}
}
}
}
//----------------------------------------------FORM1.Designer.CS--------------------------------------------------------
namespace XMLRats5
{
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.MAZAKDataLinkLabel = new System.Windows.Forms.LinkLabel();
this.DebugInstructionsLabel = new System.Windows.Forms.Label();
this.StatusCheckButton = new System.Windows.Forms.Button();
this.TitleLabel = new System.Windows.Forms.Label();
this.WakeRatsButton = new System.Windows.Forms.Button();
this.SleepRatsButton = new System.Windows.Forms.Button();
this.NISTDataLinkLabel = new System.Windows.Forms.LinkLabel();
this.BakuPicBox = new System.Windows.Forms.PictureBox();
this.HousePicBox = new System.Windows.Forms.PictureBox();
this.DekuPicBox = new System.Windows.Forms.PictureBox();
((System.ComponentModel.ISupportInitialize)(this.BakuPicBox)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.HousePicBox)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.DekuPicBox)).BeginInit();
this.SuspendLayout();
//
// MAZAKDataLinkLabel
//
this.MAZAKDataLinkLabel.AutoSize = true;
this.MAZAKDataLinkLabel.Location = new System.Drawing.Point(1287, 985);
this.MAZAKDataLinkLabel.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0);
this.MAZAKDataLinkLabel.Name = "MAZAKDataLinkLabel";
this.MAZAKDataLinkLabel.Size = new System.Drawing.Size(179, 25);
this.MAZAKDataLinkLabel.TabIndex = 0;
this.MAZAKDataLinkLabel.TabStop = true;
this.MAZAKDataLinkLabel.Text = "View Mazak Data";
this.MAZAKDataLinkLabel.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.MAZAKDataLinkLabel_LinkClicked);
//
// DebugInstructionsLabel
//
this.DebugInstructionsLabel.AutoSize = true;
this.DebugInstructionsLabel.Location = new System.Drawing.Point(1066, 524);
this.DebugInstructionsLabel.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0);
this.DebugInstructionsLabel.Name = "DebugInstructionsLabel";
this.DebugInstructionsLabel.Size = new System.Drawing.Size(623, 50);
this.DebugInstructionsLabel.TabIndex = 1;
this.DebugInstructionsLabel.Text = "Press \'Check Machine\' to ensure a device is running, otherwise \n don\'t expect muc" +
"h activity from the rats!";
this.DebugInstructionsLabel.Click += new System.EventHandler(this.DebugInstructionsLabel_Click);
//
// StatusCheckButton
//
this.StatusCheckButton.Location = new System.Drawing.Point(1271, 658);
this.StatusCheckButton.Margin = new System.Windows.Forms.Padding(4);
this.StatusCheckButton.Name = "StatusCheckButton";
this.StatusCheckButton.Size = new System.Drawing.Size(195, 54);
this.StatusCheckButton.TabIndex = 2;
this.StatusCheckButton.Text = "Check Machine Status";
this.StatusCheckButton.UseVisualStyleBackColor = true;
this.StatusCheckButton.Click += new System.EventHandler(this.StatusCheckButton_Click);
//
// TitleLabel
//
this.TitleLabel.AutoSize = true;
this.TitleLabel.Font = new System.Drawing.Font("Microsoft Sans Serif", 16F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.TitleLabel.Location = new System.Drawing.Point(1255, 382);
this.TitleLabel.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0);
this.TitleLabel.Name = "TitleLabel";
this.TitleLabel.Size = new System.Drawing.Size(211, 51);
this.TitleLabel.TabIndex = 3;
this.TitleLabel.Text = "XML Rats";
this.TitleLabel.Click += new System.EventHandler(this.titleLabel_Click);
//
// WakeRatsButton
//
this.WakeRatsButton.Location = new System.Drawing.Point(1271, 775);
this.WakeRatsButton.Margin = new System.Windows.Forms.Padding(4);
this.WakeRatsButton.Name = "WakeRatsButton";
this.WakeRatsButton.Size = new System.Drawing.Size(195, 54);
this.WakeRatsButton.TabIndex = 4;
this.WakeRatsButton.Text = "Wake Rats";
this.WakeRatsButton.UseVisualStyleBackColor = true;
//
// SleepRatsButton
//
this.SleepRatsButton.Location = new System.Drawing.Point(1271, 885);
this.SleepRatsButton.Margin = new System.Windows.Forms.Padding(4);
this.SleepRatsButton.Name = "SleepRatsButton";
this.SleepRatsButton.Size = new System.Drawing.Size(195, 54);
this.SleepRatsButton.TabIndex = 5;
this.SleepRatsButton.Text = "Sleep Rats";
this.SleepRatsButton.UseVisualStyleBackColor = true;
//
// NISTDataLinkLabel
//
this.NISTDataLinkLabel.AutoSize = true;
this.NISTDataLinkLabel.Location = new System.Drawing.Point(1287, 1054);
this.NISTDataLinkLabel.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0);
this.NISTDataLinkLabel.Name = "NISTDataLinkLabel";
this.NISTDataLinkLabel.Size = new System.Drawing.Size(162, 25);
this.NISTDataLinkLabel.TabIndex = 6;
this.NISTDataLinkLabel.TabStop = true;
this.NISTDataLinkLabel.Text = "View NIST Data";
//
// BakuPicBox
//
this.BakuPicBox.Image = global::XMLRats5.Properties.Resources.bakuTransSmall;
this.BakuPicBox.Location = new System.Drawing.Point(2092, 1388);
this.BakuPicBox.Name = "BakuPicBox";
this.BakuPicBox.Size = new System.Drawing.Size(632, 424);
this.BakuPicBox.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage;
this.BakuPicBox.TabIndex = 9;
this.BakuPicBox.TabStop = false;
//
// HousePicBox
//
this.HousePicBox.Image = global::XMLRats5.Properties.Resources.nosleep;
this.HousePicBox.Location = new System.Drawing.Point(1057, 1388);
this.HousePicBox.Name = "HousePicBox";
this.HousePicBox.Size = new System.Drawing.Size(632, 424);
this.HousePicBox.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage;
this.HousePicBox.TabIndex = 8;
this.HousePicBox.TabStop = false;
//
// DekuPicBox
//
this.DekuPicBox.Image = global::XMLRats5.Properties.Resources.DekuBackgroundTransparent;
this.DekuPicBox.Location = new System.Drawing.Point(12, 1388);
this.DekuPicBox.Name = "DekuPicBox";
this.DekuPicBox.Size = new System.Drawing.Size(632, 424);
this.DekuPicBox.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage;
this.DekuPicBox.TabIndex = 7;
this.DekuPicBox.TabStop = false;
this.DekuPicBox.Click += new System.EventHandler(this.DekuPicBox_Click);
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(12F, 25F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(2736, 1824);
this.Controls.Add(this.BakuPicBox);
this.Controls.Add(this.HousePicBox);
this.Controls.Add(this.DekuPicBox);
this.Controls.Add(this.NISTDataLinkLabel);
this.Controls.Add(this.SleepRatsButton);
this.Controls.Add(this.WakeRatsButton);
this.Controls.Add(this.TitleLabel);
this.Controls.Add(this.StatusCheckButton);
this.Controls.Add(this.DebugInstructionsLabel);
this.Controls.Add(this.MAZAKDataLinkLabel);
this.Margin = new System.Windows.Forms.Padding(4);
this.Name = "Form1";
this.Text = "Form1";
((System.ComponentModel.ISupportInitialize)(this.BakuPicBox)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.HousePicBox)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.DekuPicBox)).EndInit();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.LinkLabel MAZAKDataLinkLabel;
private System.Windows.Forms.Label DebugInstructionsLabel;
private System.Windows.Forms.Button StatusCheckButton;
private System.Windows.Forms.Label TitleLabel;
private System.Windows.Forms.Button WakeRatsButton;
private System.Windows.Forms.Button SleepRatsButton;
private System.Windows.Forms.LinkLabel NISTDataLinkLabel;
public System.Windows.Forms.PictureBox DekuPicBox;
public System.Windows.Forms.PictureBox HousePicBox;
public System.Windows.Forms.PictureBox BakuPicBox;
}
}
//-------------------------------------------------------------DRAWING.CS----------------------------
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Reflection;
using System.Drawing;
using System.Windows.Forms;
namespace XMLRats5
{
public class Drawing : Form1
{
private PictureBox HouseImage;
private PictureBox DekuImage;
private PictureBox BakuImage;
public Drawing(PictureBox house, PictureBox deku, PictureBox baku)
{
HouseImage = house;
DekuImage = deku;
BakuImage = baku;
} // Code is jumping back to form1 call :S
public void ClearRats()
{
//DekuImage.Image.Dispose();
//BakuImage.Image.Dispose();
//HouseImage.Image.Dispose();
HouseImage.Hide();
DekuImage.Hide();
BakuImage.Hide();
}
public void RePaint()
{
//BakuImage.Paint();
//DekuImage.Paint();
//HouseImage.Paint();
}
public void DrawRats(bool DekuWake, bool BakuWake) // Call this function using active status of 2 machines
{
this.ClearRats();
DekuPicBox.SuspendLayout();
BakuPicBox.SuspendLayout();
HousePicBox.SuspendLayout();
System.Drawing.Point DekuCoord = new System.Drawing.Point(ImageRat.Deku.PosX, ImageRat.Deku.PosY); // Create a 'System Point' for Deku
System.Drawing.Point BakuCoord = new System.Drawing.Point(ImageRat.Bakugo.PosX, ImageRat.Bakugo.PosY); // Create a 'System Point' for Bakugo
Console.WriteLine("Randomly Generated Point Assigned (Deku):" + DekuCoord);
Console.WriteLine("Randomly Generated Point Assigned (Baku):" + BakuCoord);
if (DekuWake == false)
{
DekuImage.Hide();
if (BakuWake == false)
{
BakuPicBox.Hide();
HousePicBox.Image = XMLRats5.Properties.Resources.bothsleep;// set HouseImage to both sleep
}
else
{
BakuPicBox.Location = BakuCoord;
BakuPicBox.Show();
HousePicBox.Image = XMLRats5.Properties.Resources.dekuSleep; //Set HouseImage to DekuSleep
}
}
else //DekuWake == true
{
DekuImage.Show();
if (BakuWake == true)
{
HousePicBox.Image = XMLRats5.Properties.Resources.nosleep;//Set House image to nosleep
DekuPicBox.Location = DekuCoord;
DekuPicBox.Show();
BakuPicBox.Location = BakuCoord;
BakuPicBox.Show();
}
else
{
BakuPicBox.Hide();
HousePicBox.Image = XMLRats5.Properties.Resources.bakusleep;// Set house image to bakusleep
DekuPicBox.Location = DekuCoord;
DekuPicBox.Show();
}
}
HousePicBox.Show(); // Out here as it should always happen
}
}
}
Honestly I'm baffled as to why it keeps jumping back to the start of form1.
What have I broken?
As Drawing is derived from Form1 & you create an instance of Drawing in the Form1 constructor - this is going to cause the Form1 constructor to be invoked again which causes the creation of another instance of Drawing which causes ........... -
Note the base class constructor is called before the code in the derived class constructor - which is why you don't get to the code in the Drawing constructor.
I have the following code, the timerStart method that will call some functions every second, the problem is when the condition is true in checkSigning method, the pop up appears more than once.. How can i possibly fix this? Can someone help me :<
public void timerStart()
{
DispatcherTimer updaterTimer = new DispatcherTimer();
updaterTimer.Tick += new EventHandler(updaterTimer_Tick);
updaterTimer.Interval = new TimeSpan(0, 0, 1);
updaterTimer.Start();
}
private void updaterTimer_Tick(object sender, EventArgs e)
{
Time.Content = "Time : " + DateTime.Now.ToLongTimeString();
exist = saved_settings();
if (exist)
{
settingForToday();
checkSigningAvailable();
setSigning(signingAvailable = getSigning());
}
else
{
ongoing.Content = "Event : No Event";
sign_in.Content = "Sign-in Time : ";
sign_out.Content = "Sign-out Time : ";
}
}
public void checkSigningAvailable()
{
if (dt_signing_in.CompareTo(DateTime.Now) < 0)
{
if ((!InisOver && signing.Equals("in")) || (!InisOver && signing.Equals("in_out") && !OutisOver))
{
disableSigningIn(OutisOver.ToString(),this.event_id);
}
}
if (dt_signing_out.CompareTo(DateTime.Now) < 0)
{
if ((!OutisOver && signing.Equals("out")) || (!OutisOver && signing.Equals("in_out") && InisOver))
{
disableSigningOut(InisOver.ToString(),this.event_id);
}
}
}
public void disableSigningOut(string In,string event_id)
{
MessageBox.Show("Signing out is over!", "No more signing out!", MessageBoxButton.OK, MessageBoxImage.Information);
connection.Open();
string sign = In + ",True";
string query = "update data_storage set data_details = '" + sign + "' where data_name = 'Signing';";
NpgsqlCommand command = new NpgsqlCommand(query, connection);
NpgsqlDataReader dr = command.ExecuteReader();
dr.Close();
connection.Close();
sign_out.Content = "Sign-out Time : Over";
string query2 = concatQuery(getIDnumberAttendance(event_id));
updateAbsences(query2);
}
You can Stop the timer while you execute the tick and start it again on the end. The only down side you will have is that the time will be measure form the moment you finish you updaterTimer_Tick execution - but you may also consider it as a benefit.
private void updaterTimer_Tick(object sender, EventArgs e)
{
updaterTimer.Stop();
Time.Content = "Time : " + DateTime.Now.ToLongTimeString();
exist = saved_settings();
if (exist)
{
settingForToday();
checkSigningAvailable();
setSigning(signingAvailable = getSigning());
}
else
{
ongoing.Content = "Event : No Event";
sign_in.Content = "Sign-in Time : ";
sign_out.Content = "Sign-out Time : ";
}
updaterTimer.Start();
}
I got a tab container which has 4 tabs in it. In one of the tab named ADD TASK I got few fields like
(Task Name: --txtbox
Client Name:--drpdwn
Begin Date:--txtbox wid calendar
Due Date:--txtbox wid calendar
Description:--txtbox
Assign To:--drpdown
Status:--drpdown
% Complete:--drpdown)
and an ADD and CANCEL button in the end.
On running the project and inserting the values to those above mentioned fields i will click the add button and after clicking the button the values should store in my DATABASE. i have table named TASK in my DB already.
Please help me with the back end code.
here is my code
protected void BtnAdd_Click(object sender, EventArgs e)
{
MTMSDTO objc = new MTMSDTO();
int Flag = 0;
objc.TaskName = Session["TaskName"].ToString();
objc.ClientName = DrpClientName.SelectedItem.Text;
objc.BeginDate = Convert.ToDateTime(TxtBeginDate.Text);
objc.DueDate = Convert.ToDateTime(TxtDueDate.Text);
objc.Description = Session["Description"].ToString();
objc.AssignTo = DrpAssignTo.SelectedItem.Text;
objc.Status = DrpStatus.SelectedItem.Text;
objc.PercentageComplete = Convert.ToInt32(DrpPercentageComplete.Text);
int X = obj.InsertTask(objc);
{
if (X >= 0)
{
Flag = 1;
}
else
{
Flag = 0;
}
}
if (Flag == 1)
{
LblSuccess.Visible = true;
LblSuccess.Text = "Data Added Successfully";
Panel2.Visible = false;
}
else
{
LblErr.Visible = true;
LblErr.Text = "Failed To Add Data!!!";
}
}
im using layered architecture and i have this code on my ACCESS file of DAL CLASS
public int InsertTask(MTMSDTO M)
{
DBAccess db = new DBAccess();
SqlParameter objParam = new SqlParameter("#TaskID", M.TaskID);
objParam.Direction = ParameterDirection.Output;
db.Parameters.Add(new SqlParameter("#TaskName", M.TaskName));
db.Parameters.Add(new SqlParameter("#ClientName", M.ClientName));
db.Parameters.Add(new SqlParameter("#BeginDate", M.BeginDate));
db.Parameters.Add(new SqlParameter("#DueDate", M.DueDate));
db.Parameters.Add(new SqlParameter("#Description", M.Description));
db.Parameters.Add(new SqlParameter("#AssignTo", M.AssignTo));
db.Parameters.Add(new SqlParameter("#Status", M.Status));
db.Parameters.Add(new SqlParameter("#PercentageComplete", M.PercentageComplete));
db.Parameters.Add(objParam);
int retval = db.ExecuteNonQuery("InsertTask");
if (retval >= 1)
{
return int.Parse(objParam.Value.ToString());
}
else
{
return -1;
}
}
the code is edited now but im getting error as "object reference not set to an instance of an object. " for the line (objc.TaskName = Session["TaskName"].ToString();) which is in BtnAdd_Cick.
Shouldn't your BtnAdd_Click function be something like this instead? You don't currently seem to be calling the InsertTask() function.
protected void BtnAdd_Click(object sender, EventArgs e) {
MTMSDTO m = new MTMSDTO();
m.TaskName = TxtTaskName.Text;
m.ClientName = DrpClientName.Text;
m.BeginDate = TxtBeginDate.Text;
m.DueDate = TxtDueDate.Text;
m.Description = TxtDescription.Text;
m.AssignTo = DrpAssignTo.Text;
m.Status = DrpStatus.Text;
m.PercentageComplete = DrpPercentageComplete.Text;
InsertTask(m);
}
get all values in back end and pass to this function
public bool InsertRecord(string strTableName, string strColumn_Name, string strValues)
{
SqlConnection OBJCONNECTION;
StringBuilder strbQuery;
SqlCommand cmd;
try
{
OBJCONNECTION= new SqlConnection();
OBJCONNECTION.ConnectionString = ConfigurationManager.ConnectionStrings["Basic_ADO"].ConnectionString;//get connection string from web.config file
OBJCONNECTION=
strbQuery = new StringBuilder();
strbQuery.Append("INSERT INTO ");
strbQuery.Append(strTableName);
strbQuery.Append("(" + strColumn_Name + ")");
//strbQuery.Append(" VALUES");
strbQuery.Append("(" + strValues + ")");
cmd = new SqlCommand(strbQuery.ToString(), OBJCONNECTION);
cmd.ExecuteNonQuery();
return true;
}
catch (Exception ex) { throw ex; }
finally { strbQuery = null; cmd = null;OBJCONNECTION.close();}
}
Eventhough i specify a different location the file gets saved in mydocuments. How to resolve this issue. Pls share your ideas if any.Here is the code.
if (externalButton.Checked == true)
{
// int i = 1;
saveFileDialog.Title = "Save the Proofer Report";
saveFileDialog.Filter = "Document Files (*.doc)|*.doc|Document Files (*.docx)|*.docx";
saveFileDialog.FilterIndex = 0;
saveFileDialog.InitialDirectory = "MyDocuments";
saveFileDialog.FileName = "Proofer Report -- " + Path.GetFileName((string)fileName) + ".doc";
//i.tostring()
saveFileDialog.DefaultExt = ".doc";
saveFileDialog.ShowHelp = true;
// saveFileDialog.ShowDialog();
var thread = new Thread(new ParameterizedThreadStart(param => { saveFileDialog.ShowDialog(); }));
thread.SetApartmentState(ApartmentState.STA);
thread.Start();
fname = saveFileDialog.FileName;
You are showing dialog assynchronously on new thread and code after starting the thread executes before dialog is shown (most of the time).
Either wait for thread completion or move saving to that thread after dialog is closed.
Why You Are Showing saveFileDialog in different thread?
if you show save dialog in diffrent thread fname = saveFileDialog.FileName; is always return null.dont use separate thread.or Call this event after thread start
saveFileDialog1.FileOk += new CancelEventHandler(saveFileDialog1_FileOk);
void saveFileDialog1_FileOk(object sender, CancelEventArgs e)
{
string fname = null;
fname = saveFileDialog1.FileName;
}
Edited
Example
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
_SaveFileDialog.FileOk += new CancelEventHandler(_SaveFileDialog_FileOk);
}
string filename = null;
SaveFileDialog _SaveFileDialog = new SaveFileDialog();
private void savebtn_Click(object sender, EventArgs e)
{
_SaveFileDialog.Title = "Save the Proofer Report";
_SaveFileDialog.Filter = "Document Files (*.doc)|*.doc|Document Files (*.docx)|*.docx";
_SaveFileDialog.FilterIndex = 0;
_SaveFileDialog.InitialDirectory = "MyDocuments";
_SaveFileDialog.FileName = "Proofer Report -- .doc";
_SaveFileDialog.DefaultExt = ".doc";
_SaveFileDialog.ShowHelp = true;
var thread = new Thread(new ParameterizedThreadStart(param => { _SaveFileDialog.ShowDialog(); }));
thread.SetApartmentState(ApartmentState.STA);
thread.Start();
}
void _SaveFileDialog_FileOk(object sender, CancelEventArgs e)
{
filename = _SaveFileDialog.FileName;
}
}