Popup about array rank size preventing me from saving - c#

I have a specific user control with several properties, including one which is of another class. That class contains a public int[,] this[int x, int y] (I don't remember the exact term for that) as well as a public int[,] property and a private int[,] field. I then have a form containing that control. Whenever I attempt to edit the form and then save, it denies me from saving with the following popup appearing 3 to 6 times in a row:
Note that I don't need the information saved into these arrays in the designer; the value is set to a default each time anyways within the ExampleControl. I don't even have the ability to modify or see these arrays.
Here's all of the code needed to reproduce:
Create a new form application, and then delete the Form1.cs file generated.
Program.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
namespace ArrayRankIssue
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main() {
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new ExampleForm());
}
}
}
ExampleClass.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ArrayRankIssue
{
public class ExampleClass
{
private int[,] data = new int[2, 2];
public int[,] Data {
get {
return data;
}
set {
if (value.GetLength(0) != data.GetLength(0) || value.GetLength(1) != data.GetLength(1)) {
throw new ArgumentException("Argument must match size of array exactly.");
}
data = value;
}
}
public int[,] this[int x, int y] {
get {
return data;
}
set {
if (value.GetLength(0) != data.GetLength(0) || value.GetLength(1) != data.GetLength(1)) {
throw new ArgumentException("Argument must match size of array exactly.");
}
data = value;
}
}
}
}
ExampleControl.cs:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace ArrayRankIssue
{
public partial class ExampleControl : UserControl
{
internal ExampleClass example = new ExampleClass();
public ExampleClass Example {
get {
return example;
}
set {
example = value;
}
}
public ExampleControl() {
InitializeComponent();
}
}
}
ExampleControl.Designer.cs:
namespace ArrayRankIssue
{
partial class ExampleControl
{
/// <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 Component 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() {
components = new System.ComponentModel.Container();
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
}
#endregion
}
}
ExampleForm.cs:
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 ArrayRankIssue
{
public partial class ExampleForm : Form
{
public ExampleForm() {
InitializeComponent();
}
}
}
ExampleForm.Designer.cs:
namespace ArrayRankIssue
{
partial class ExampleForm
{
/// <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() {
ArrayRankIssue.ExampleClass exampleClass8 = new ArrayRankIssue.ExampleClass();
this.exampleControl1 = new ArrayRankIssue.ExampleControl();
this.SuspendLayout();
//
// exampleControl1
//
this.exampleControl1.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.exampleControl1.Example = exampleClass8;
this.exampleControl1.Location = new System.Drawing.Point(12, 12);
this.exampleControl1.Name = "exampleControl1";
this.exampleControl1.Size = new System.Drawing.Size(150, 150);
this.exampleControl1.TabIndex = 0;
//
// ExampleForm
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(292, 273);
this.Controls.Add(this.exampleControl1);
this.Name = "ExampleForm";
this.Text = "Form1";
this.ResumeLayout(false);
}
#endregion
private ExampleControl exampleControl1;
}
}
After creating all of these files, select Build-->Rebuild solution [note 1]. Then, double-click ExampleForm.cs, click on the outlined control, and then press left and then right on your keyboard [note 2]. Then, press Control and S, and you will be greeted with the same error message many times.
What I'm looking for is a way to keep this message from popping up (and hopefully to solve the reason why it is popping up, not just suppress it). I have found a simple workaround, which is to close the form designer window and then save, but that seems impractical. Once it is successfully saved, the form appears properly, so there also doesn't seem to be any other effects.
The one other mention of this error message was in this question, but that offered no useful solution.
Note 1: This option is only available in "Expert mode" - if you don't have it, go to Tools-->Settings-->Expert Settings)
Note 2: This is needed so that the file appears as modified by Visual Studio. If it isn't done, you can't force a second save.

Moving these lines worked for me:
From ExampleForm.Designer.cs:
ArrayRankIssue.ExampleClass exampleClass2 = new ArrayRankIssue.ExampleClass();
this.exampleControl1.Example = exampleClass2;
To ExampleForm.cs:
public partial class ExampleForm : Form
{
public ExampleForm()
{
InitializeComponent();
ArrayRankIssue.ExampleClass exampleClass2 = new ArrayRankIssue.ExampleClass();
this.exampleControl1.Example = exampleClass2;
}
}
Solution 2
If you're properties are already setup and you don't need to change them mark them with:
[ReadOnly(true)]
[Browsable(false)]
In your example add those attributes to Data and this in ExampleClass.cs.
You'll have to change your code, remove any existing controls from your form, compile then re-add

Related

WinForms - How to loop through tabcontrol's tabpages that have custom pages and system.windows.forms tabpages?

