InvalidOperationalException base.Dispose(disposing) - c#

I creating diagnostic application for PLCs. I have one form and a few Controls, which was inherited of UserControl. This Controls I switch. One view is Dashboard, Graph, and so on. When the graph is running, exception is occured. Exception is showed on line "base.Dispose(disposing)" in Form1.Designer.cs. Do you have any idea, how I can fix it? Thanks for any ideas.
This is code of Form1.Designer.cs. Error is show on line base.Dispose(disposing). Basicaly I don't know what this part of code do. That I can't repair it. Can somebody tell me, how it works? When is this part called? I don't find any use of method Dispose() in my program, only override methodes in each Control (inherited from UserControl). Thanks
namespace WindowsFormsApplication1
{
partial class Form1
{
///
/// Required designer variable.
///
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)
{
/*Updated 8.4.2013*/
//try
//{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
//}
//catch { }
}
#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(Form1));
this.statusStrip1 = new System.Windows.Forms.StatusStrip();
this.toolStripStatusLabel1 = new System.Windows.Forms.ToolStripStatusLabel();
this.btn_ChangeLanguage = new System.Windows.Forms.Button();
this.pictureBox1 = new System.Windows.Forms.PictureBox();
this.Zobraz_Palubka = new System.Windows.Forms.Button();
this.Zobraz_Verzi = new System.Windows.Forms.Button();
this.Zobraz_error = new System.Windows.Forms.Button();
this.Zobraz_Nastaveni = new System.Windows.Forms.Button();
this.Zobraz_TestIO = new System.Windows.Forms.Button();
this.Zobraz_monitor = new System.Windows.Forms.Button();
this.statusStrip1.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).BeginInit();
this.SuspendLayout();
//
// statusStrip1
//
this.statusStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.toolStripStatusLabel1});
resources.ApplyResources(this.statusStrip1, "statusStrip1");
this.statusStrip1.Name = "statusStrip1";
//
// toolStripStatusLabel1
//
this.toolStripStatusLabel1.Name = "toolStripStatusLabel1";
resources.ApplyResources(this.toolStripStatusLabel1, "toolStripStatusLabel1");
//
// btn_ChangeLanguage
//
this.btn_ChangeLanguage.Image = global::WindowsFormsApplication1.Properties.Resources.flag_cze_mini;
resources.ApplyResources(this.btn_ChangeLanguage, "btn_ChangeLanguage");
this.btn_ChangeLanguage.Name = "btn_ChangeLanguage";
this.btn_ChangeLanguage.UseVisualStyleBackColor = true;
this.btn_ChangeLanguage.Click += new System.EventHandler(this.btn_ChangeLanguage_Click);
this.btn_ChangeLanguage.MouseEnter += new System.EventHandler(this.Zobraz_Nastaveni_MouseEnter);
this.btn_ChangeLanguage.MouseLeave += new System.EventHandler(this.Zobraz_Nastaveni_MouseLeave);
//
// pictureBox1
//
this.pictureBox1.BackColor = System.Drawing.Color.Transparent;
this.pictureBox1.Image = global::WindowsFormsApplication1.Properties.Resources.trojuhelnik;
resources.ApplyResources(this.pictureBox1, "pictureBox1");
this.pictureBox1.Name = "pictureBox1";
this.pictureBox1.TabStop = false;
//
// Zobraz_Palubka
//
this.Zobraz_Palubka.Image = global::WindowsFormsApplication1.Properties.Resources.tachometr_mini;
resources.ApplyResources(this.Zobraz_Palubka, "Zobraz_Palubka");
this.Zobraz_Palubka.Name = "Zobraz_Palubka";
this.Zobraz_Palubka.UseVisualStyleBackColor = true;
this.Zobraz_Palubka.Click += new System.EventHandler(this.Zobraz_Click);
this.Zobraz_Palubka.MouseEnter += new System.EventHandler(this.Zobraz_Nastaveni_MouseEnter);
this.Zobraz_Palubka.MouseLeave += new System.EventHandler(this.Zobraz_Nastaveni_MouseLeave);
//
// Zobraz_Verzi
//
this.Zobraz_Verzi.Image = global::WindowsFormsApplication1.Properties.Resources.info_mini;
resources.ApplyResources(this.Zobraz_Verzi, "Zobraz_Verzi");
this.Zobraz_Verzi.Name = "Zobraz_Verzi";
this.Zobraz_Verzi.UseVisualStyleBackColor = true;
this.Zobraz_Verzi.Click += new System.EventHandler(this.Zobraz_Click);
this.Zobraz_Verzi.MouseEnter += new System.EventHandler(this.Zobraz_Nastaveni_MouseEnter);
this.Zobraz_Verzi.MouseLeave += new System.EventHandler(this.Zobraz_Nastaveni_MouseLeave);
//
// Zobraz_error
//
this.Zobraz_error.Image = global::WindowsFormsApplication1.Properties.Resources.error1_mini;
resources.ApplyResources(this.Zobraz_error, "Zobraz_error");
this.Zobraz_error.Name = "Zobraz_error";
this.Zobraz_error.UseVisualStyleBackColor = true;
this.Zobraz_error.Click += new System.EventHandler(this.Zobraz_Click);
this.Zobraz_error.MouseEnter += new System.EventHandler(this.Zobraz_Nastaveni_MouseEnter);
this.Zobraz_error.MouseLeave += new System.EventHandler(this.Zobraz_Nastaveni_MouseLeave);
//
// Zobraz_Nastaveni
//
this.Zobraz_Nastaveni.Image = global::WindowsFormsApplication1.Properties.Resources.settings_mini;
resources.ApplyResources(this.Zobraz_Nastaveni, "Zobraz_Nastaveni");
this.Zobraz_Nastaveni.Name = "Zobraz_Nastaveni";
this.Zobraz_Nastaveni.UseVisualStyleBackColor = true;
this.Zobraz_Nastaveni.Click += new System.EventHandler(this.Zobraz_Click);
this.Zobraz_Nastaveni.MouseEnter += new System.EventHandler(this.Zobraz_Nastaveni_MouseEnter);
this.Zobraz_Nastaveni.MouseLeave += new System.EventHandler(this.Zobraz_Nastaveni_MouseLeave);
//
// Zobraz_TestIO
//
this.Zobraz_TestIO.Image = global::WindowsFormsApplication1.Properties.Resources.testIO_mini;
resources.ApplyResources(this.Zobraz_TestIO, "Zobraz_TestIO");
this.Zobraz_TestIO.Name = "Zobraz_TestIO";
this.Zobraz_TestIO.UseVisualStyleBackColor = true;
this.Zobraz_TestIO.Click += new System.EventHandler(this.Zobraz_Click);
this.Zobraz_TestIO.MouseEnter += new System.EventHandler(this.Zobraz_Nastaveni_MouseEnter);
this.Zobraz_TestIO.MouseLeave += new System.EventHandler(this.Zobraz_Nastaveni_MouseLeave);
//
// Zobraz_monitor
//
this.Zobraz_monitor.Image = global::WindowsFormsApplication1.Properties.Resources.line_graph_icon_mini;
resources.ApplyResources(this.Zobraz_monitor, "Zobraz_monitor");
this.Zobraz_monitor.Name = "Zobraz_monitor";
this.Zobraz_monitor.UseVisualStyleBackColor = true;
this.Zobraz_monitor.Click += new System.EventHandler(this.Zobraz_Click);
this.Zobraz_monitor.MouseEnter += new System.EventHandler(this.Zobraz_Nastaveni_MouseEnter);
this.Zobraz_monitor.MouseLeave += new System.EventHandler(this.Zobraz_Nastaveni_MouseLeave);
//
// Form1
//
resources.ApplyResources(this, "$this");
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.Controls.Add(this.btn_ChangeLanguage);
this.Controls.Add(this.pictureBox1);
this.Controls.Add(this.Zobraz_Palubka);
this.Controls.Add(this.Zobraz_Verzi);
this.Controls.Add(this.Zobraz_error);
this.Controls.Add(this.statusStrip1);
this.Controls.Add(this.Zobraz_Nastaveni);
this.Controls.Add(this.Zobraz_TestIO);
this.Controls.Add(this.Zobraz_monitor);
this.Name = "Form1";
this.statusStrip1.ResumeLayout(false);
this.statusStrip1.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).EndInit();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.Button Zobraz_monitor;
private System.Windows.Forms.Button Zobraz_Nastaveni;
private System.Windows.Forms.StatusStrip statusStrip1;
private System.Windows.Forms.ToolStripStatusLabel toolStripStatusLabel1;
private System.Windows.Forms.Button Zobraz_TestIO;
private System.Windows.Forms.Button Zobraz_error;
private System.Windows.Forms.Button Zobraz_Verzi;
private System.Windows.Forms.Button Zobraz_Palubka;
private System.Windows.Forms.PictureBox pictureBox1;
private System.Windows.Forms.Button btn_ChangeLanguage;
}
}
Here is exception detail:
System.InvalidOperationException was unhandled by user code
Message=Cross-thread operation not valid: Control 'Form1' accessed from a thread other than the thread it was created on.
Source=System.Windows.Forms
StackTrace:
at System.Windows.Forms.Control.get_Handle()
at System.Windows.Forms.Form.UpdateMenuHandles(MainMenu menu, Boolean forceRedraw)
at System.Windows.Forms.Form.UpdateMenuHandles()
at System.Windows.Forms.Form.MenuChanged(Int32 change, Menu menu)
at System.Windows.Forms.Form.Dispose(Boolean disposing)
at WindowsFormsApplication1.Form1.Dispose(Boolean disposing) in c:__Projects__\C#\RailJay Diagnostic SW\20130408\Motor\Motor\Form1.Designer.cs:line 23
at System.ComponentModel.Component.Dispose()
at System.Windows.Forms.ApplicationContext.Dispose(Boolean disposing)
at System.Windows.Forms.Application.ThreadContext.DisposeThreadWindows()
InnerException:

It appears that you're calling Dispose from a thread other than the GUI thread. You can't do that.

You need to be more specific - perhaps adding some code to what you are trying to do, where?
[EDIT]
As Jim mentioned, you are referencing a form from a seperate thread;
Here is exception detail:
System.InvalidOperationException was unhandled by user code
Message=Cross-thread operation not valid: Control 'Form1' accessed
from a thread other than the thread it was created on
This means that you are trying to dispose Form1 from a thread that it was not created on.
Have you got sperate threads running in the application, if so, this is the first place to look.
Are you closing the Form1 anywhere within code?

Related

Windows Form Is Shown Blank When Opened

this is how the form shows when opened
http://imgur.com/JbE5I6m
what the form is supposed to look like
http://imgur.com/eTTiWUw
note: when in visual studio i did not start by making a win form app, this is for a private server for a game, its a .sln with 9 projects in it that all compile and work together, i am experimenting and seeing if its possible to do windows form in it, so far ive gotten good results, except for when i do the command (/wedit) to open it, the form shows blank, meanwhile in VS i have indeed added stuff to the form.
FrmWorldEdit.Designer.cs below
namespace WorldEdit
{
partial class FrmWorldEdit
{
/// <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.listTiles = new System.Windows.Forms.ListView();
this.lblSearch = new System.Windows.Forms.Label();
this.tbxSearch = new System.Windows.Forms.TextBox();
this.btnToggle = new System.Windows.Forms.Button();
this.lblSelected = new System.Windows.Forms.Label();
this.SuspendLayout();
//
// listTiles
//
this.listTiles.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.listTiles.Location = new System.Drawing.Point(24, 69);
this.listTiles.Margin = new System.Windows.Forms.Padding(6);
this.listTiles.MultiSelect = false;
this.listTiles.Name = "listTiles";
this.listTiles.Size = new System.Drawing.Size(512, 492);
this.listTiles.TabIndex = 0;
this.listTiles.UseCompatibleStateImageBehavior = false;
this.listTiles.View = System.Windows.Forms.View.List;
this.listTiles.SelectedIndexChanged += new System.EventHandler(this.listTiles_SelectedIndexChanged);
//
// lblSearch
//
this.lblSearch.AutoSize = true;
this.lblSearch.Location = new System.Drawing.Point(19, 28);
this.lblSearch.Name = "lblSearch";
this.lblSearch.Size = new System.Drawing.Size(138, 25);
this.lblSearch.TabIndex = 1;
this.lblSearch.Text = "Search Tiles:";
//
// tbxSearch
//
this.tbxSearch.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.tbxSearch.Location = new System.Drawing.Point(163, 26);
this.tbxSearch.Name = "tbxSearch";
this.tbxSearch.Size = new System.Drawing.Size(373, 31);
this.tbxSearch.TabIndex = 2;
this.tbxSearch.TextChanged += new System.EventHandler(this.tbxSearch_TextChanged);
//
// btnToggle
//
this.btnToggle.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.btnToggle.Location = new System.Drawing.Point(24, 617);
this.btnToggle.Name = "btnToggle";
this.btnToggle.Size = new System.Drawing.Size(512, 45);
this.btnToggle.TabIndex = 3;
this.btnToggle.Text = "Start Painting";
this.btnToggle.UseVisualStyleBackColor = true;
this.btnToggle.Click += new System.EventHandler(this.btnToggle_Click);
//
// lblSelected
//
this.lblSelected.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
this.lblSelected.AutoSize = true;
this.lblSelected.Location = new System.Drawing.Point(20, 577);
this.lblSelected.Name = "lblSelected";
this.lblSelected.Size = new System.Drawing.Size(197, 25);
this.lblSelected.TabIndex = 4;
this.lblSelected.Text = "Selected Tile: none";
//
// FrmWorldEdit
//
this.AutoScaleDimensions = new System.Drawing.SizeF(12F, 25F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(564, 685);
this.Controls.Add(this.lblSelected);
this.Controls.Add(this.btnToggle);
this.Controls.Add(this.tbxSearch);
this.Controls.Add(this.lblSearch);
this.Controls.Add(this.listTiles);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.SizableToolWindow;
this.Margin = new System.Windows.Forms.Padding(6);
this.Name = "FrmWorldEdit";
this.Text = "World Editor Tool";
this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.FrmWorldEdit_FormClosing);
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.ListView listTiles;
private System.Windows.Forms.Label lblSearch;
private System.Windows.Forms.TextBox tbxSearch;
private System.Windows.Forms.Button btnToggle;
private System.Windows.Forms.Label lblSelected;
public FrmWorldEdit()
{
}
}
}
You have provided the content of the 'FrmWorldEdit.Designer.cs' file
Go to your 'FrmWorldEdit' file and make sure you have 'InitializeComponent' method call in the constructor, like so:
public partial class FrmWorldEdit : Form
{
public FrmWorldEdit()
{
InitializeComponent();
}
}
Dont forget to remove your constructor from the 'Designer' file if will decide to implement as I have suggested. Otherwise leave all as it is, but dont forget to add 'InitializeComponent()' method to your constructor in the 'Designer.cs' file
If the startup Form is blank and there is no compiler error.
Check if your Program.cs file is running the right Form, else it will run a form without context and will appear blank.
In this case the Program.cs file should look something like this:
using System;
using System.Windows.Forms;
namespace WorldEdit
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new FrmWorldEdit());
}
}
}