I've made some pre-built tab pages that inherit from the systems.windows.forms.tabpage class to help cluster relevant elements and improve flexibility and readability. The problem is that in doing this, I made it so that I can't loop through the tabcontrol's pages when I want that specific tabpage layout by using foreach. I get the following error:
"System.InvalidCastException: 'Unable to cast object of type 'System.Windows.Forms.TabPage' to type 'GraphicProject.ProductionTabPage'.'"
What are some of the options I have to get fix this issue that allow me to continue making these pre-built components? Code below.
Form Designer Code
using System;
using System.Drawing;
using System.Threading;
using System.Windows.Forms;
namespace FlowCal_Time_Analyzer
{
partial class Form1
{
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()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(Form1));
this.tabControl1 = new System.Windows.Forms.TabControl();
this.tabControl1.SuspendLayout();
this.tabControl1.Controls.Add(new System.Windows.Forms.TabPage());
this.tabControl1.Controls.Add(new ProductionTabPage());
foreach (ProductionTabPage PTG in tabControl1.TabPages) //failure happens here on first element
{
PTG.Initialize();
}
this.tabControl1.ResumeLayout(false);
}
}
}
TabPage Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using LiveCharts;
using LiveCharts.Wpf;
using System.Threading;
namespace FlowCal_Time_Analyzer
{
class ProductionTabPage : TabPage
{
private Button GetProductionDataButton = new Button();
private DateTimePicker ProductionDatePicker = new DateTimePicker();
private DateTime m_selectedDate;
public void Initialize()
{
this.ProductionDatePicker.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.ProductionDatePicker.Format = System.Windows.Forms.DateTimePickerFormat.Short;
this.ProductionDatePicker.Location = new System.Drawing.Point(83,4);
this.ProductionDatePicker.Margin = new System.Windows.Forms.Padding(2);
this.ProductionDatePicker.Name = "GraphDatePicker";
this.ProductionDatePicker.Size = new System.Drawing.Size(96, 20);
this.ProductionDatePicker.TabIndex = 1;
this.ProductionDatePicker.ValueChanged += new System.EventHandler(this.dateTimePicker1_ValueChanged);
this.ProductionDatePicker.MouseUp += new System.Windows.Forms.MouseEventHandler(this.GraphDatePicker_MouseUp);
this.GetProductionDataButton.Location = new System.Drawing.Point(4, 4);
this.GetProductionDataButton.Name = "GetProductionDataButton";
this.GetProductionDataButton.Size = new System.Drawing.Size(75, 23);
this.GetProductionDataButton.TabIndex = 0;
this.GetProductionDataButton.Text = "Get Device Count";
this.GetProductionDataButton.UseVisualStyleBackColor = true;
this.GetProductionDataButton.Click += new System.EventHandler(this.GetProductionDataButton_Click);
this.Controls.Add(ProductionDatePicker);
this.Controls.Add(GetProductionDataButton);
}
private void dateTimePicker1_ValueChanged(object sender, EventArgs e)
{
m_selectedDate = ProductionDatePicker.Value.Date;
}
private void GraphDatePicker_MouseUp(object sender, MouseEventArgs e)
{
ProductionDatePicker.Select();
SendKeys.Send("%{DOWN}");
}
private void GetProductionDataButton_Click(object sender, EventArgs e)
{
DBProductionModule dB_Production = new DBProductionModule();
dB_Production.GetProductionData(m_selectedDate);
}
}
}

Form Components went missing Visual Studio c#