How to pass value from one cs-file (void!) to another?

my little program works very well, reading an xml file with 3 config values, reading a json-http-page and so on.
now there is a little thing i want to do: display the values out of the xml in my settings dialogue. i got this (Program.cs):
using ...
//*****************************************************************************
namespace t2bl
{
abstract class TANSS2BL
{
public static NotifyIcon notico;
//==========================================================================
public static void Main(string[] astrArg)
{
ContextMenu cm;
MenuItem miCurr;
cm = new ContextMenu();
miCurr = new MenuItem();
miCurr.Index = 0;
miCurr.Text = "&Settings";
miCurr.Click += new System.EventHandler(SettingsClick);
cm.MenuItems.Add(miCurr);
miCurr = new MenuItem();
miCurr.Index = 1;
miCurr.Text = "Beenden";
miCurr.Click += new System.EventHandler(ExitClick);
cm.MenuItems.Add(miCurr);
notico = new NotifyIcon();
notico.Icon = new Icon("tanss.ico");
notico.Text = "TANSS Busylight Connector";
notico.Visible = true;
notico.ContextMenu = cm;
notico.DoubleClick += new EventHandler(NotifyIconDoubleClick);
BackgroundWorker bw = new BackgroundWorker();
bw.DoWork += new DoWorkEventHandler(bw_DoWork);
bw.RunWorkerAsync();
Application.Run();
}
public static void bw_DoWork(object sender, DoWorkEventArgs e)
{
XmlDocument doc = new XmlDocument();
doc.Load("C://bll.config.xml");
XmlNode xmlurl = doc.SelectSingleNode("/settings/url");
string url = xmlurl.FirstChild.Value;
XmlNode xmluid = doc.SelectSingleNode("/settings/userID");
string userid_string = xmluid.FirstChild.Value;
XmlNode xmlrefresh = doc.SelectSingleNode("/settings/refresh");
string refresh_string = xmlrefresh.FirstChild.Value;
int userid = Convert.ToInt32(userid_string);
int refresh = 1000 * (Convert.ToInt32(refresh_string));
var controller = new BusylightUcController();
while (true)
{
WebClient client = new WebClient();
var downloadString = client.DownloadString(url + "/module/busylight.php? user=" + userid);
JObject colors = JObject.Parse(downloadString);
//Console.WriteLine(colors["color"]); //Debug
var colorStatus = Convert.ToInt32(colors["color"]);
switch (colorStatus)
{
check the colors and set the light
}
Thread.Sleep(refresh);
GC.Collect();
}
}
//==========================================================================
protected static void ExitClick(Object sender, EventArgs e)
{
notico.Dispose();
Application.Exit();
}
//==========================================================================
protected static void SettingsClick(Object sender, EventArgs e)
{
/// <summary>
/// Der Haupteinstiegspunkt für die Anwendung.
/// </summary>
// This should open the "Settings"-Popup, containing 3 textboxes and a button to save them to xml.
SettingsDiag form1 = new SettingsDiag();
form1.Show();
}
//==========================================================================
protected static void NotifyIconDoubleClick(Object sender, EventArgs e)
{
// ...
}
}
}
and on the other side this (Form1.Designer.cs):
namespace Settingsdialog
{
partial class SettingsDiag
{
/// <summary>
/// Erforderliche Designervariable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Verwendete Ressourcen bereinigen.
/// </summary>
/// <param name="disposing">True, wenn verwaltete Ressourcen gelöscht werden sollen; andernfalls False.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Vom Windows Form-Designer generierter Code
/// <summary>
/// Erforderliche Methode für die Designerunterstützung.
/// Der Inhalt der Methode darf nicht mit dem Code-Editor geändert werden.
/// </summary>
private void InitializeComponent()
{
this.label1 = new System.Windows.Forms.Label();
this.textBox1 = new System.Windows.Forms.TextBox();
this.SuspendLayout();
//
// label1
//
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(50, 28);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(163, 13);
this.label1.TabIndex = 0;
this.label1.Text = "TANSS Busylight connector v1.0";
this.label1.Click += new System.EventHandler(this.label1_Click);
//
// textBox1
//
this.textBox1.Location = new System.Drawing.Point(53, 65);
this.textBox1.Name = "textBox1";
this.textBox1.Size = new System.Drawing.Size(159, 20);
this.textBox1.TabIndex = 1;
this.textBox1.TextChanged += new System.EventHandler(this.textBox1_TextChanged);
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(271, 117);
this.Controls.Add(this.textBox1);
this.Controls.Add(this.label1);
this.Name = "Form1";
this.Text = "TANSS Busylight connector";
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.Label label1;
private System.Windows.Forms.TextBox textBox1;
}
}
How do i pass the values "url", "userid_string", "refresh_string" from the backgroundworker void to the "textbox1.Text=" Output?
Thanks!
There are many ways to accomplish that, one you had in other answers, I can suggest another one:
Because your worker is set to run async, you can for example, report the update progress using the worker event and then in the handler update the textbox
bw.WorkerReportsProgress = true;
bw.ProgressChanged += (o, args) => { textBox1.Text = args.UserState.ToString();}
It's clear that in your bw.DoWorkevent handler you need to report the progress operation passing the UserState as the string value you want to report and update, so inside the event handler you need to call
bw.ReportProgress(0, "you value to report");
hope this helps
If you want to communicate to your form the result of the background worker you could define your form as a member of TANSS2BL (and init it in Main).
Then in bw_DoWork you can call a method on your form with the information you want to display as parameters.
As bw_DoWork is on another thread don't forget to test InvokeRequired and BeginInvoke in your form before setting your textBox value.

ContextMenu Will Not Stay Open C# .Net 4.0 Client Profile WinForms

I have been unable to figure out how to keep a context menu open after handling a click event past the first level. Here is an example of where I have a context menu with a menu of checkable menus. I open up the context menu after handling the click event, but I have to manually return to the inner menu. Is there a way to open up the outer menu programmatically or to prevent the inner menu from closing?
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;
namespace NoCloseContextMenu
{
public partial class Form1 : Form
{
bool[] store_checks = new bool[8];
public Form1()
{
InitializeComponent();
richTextBox1.AppendText("http://");
richTextBox1.LinkClicked += new LinkClickedEventHandler(richTextBox1_LinkClicked);
}
void richTextBox1_LinkClicked(object sender, LinkClickedEventArgs e)
{
MenuItemExtended[] inner_menuitems = new MenuItemExtended[8];
for (int i = 0; i < store_checks.Length; i++)
{
MenuItemExtended inner_menuitem = new MenuItemExtended("Check #" + i.ToString());
inner_menuitem.menuitem_index = i;
inner_menuitem.contextmenu_point = this.PointToClient(Cursor.Position);
inner_menuitem.Checked = store_checks[i];
inner_menuitem.Shortcut = (Shortcut)(131120 + i); //Ctrl+i = 131120+i
inner_menuitem.ShowShortcut = true;
inner_menuitem.Click += new EventHandler(inner_menuitem_Click);
inner_menuitems[i] = inner_menuitem;
}
MenuItem outer_menu = new MenuItem("Outer Menu", inner_menuitems);
ContextMenu context_menu = new ContextMenu(new MenuItem[] { outer_menu });
context_menu.Show(this, this.PointToClient(Cursor.Position));
}
void inner_menuitem_Click(object sender, EventArgs e)
{
MenuItemExtended sender_menu = (MenuItemExtended)sender;
store_checks[sender_menu.menuitem_index] = !store_checks[sender_menu.menuitem_index];
sender_menu.Checked = !sender_menu.Checked;
sender_menu.GetContextMenu().Show(this, sender_menu.contextmenu_point);
}
/// <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.richTextBox1 = new System.Windows.Forms.RichTextBox();
this.SuspendLayout();
//
// richTextBox1
//
this.richTextBox1.Location = new System.Drawing.Point(13, 13);
this.richTextBox1.Name = "richTextBox1";
this.richTextBox1.Size = new System.Drawing.Size(100, 96);
this.richTextBox1.TabIndex = 0;
this.richTextBox1.Text = "";
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(284, 262);
this.Controls.Add(this.richTextBox1);
this.Name = "Form1";
this.Text = "Form1";
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.RichTextBox richTextBox1;
}
public class MenuItemExtended : MenuItem
{
public int menuitem_index;
public Point contextmenu_point;
public MenuItemExtended(string text)
{
this.Text = text;
}
}
}
Also, is there any way to get the "Control + number" shortcuts to work and activate the click event? Thanks in advance for the help!
I did not find any way to prevent the context menu from closing so instead I used ContextMenuStrip and ToolStripMenuItem. This also fixed the problem I had with shortcuts not working before. I handle the Closing event of the menu containing the checkable items and cancel closing if the items were clicked/checked.
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;
namespace NoCloseContextMenu
{
public partial class Form1 : Form
{
bool[] store_checks = new bool[8];
public Form1()
{
InitializeComponent();
richTextBox1.AppendText("http://");
richTextBox1.LinkClicked += new LinkClickedEventHandler(richTextBox1_LinkClicked);
}
void richTextBox1_LinkClicked(object sender, LinkClickedEventArgs e)
{
ToolStripMenuItem[] inner_menuitems = new ToolStripMenuItem[8];
for (int i = 0; i < store_checks.Length; i++)
{
ToolStripMenuItem inner_menuitem = new ToolStripMenuItem("Check #" + i.ToString());
inner_menuitem.Checked = store_checks[i];
inner_menuitem.CheckOnClick = true;
inner_menuitem.ShortcutKeys = Keys.Control | (Keys)(48 + i); //Di = 48 + i
inner_menuitem.ShowShortcutKeys = true;
inner_menuitem.Click += new EventHandler(inner_menuitem_Click);
inner_menuitem.Tag = i.ToString();
inner_menuitems[i] = inner_menuitem;
}
ToolStripMenuItem outer_menu = new ToolStripMenuItem("Outer Menu", null, inner_menuitems);
outer_menu.DropDown.Closing += new ToolStripDropDownClosingEventHandler(DropDown_Closing);
ContextMenuStrip context_menu = new ContextMenuStrip();
context_menu.Items.Add(outer_menu);
context_menu.Show(this, this.PointToClient(Cursor.Position));
}
void DropDown_Closing(object sender, ToolStripDropDownClosingEventArgs e)
{
if (e.CloseReason == ToolStripDropDownCloseReason.ItemClicked)
{
e.Cancel = true;
((ToolStripDropDownMenu)sender).Invalidate();
}
}
void inner_menuitem_Click(object sender, EventArgs e)
{
ToolStripMenuItem sender_menu = (ToolStripMenuItem)sender;
int index = int.Parse(sender_menu.Tag.ToString());
store_checks[index] = !store_checks[index];
}
/// <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.richTextBox1 = new System.Windows.Forms.RichTextBox();
this.SuspendLayout();
//
// richTextBox1
//
this.richTextBox1.Location = new System.Drawing.Point(13, 13);
this.richTextBox1.Name = "richTextBox1";
this.richTextBox1.Size = new System.Drawing.Size(100, 96);
this.richTextBox1.TabIndex = 0;
this.richTextBox1.Text = "";
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(284, 262);
this.Controls.Add(this.richTextBox1);
this.Name = "Form1";
this.Text = "Form1";
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.RichTextBox richTextBox1;
}
}
You can also select certain buttons from within your unclosable submenu to cause the context menu to close normally. For a specific ToolStripMenuItem to close the menu normally, give it a different event method to call:
inner_menuitem.Click += new EventHandler(inner_menuitem_Can_Close);
And use the following code in the method (works regardless of how deep the menus go):
void inner_menuitem_Can_Close(object sender, EventArgs e)
{
ToolStripMenuItem castSender = (ToolStripMenuItem)sender;
object owner = castSender.OwnerItem;
while (owner is ToolStripMenuItem)
{
if (((ToolStripMenuItem)owner).Owner is ContextMenuStrip)
((ContextMenuStrip)((ToolStripMenuItem)owner).Owner).Close();
owner = ((ToolStripMenuItem)owner).OwnerItem;
}
}
I would advise strongly against handling click events on 'parent' context menu items - let the OS handle this for you.

Cannot access a disposed object

Cannot access a disposed object
Anyone know why I would get this error "Cannot access a disposed object" on this line of code
Invoke(new UpdateTimerDelegate(UpdateTimer), new object[] { null });
Hit start over then either accept / reject / or close the form -- seems to happen when closing the form
the error happens when you bring the form up again
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace TimerTester
{
public class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void StartOverBtn_Click(object sender, EventArgs e)
{
ShowForm2();
}
private void Form1_Load(object sender, EventArgs e)
{
ShowForm2();
}
private void ShowForm2()
{
Form2 f2;
f2 = new Form2(10000);
f2.Owner = this;
switch (f2.ShowDialog())
{
case DialogResult.Yes:
break;
case DialogResult.No:
break;
default:
break;
}
}
/// <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.StartOverBtn = new System.Windows.Forms.Button();
this.SuspendLayout();
//
// StartOverBtn
//
this.StartOverBtn.Location = new System.Drawing.Point(33, 33);
this.StartOverBtn.Name = "StartOverBtn";
this.StartOverBtn.Size = new System.Drawing.Size(75, 23);
this.StartOverBtn.TabIndex = 0;
this.StartOverBtn.Text = "Start Over";
this.StartOverBtn.UseVisualStyleBackColor = true;
this.StartOverBtn.Click += new System.EventHandler(this.StartOverBtn_Click);
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(292, 266);
this.Controls.Add(this.StartOverBtn);
this.Name = "Form1";
this.Text = "Form1";
this.Load += new System.EventHandler(this.Form1_Load);
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.Button StartOverBtn;
}
}
form2
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.Diagnostics;
namespace TimerTester
{
public class Form2 : Form
{
public Form2(int timeoutSecondsForAcceptCall)
{
this.timeoutSecondsForAcceptCall = timeoutSecondsForAcceptCall;
InitializeComponent();
tUpdateTimer = new System.Threading.Timer(new System.Threading.TimerCallback(UpdateTimer), null, TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(1));
}
DateTime dtCreate = DateTime.Now;
int timeoutSecondsForAcceptCall = 99999;
System.Threading.Timer tUpdateTimer;
private delegate void UpdateTimerDelegate(object obj);
void UpdateTimer(object obj)
{
if (InvokeRequired == true)
{
Invoke(new UpdateTimerDelegate(UpdateTimer), new object[] { null });
}
else
{
TimeSpan ts = DateTime.Now - dtCreate;
if (ts.TotalSeconds > timeoutSecondsForAcceptCall)
{
DialogResult = DialogResult.Cancel;
return;
}
TimeSpan timeleft = TimeSpan.FromSeconds(timeoutSecondsForAcceptCall) - ts;
label1.Text = FormatTimeSpan(timeleft);
}
}
private string FormatTimeSpan(TimeSpan ts)
{
return ((int)ts.TotalMinutes).ToString().PadLeft(2, '0') + ":" + ((int)ts.Seconds).ToString().PadLeft(2, '0');
}
private void btnAccept_Click(object sender, EventArgs e)
{
DialogResult = DialogResult.Yes;
}
private void btnReject_Click(object sender, EventArgs e)
{
DialogResult = DialogResult.No;
}
/// <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.btnAccept = new System.Windows.Forms.Button();
this.btnReject = new System.Windows.Forms.Button();
this.label1 = new System.Windows.Forms.Label();
this.SuspendLayout();
//
// btnAccept
//
this.btnAccept.Location = new System.Drawing.Point(31, 30);
this.btnAccept.Name = "btnAccept";
this.btnAccept.Size = new System.Drawing.Size(75, 23);
this.btnAccept.TabIndex = 0;
this.btnAccept.Text = "Accept";
this.btnAccept.UseVisualStyleBackColor = true;
this.btnAccept.Click += new System.EventHandler(this.btnAccept_Click);
//
// btnReject
//
this.btnReject.Location = new System.Drawing.Point(140, 29);
this.btnReject.Name = "btnReject";
this.btnReject.Size = new System.Drawing.Size(75, 23);
this.btnReject.TabIndex = 1;
this.btnReject.Text = "Reject";
this.btnReject.UseVisualStyleBackColor = true;
this.btnReject.Click += new System.EventHandler(this.btnReject_Click);
//
// label1
//
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(31, 80);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(35, 13);
this.label1.TabIndex = 2;
this.label1.Text = "label1";
//
// Form2
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(240, 117);
this.Controls.Add(this.label1);
this.Controls.Add(this.btnReject);
this.Controls.Add(this.btnAccept);
this.Name = "Form2";
this.Text = "Form2";
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.Button btnAccept;
private System.Windows.Forms.Button btnReject;
private System.Windows.Forms.Label label1;
}
}
Your form is disposed by the time invoke() message is processed by the message loop. I donot think so there is a way to avoid it. You can put a check e.g
if(!yourForm.IsDisposed)
yourForm.Invoke(...)
But that may not work sometime as the invoke is posted to UI thread and by the time it is process form may already be disposed and you will still get that exception. You have to fix your program in a way to avoid this situation by making sure invoke is not posted on a disposed or disposing form. This is a fatal error and your program will exit after this. I think suppressing it via try{}catch{} will not work as framework already start to unload when catch block is executed.
You can fix the problem in two ways.
1. Just drop a timer component from toolbox i.e. System.Windows.Forms.Timer and use that.
Designer will automatically add it to component collection and dispose it before form is disposed.
2. Manually over OnDispose(bool disposing) in your form and perform
if(disposing)
yourTimer.Dispose()
So now your timer is dispose before your form so no subsequent invoke() will be posted to your form after its disposed.
You see this error, because your System.Threading.Timer is not component of form. Thus it doesn't get disposed when form is closed. I'd recommend you to use System.Windows.Forms.Timer instead. Because this is a component, which you can place on your Form and it will be disposed with other form's components (just drag it from toolbox in designer).
public class Form2 : Form
{
DateTime dtCreate = DateTime.Now;
int timeoutSecondsForAcceptCall = 99999;
public Form2(int timeoutSecondsForAcceptCall)
{
this.timeoutSecondsForAcceptCall = timeoutSecondsForAcceptCall;
InitializeComponent();
timer1.Interval = 1000;
timer1.Start();
}
private void timer1_Tick(object sender, EventArgs e)
{
TimeSpan ts = DateTime.Now - dtCreate;
if (ts.TotalSeconds > timeoutSecondsForAcceptCall)
{
DialogResult = DialogResult.Cancel;
return;
}
TimeSpan timeleft = TimeSpan.FromSeconds(timeoutSecondsForAcceptCall) - ts;
label1.Text = FormatTimeSpan(timeleft);
}
// other code
}
BTW another benefit of using System.Windows.Forms.Timer is that it's Tick event handler executed on UI thread. Thus you don't need to verify if invoke required.
I've had this problem before. There are a couple things you should be doing.
1) When you close your program, you should be removing handlers and/or shutting down timers or other code that will run as the program is exiting. You are still left with the problem of how many timer handlers will still run after shutting down the timer. One possible solution is to set a "stop running" flag after you turn off the Timer. Check the flag in the handler and don't run the code if it is set. The flag could be a bool marked as volatile or a long using Interlocked to avoid concurrency issues, especially if your timer is really short.
2) Wrap a try/catch around your Invoke statement, also put one in the GUI editing code (the part where InvokeRequired == false).

C# issue: How do I manipulate a Textbox on one form from another form?

I'm trying to create my own error window for the project I am working on. When I show my error window I have no way to pass the error message, and user message to the Error window because the "ErrorMessage.Text" cannot be seen in the classes I make.
I went into the form designer generated code and tried to make the TextBox static, but that just breaks things. Can I make a TextBox public / static so I can change it from another form?
How do I make a TextBox Static Public so I can manipulate it across other forms, or is there another method for doing this?
EDIT:
Okay, for more information...
I have my own Form created. It is called "formErrorWindow." I need to display the form that i've pre-designed with the message set from another form. The only way I can do this is if I create a Function in the windows designer area for the form, and I set the variables with "this.errorMsg.text = error." The only way I can see that function is if I set it to static. If I set the function to Static, when I try and put "this.errorMsg.Text = error" I get this error: An object reference is required for the non-static field, method, or property.
Here is what I've attempted:
namespace LCR_ShepherdStaffupdater_1._0
{
partial class formErrorWindow
{
/// <summary>
/// Required designer variable.
/// </summary>
public 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>
// ********* HERE IS THE FUNCTION THAT IVE ADDED BELOW. THIS WOULD WORK BUT.... *********
public static void showError(string errorTitle, string usrMsg, string errorMsg)
{
formErrorWindow errorWindow = new formErrorWindow();
errorMsgItem.Text = errorMsg;
errorTitleItem.Text = "Error! : " + errorTitle;
usrMsgItem.Text = usrMsg;
errorWindow.ShowDialog();
}
// ********* HERE IS THE FUNCTION THAT IVE ADDED ABOVE. THIS WOULD WORK BUT.... *********
// ********* I get an error: "An object reference is required for the non-static field, method, or property." *********
public void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(formErrorWindow));
this.usrMsgItem = new System.Windows.Forms.TextBox();
this.errorTitleItem = new System.Windows.Forms.Label();
this.errorMsgItem = new System.Windows.Forms.TextBox();
this.button1 = new System.Windows.Forms.Button();
this.panel1 = new System.Windows.Forms.Panel();
this.label2 = new System.Windows.Forms.Label();
this.panel1.SuspendLayout();
this.SuspendLayout();
//
// usrMsgItem
//
this.usrMsgItem.Enabled = false;
this.usrMsgItem.Location = new System.Drawing.Point(13, 37);
this.usrMsgItem.Multiline = true;
this.usrMsgItem.Name = "usrMsgItem";
this.usrMsgItem.Size = new System.Drawing.Size(334, 81);
this.usrMsgItem.TabIndex = 0;
this.usrMsgItem.Text = "Undefined";
//
// errorTitleItem
//
this.errorTitleItem.AutoSize = true;
this.errorTitleItem.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.errorTitleItem.ForeColor = System.Drawing.Color.Red;
this.errorTitleItem.Location = new System.Drawing.Point(12, 9);
this.errorTitleItem.Name = "errorTitleItem";
this.errorTitleItem.Size = new System.Drawing.Size(152, 20);
this.errorTitleItem.TabIndex = 1;
this.errorTitleItem.Text = "Error! : Undefined";
//
// errorMsgItem
//
this.errorMsgItem.Enabled = false;
this.errorMsgItem.Location = new System.Drawing.Point(0, 21);
this.errorMsgItem.Multiline = true;
this.errorMsgItem.Name = "errorMsgItem";
this.errorMsgItem.Size = new System.Drawing.Size(329, 101);
this.errorMsgItem.TabIndex = 2;
this.errorMsgItem.Text = "Undefined";
//
// button1
//
this.button1.Location = new System.Drawing.Point(272, 256);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(75, 23);
this.button1.TabIndex = 3;
this.button1.Text = "Continue";
this.button1.UseVisualStyleBackColor = true;
this.button1.Click += new System.EventHandler(this.button1_Click);
//
// panel1
//
this.panel1.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(128)))), ((int)(((byte)(128)))));
this.panel1.Controls.Add(this.label2);
this.panel1.Controls.Add(this.errorMsgItem);
this.panel1.Location = new System.Drawing.Point(12, 124);
this.panel1.Name = "panel1";
this.panel1.Size = new System.Drawing.Size(335, 126);
this.panel1.TabIndex = 4;
//
// label2
//
this.label2.AutoSize = true;
this.label2.Font = new System.Drawing.Font("Microsoft Sans Serif", 10F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label2.Location = new System.Drawing.Point(68, 1);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(189, 17);
this.label2.TabIndex = 3;
this.label2.Text = "Technical Error Message";
//
// formErrorWindow
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(192)))), ((int)(((byte)(192)))));
this.ClientSize = new System.Drawing.Size(359, 290);
this.Controls.Add(this.panel1);
this.Controls.Add(this.button1);
this.Controls.Add(this.errorTitleItem);
this.Controls.Add(this.usrMsgItem);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedToolWindow;
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.MaximizeBox = false;
this.MinimizeBox = false;
this.Name = "formErrorWindow";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent;
this.Text = "Error!";
this.VisibleChanged += new System.EventHandler(this.formErrorWindow_VisibleChanged);
this.panel1.ResumeLayout(false);
this.panel1.PerformLayout();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.Button button1;
private System.Windows.Forms.Panel panel1;
private System.Windows.Forms.Label label2;
public System.Windows.Forms.TextBox usrMsgItem;
public System.Windows.Forms.Label errorTitleItem;
public System.Windows.Forms.TextBox errorMsgItem;
}
}
Look for the function I've added above. How do I get that to compile and do what I want it to do WITHOUT that error I keep getting: An object reference is required for the non-static field, method, or property.
I would just pass the message as a constructor parameter.
MyMessageBox messageBox = new MyMessageBox("My error message");
messageBox.Show();
Yes! have a function made public that can receive this text:
pseudo: public void updateTextBox(string new_text)
and have the function update the textbox from there.
don't mix UI with logic.
public partial class Form1 : Form
{
private static TextBox box;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
// box
box = new TextBox();
box.Location = new System.Drawing.Point(87, 230);
box.Name = "box";
box.Size = new System.Drawing.Size(100, 20);
box.TabIndex = 1;
this.Controls.Add(box);
}
}
You can make the TextBox public first of.
Second make a static form(name of your form) variable and put the form there each time its loaded...
This is not a good solution in my eyes but without knowing more about your design its the best i can come up with...
Allowing public access to an object contained in your class may be a design. How about writing a property in the error window class called ErrorText and inside that property set the ErrorMessage.Text to the passed string? Or am I missing something?
If you really want to go with accessing the controls directly:
public Form2(Form1 form1)
{
InitializeComponent();
Owner = form1;
_form1 = form1;
}
now you can access the controls on form1 this way:
_form1.theForm1ControlName
You could create a method in the Error window's class which could be something like:
public void SetErrorText(string errorText)
{
this.ErrorMessage.Text = errorText; // assuming the TextBox' ID is ErrorMessage.
}
Sounds like you're on the right track by adding the public function you did, but you shouldn't have to make it static. As a general rule, if you have to go into the Designer Generated Code, something isn't right, so let's get out of there - it doesn't mean you can't add code to the form, obviously, but don't do it in that section :)
The error you're getting I believe originates from having a non-instantiated object (i.e. creating the error form like:
formErrorWindow myErrorWindow;
as opposed to instantiating it / creating an instance of it like so:
formErrorWindow myErrorWindow = new formErrorWindow();
You've made the function static, so you can see it from anywhere, however that function can't actually do anything because the form that it runs on doesn't exist yet until you use " = new formErrorWindow();".
So if I'm in a form called "MainForm" and I want to show an error, using the name of the function you provided it would be done like this:
formErrorWindow myErrorWindow = new formErrorWindow();
myErrorWindow.showError("Title", "User Message Here", "Error Message Here");
myErrorWindow.ShowDialog();
The key is to make sure nothing is static and then make sure you're initializing the formErrorWindow with = new formErrorWindow();
Pass the TextBox to the function/method like so
public static void myFunc(TextBox textBox1)
{
textBox1.Text = "do stuff";
{

Categories