Was making a very simple text editor for practice, got the form all setup but then when I started to add the code all of the form components suddenly disappeared from the form but the still exist somewhere. Not really sure what is going on.
I have posted the code I have written so far. Alot of the features are likely going to be removed as I want this text editor to follow a free writing style. I really only plan to use the "File" drop down selection (New, Open, Save and Exit).
Thank in advance for any assistance.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Text;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace CustomTextEditor2 {
public partial class TextEditor : Form {
public TextEditor() {
InitializeComponent();
}
#region Editor and General
#endregion
#region MainMenu
#endregion
#region Toolbar
#endregion
#region contextmenu
#endregion
#region Methods
#region file
void New()
{
Document.Clear();
}
void Open()
{
if (openWork.ShowDialog() == DialogResult.OK)
{
Document.LoadFile(openWork.FileName, RichTextBoxStreamType.PlainText);
}
}
void Save()
{
if (saveWork.ShowDialog() == DialogResult.OK)
{
try
{
Document.SaveFile(saveWork.FileName, RichTextBoxStreamType.PlainText);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
void Exit()
{
Application.Exit();
}
#endregion
#region edit
#endregion
#region tools
void customise()
{
ColorDialog myDialog = new ColorDialog();
if (myDialog.ShowDialog() == DialogResult.OK)
{
mainMenu.BackColor = myDialog.Color;
Status.BackColor = myDialog.Color;
Tools.BackColor = myDialog.Color;
}
}
#endregion
#endregion
}
}
Okay here is the code from TextEditor.Designer.cs:
namespace CustomTextEditor2
{
partial class TextEditor
{
/// <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.SuspendLayout();
//
// TextEditor
//
this.ClientSize = new System.Drawing.Size(732, 434);
this.MinimumSize = new System.Drawing.Size(748, 473);
this.Name = "TextEditor";
/this.Load += new System.EventHandler(this.TextEditor_Load_1);
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.MenuStrip mainMenu;
private System.Windows.Forms.RichTextBox Document;
private System.Windows.Forms.StatusStrip Status;
private System.Windows.Forms.ToolStripMenuItem mM_File;
private System.Windows.Forms.ToolStripMenuItem file_New;
private System.Windows.Forms.ToolStripMenuItem file_Open;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator;
private System.Windows.Forms.ToolStripMenuItem file_Save;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator1;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator2;
private System.Windows.Forms.ToolStripMenuItem file_Exit;
private System.Windows.Forms.ToolStripStatusLabel charCount;
private System.Windows.Forms.ToolStripStatusLabel toolStripStatusLabel1;
private System.Windows.Forms.ToolStripStatusLabel zoom;
private System.Windows.Forms.OpenFileDialog openWork;
private System.Windows.Forms.SaveFileDialog saveWork;
private System.Windows.Forms.Timer timer;
}
}

Can't make MSDNs simple example c# service

I've attempt to follow MSDN simple make a service instructions
Walkthrough: Creating a Windows Service Application in the Component Designer
https://msdn.microsoft.com/en-us/library/zt39148a(v=vs.110).aspx?cs-save-lang=1&cs-lang=csharp#code-snippet-1
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
namespace WindowsService1
{
public partial class Service1 : ServiceBase
{
private System.ComponentModel.IContainer components;
private System.Diagnostics.EventLog eventLog1;
public Service1()
{
InitializeComponent();
eventLog1 = new System.Diagnostics.EventLog();
if (!System.Diagnostics.EventLog.SourceExists("MySource"))
{
System.Diagnostics.EventLog.CreateEventSource("MySource", "MyNewLog");
}
eventLog1.Source = "MySource";
eventLog1.Log = "MyNewLog";
}
protected override void OnStart(string[] args)
{
eventLog1.WriteEntry("In OnStart");
}
protected override void OnStop()
{
}
}
}
I seem to fail at the 2nd hurdle, "Adding Features to the Service"
When I compile I get Ambiguity between 'WindowsService1.Service1.eventLog1' and 'WindowsService1.Service1.Service1.eventLog1' and The type 'WindowsService1.Service1' already contains a defintion for 'components'
Thanks for the comments people got me looking in the right place, seems that you don't need to do step4 it is done automatically when you add the eventlog in the design view.
Service1.designer.cs looks like this
namespace WindowsService4
{
partial class Service1
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components;
/// <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 Component 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.eventLog1 = new System.Diagnostics.EventLog();
((System.ComponentModel.ISupportInitialize)(this.eventLog1)).BeginInit();
//
// Service1
//
this.ServiceName = "Service1";
((System.ComponentModel.ISupportInitialize)(this.eventLog1)).EndInit();
}
#endregion
private System.Diagnostics.EventLog eventLog1;
}
}

'Object' does not contain a method for 'dispose' C# compiler error

I'm trying to compile and test my code for my homework assignment, and Visual Studio is throwing up errors saying that the 'object' does not contain a method for 'dispose', and I can't figure out why it won't let me compile my code. The assignment reads:
Rectangle Class: Create a class Rectangle. The class has attributes length and width, each of which default to 1. It has read-only properties that calculate the Perimeter and the Area of the rectangle. It has properties for both length and width. The set accessors should verify that length and width are each floating point numbers greater than 0.0 and less than 20.0. Write an app to test class Rectangle.
Here is the code for the rectangle class:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WindowsFormsApplication16
{
class Rectangle
{
private float length = 1;
private float width = 1;
public Rectangle(float length, float width)
{
Length = length;
Width = width;
}
public float Length
{
get
{
return this.length;
}
set
{
if (value <= 0.0f || value > 20.0f)
{
this.length = 1.0f;
}
else
{
this.length = value;
}
}
}
public float Width
{
get
{
return this.width;
}
set
{
if (value <= 0.0f || value > 20.0f)
{
this.width = 1.0f;
}
else
{
this.width = value;
}
}
}
public float Perimeter
{
get
{
return(Length + Width)*2;
}
}
public float Area
{
get
{
return(Length*Width);
}
}
public override string ToString()
{
return string.Format("Perimeter is {0:F2} and Area is {1:F2}", Perimeter, Area);
}
}
}
Here is the code for the app to test:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WindowsFormsApplication16
{
class TestProgram
{
static void main(string[] args)
{
Rectangle rect = new Rectangle(19.5f, 15.9f);
Console.WriteLine(rect);
Console.ReadLine();
}
}
}
When I go to compile it, it throws up two errors:
Error 1 'WindowsFormsApplication16.Form2.Dispose(bool)': no suitable method found to
override c:\users\kyle\documents\visual studio 2012\Projects\WindowsFormsApplication16\
WindowsFormsApplication16\Form2.Designer.cs 14 33 WindowsFormsApplication16
Error 2 'object' does not contain a definition for 'Dispose'
c:\users\kyle\documents\visual studio 2012\Projects\WindowsFormsApplication16\
WindowsFormsApplication16\Form2.Designer.cs 20 18
WindowsFormsApplication16
Here is the code it says the error is located at:
namespace WindowsFormsApplication16
{
partial class Form2
{
/// <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>
#endregion
}
}
Can anyone possibly shed some light on this and give me an idea as to why it won't compile?
That Form2 has to derive from a class...I think it should be "Form". Create a new project / add a new Form and see the class from which it derives. You probably deleted it by accident.
I encountered this error recently when I was importing a form into a project.
The error came after importing the form, I changed the namespace on the main.cs code file, but I did not change the namespace for the corresponding designer.cs file. When I matched the namespaces, the error messages went away.

Matching MEF imports to exports

In the code below I am attempting to use MEF to match an import to a matching export. The TestMEFClass has an import and an export which share a matching contract name. The export should increment a counter every time it's called.
When I printed the export to the console, it did not increment the counter. Could someone point out my mistake?
Thank you very much,
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
using System.ComponentModel.Composition;
using System.ComponentModel.Composition.Hosting;
using System.Reflection;
namespace MEFConsoleTest {
public class TestMEFClass {
/// <summary>
/// This counter should increment everytime the getter in the ExportString property gets called.
/// </summary>
private int counter = 0;
[Export("Contract_Name")]
public string ExportString {
get {
return "ExportString has been called " + counter++.ToString();
}
}
[Import("Contract_Name")]
public string ImportString { get; set; }
/// <summary>
/// Default Constructor.
/// Make a catalog from this assembly, add it to the container and compose the parts.
/// </summary>
public TestMEFClass() {
AggregateCatalog catalog = new AggregateCatalog();
catalog.Catalogs.Add(new AssemblyCatalog(Assembly.GetExecutingAssembly()));
var container = new CompositionContainer(catalog);
container.ComposeParts(this);
}
}
class Program {
static void Main(string[] args) {
TestMEFClass testClass = new TestMEFClass();
Console.WriteLine(testClass.ImportString);
Console.WriteLine(testClass.ImportString);
Console.ReadLine();
}
}
For reasons I cannot explain at this moment I wasn't able to get MEF and properties imports/exports to work on a mutable property. However, using functions did the trick. I hope this code helps someone else.
Thanks,
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
using System.ComponentModel.Composition;
using System.ComponentModel.Composition.Hosting;
using System.Reflection;
namespace MEFConsoleTest {
public class TestMEFClass {
/// <summary>
/// This counter should increment everytime the getter in the ExportString property gets called.
/// </summary>
private int counter = 0;
[Export("Contract_Name")]
string ExportMethod() {
return ExportString;
}
public string ExportString {
get {
return "ExportString has been called " + counter++.ToString();
}
}
[Import("Contract_Name")]
Func<string> ImportMethod;
public string ImportString { get { return ImportMethod(); } }
/// <summary>
/// Default Constructor.
/// Make a catalog from this assembly, add it to the container and compose the parts.
/// </summary>
public TestMEFClass() {
AggregateCatalog catalog = new AggregateCatalog();
catalog.Catalogs.Add(new AssemblyCatalog(Assembly.GetExecutingAssembly()));
var container = new CompositionContainer(catalog);
container.ComposeParts(this);
}
}
class Program {
static void Main(string[] args) {
TestMEFClass testClass = new TestMEFClass();
for (int x = 0; x < 10; x++) {
Console.WriteLine(testClass.ImportString);
}
Console.ReadLine();
}
}
}

Categories