I cannot change the image in pictureBox1 from code in C# - c#

First things first: Im pretty new to Programming, and I'm trying to learn the C# Language
My Goal: Having a method that changes the picture in pictureBox1.
Issue: I get the error that tells me that an object reference is required for non-static field.
Here's a snippet of my class where the method should go.
private class Execute
{
private void valueChecker(char value)
{
for (int i = 0; i <= charLenght; i++)
{
if (value != CharArray[i])
{
i++;
}
else if (value == CharArray[i])
{
CorrectLetter(value);
svalue = true;
}
}
if (svalue == true)
{
/* This is where the command is happening.
But I get error message : "An object reference is required for the non-static field, method or property."
*/
pictureBox1.Image = photos[x];
x++;
}
}
}
I have also tried making new classes and methods other places in the code, and call it from the if statement, but I don't get this to work.
I need to change the picture in pictureBox1 if the svalue == true
A little further info on what exactly Im doing:
Im making a hangman game as an exercise, and I want to update the Image in pictureBox1 if the input letter can't be found in the answer.
The pictures are stored in an array I have called photos[].

Your method declaration should be something like this:
public void valueChecker(char value,PictureBox pictureBox1)

var MyImage = new Bitmap(photos[x]);
pictureBox1.Image = (Image) MyImage ;

Your class needs a reference to the PictureBox. You can add a property and set it after creating an instance of the class or even pass it right into the constructor..
private class Execute
{
public PictureBox pBox {get; set;}
public Execute(PictureBox pb)
{
pBox = pb;
}
private void valueChecker(char value) // or maybe public ?!
{
...
...
if (pBox != null) pBox.Image = photos[x];
x++;
}
}
Create the class instance like this:
Execute someName = new Execute(pictureBox1);
Note that there are other ways to solve this; this is just a rather direct and straightforward one. If your class is a kind of service class you may want to go with Tarek's even more direct solution. Note that he not just adds the PictureBox to the parameter list. He also makes the function public.

Related

Cannot access List from a class within an Array

I am a beginner developer, and would very much appreciate if you can help me figure out the problem which is in my code. The code is particularly confusing, mainly because it derives from a framework. The comments should be able to somewhat allow us to understand.
// Create an IBindable List
public static List<IBindable> KyzerBindables = new List<IBindable>();
// Attach elements to a list, for better control over all of them
internal static void AttachBindablesToList(IReadOnlyList<Drawable> children)
{
// For all the children classes located in Drawable list
for (int i = 0; i < children.Count; i++) // children.Count returns 4
{
// For all of the SettingsSubsection which are present in the Drawable array
for (int l = 0; l < (children[i] as SettingsSubsection).Children.Count; l++) // (children[i] as Subsection).Children.Count returns 0.
{
// Get a specific element
var element = (children[i] as SettingsSubsection).Children[l];
// if is a SettingsCheckbox
if (element.GetType() == typeof(SettingsCheckbox))
KyzerBindables.Add((element as SettingsCheckbox).Bindable);
}
}
}
// in another class
public class KyzerSection: SettingsSection
{
public KyzerSection()
{
Children = new Drawable[]
{
new KyzerMiscellaneous(),
};
...AttachElementsToList(Children);
}
}
public class KyzerMiscellaneous: SettingsSubsection
{
[BackgroundDependencyLoader] // Calls load, framework thing.
private void load(OsuConfigManager config)
{
Children = new Drawable[]
{
new SettingsCheckbox
{
LabelText = "Something here",
Bindable = new BindableBool(false),
}
};
}
}
My problem is, the second for loop does not even initiate for the AttachBindablesToList. For whatever particular reason, it isn't recieving a count. I am uncertain of what I am doing wrong.
Edit:
If, in any way, the GitHub repository issue can clear some issues up, please feel free to navigate there and check the commit which contains these changes. https://github.com/Frontear/osuKyzer/issues/3
After reviewing your github repository, I believe the issue is caused at:
private void load(params here)
The above is not being called at the time of AttachBindablesToList. This results in an empty
(children[i] as SettingsSubsection).Children.Count
The best option is to create an empty instantiation method
public KyzerMiscellaneous() { /* create Drawable elements */ }
// then
[BackgroundDependancyLoader]
private void load(params here) { /* doSomething */ }
This will allow access to the children list since it has been initialized before, which therefore allows the second loop to correctly function, and pushes IBindables to your list.

Accessing class from form and vice-versa

After hunting the internet for two days and not finding a solution that I can understand properly I have to ask on here for an answer.
I have a windows forms application that was written in vb.net and works fine. I have decided to rewrite this in c# which I thought wouldn't be too much of a problem but ...
I have two classes in the project :
FormJobs & AppJobs
FormJobs contains methods and functions that modify the forms in some way.
AppJobs contains methods and functions for everything else (Checks,Scanning and so forth).
On my main form (FrmStart) the On_load event uses a function from AppJobs to check that the network is up (public bool CheckNetConnection) and then Checks to make sure that the root save folder exists (public void CheckRoot).
If CheckNetConnection is false or CheckRoot does not exist then a method in the FormJobs class sets some buttons to disabled, some labels to display information as to what has gone wrong and also sets the height of the form.
The above works in VB.net but I keep getting a StackOverflowException or NullReferenceException with the C# code.
I know the reason for the Exceptions is because the two classes and the form all keep calling each other so I know that I need to remove this code but I am not sure how to let each class and the form access each other. It is obviously bad design as I`m just starting to learn C# so any help on this would be much appreciated.
But my main questions are:-How do I get a form to access multiple classes?
Allow the classes to access each other?
Let the classes make changes to a form?
FrmStart Code
AppJobs Appjobs = new AppJobs();
private void FrmStart_Load(object sender, EventArgs e)
{
KeyPreview = true;
if (Appjobs.CheckNetConnection(this) == true)
{
Appjobs.CheckRoot(this);
}
AppJobs Code
public class AppJobs
{
FormJobs Formjobs = new FormJobs();
public string AppRoot = Properties.Settings.Default.DefaultFolder;
public string DefaultDevice = Properties.Settings.Default.DefaultScanner;
public bool NoDirectory = false;
DialogResult MsgBoxQuestion;
public bool CheckNetConnection(Form StartForm)
{
IPHostEntry ServerIP = new IPHostEntry();
bool ConnectedToServer = false;
string CurrentRoot = "MyServer";
if (System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable())
{
try
{
IPHostEntry DNSTest = Dns.GetHostEntry(CurrentRoot);
if (DNSTest.AddressList.Length > 0)
{
ConnectedToServer = true;
}
else
{
ConnectedToServer = false;
}
}
catch (System.Net.Sockets.SocketException ex)
{
ConnectedToServer = false;
}
}
return ConnectedToServer;
}
public void CheckRoot(Form StartForm)
{
if (string.IsNullOrEmpty(AppRoot))
{
Formjobs.SetHeight(StartForm);
return;
}else if(AppRoot == "0")
{
Formjobs.SetHeight(StartForm);
return;
}
else
{
if ((!Directory.Exists(AppRoot)))
{
NoDirectory = true;
MsgBoxQuestion = MessageBox.Show(AppRoot + " is set, but the directory does not exist." + Environment.NewLine
+ Environment.NewLine + "Would you like to create the folder now?", "Root folder missing", MessageBoxButtons.YesNo);
if (MsgBoxQuestion == DialogResult.Yes)
{
Directory.CreateDirectory(AppRoot);
NoDirectory = false;
}
else
{
MessageBox.Show("You will not be able to use this program until you create a root folder.", "No root folder selected",MessageBoxButtons.OK);
}
}
}
}
}
FormJobs Code
public class FormJobs
{
AppJobs Appjobs = new AppJobs();
public void SetHeight(Form StartForm)
{
if (Appjobs.AppRoot == null | Appjobs.AppRoot == "0") {
if (Appjobs.DefaultDevice == null | Appjobs.DefaultDevice == "0") {
if (StartForm.Controls["MenuStrip1"].Visible == true) {
StartForm.Height = 167;
StartForm.Controls["LblNoRoot"].Visible = true;
StartForm.Controls["LblNoRoot"].Location = new Point(0, 24);
StartForm.Controls["LblNoRoot"].Text = "There is no root folder selected. Please select a root folder to continue.";
StartForm.Controls["LblNoDevice"].Visible = true;
StartForm.Controls["LblNoDevice"].Location = new Point(0, 48);
StartForm.Controls["LblNoDevice"].Text = "There is no default device selected. Please select a default device to continue.";
StartForm.Controls["BtnOkTickets"].Enabled = false;
StartForm.Controls["BtnQueryTickets"].Enabled = false;
StartForm.Controls["BtnSearch"].Enabled = false;
}else
{
StartForm.Height = 147;
StartForm.Controls["LblNoRoot"].Visible = true;
StartForm.Controls["LblNoRoot"].Location = new Point(0, 9);
StartForm.Controls["LblNoRoot"].Text = "There is no root folder selected. Please select a root folder to continue.";
StartForm.Controls["LblNoDevice"].Visible = true;
StartForm.Controls["LblNoDevice"].Location = new Point(0, 33);
StartForm.Controls["LblNoDevice"].Text = "There is no default device selected. Please select a default device to continue.";
StartForm.Controls["BtnOkTickets"].Enabled = false;
StartForm.Controls["BtnQueryTickets"].Enabled = false;
StartForm.Controls["BtnSearch"].Enabled = false;
}
}
One of the causes of your problems is that everyone is changing your StartForm. Apart from that this spaghetti makes it difficult to understand, it certainly doesn't help to make your classes reusable and maintainable if your Startform changes.
It seems to me, that AppJobs is meant to decide what the form should look like (for instance it decides that the StartForm should change height), while FormJobs performs the calculations needed to change this height. StartForm apparently is just allowing to let everyone make changes to him.
A better design would be that StartForm would not ask AppJobs to change its size, and to ask the operator whether a folder should be generated. Instead if ought to ask appJobs for advise: "Which height do you think I should have". after that it could ask FormJobs: "Please adjust my height according to this specification"
FormJobs should trust StartForm that it has gathered the correct information about how a StartForm ought to look like. FormJobs should not ask AppJobs for any information: "Hey AppJobs, StartForm asked me to change its appearance to certain specifications, but I'm not certain whether StartForm has done its job correctly. Please tell me if these specifications are correct, and give me some missing information")
The correct division into tasks would be:
AppJobs specifies the format of any StartForm according to its internal state (a.o. AppRoot, and existence of certain folders)
StartForm is the one who displays all items. He decides who to ask for specifications, and what to do with the returned specifications. He is also the only one who communicates with operators
FormJobs is a class that apparently knows all elements from a StartForm. If you will only have one type of StartForm, then Appjobs should be part of the Startform class. If you think there might be several different Startform classes, all with the same elements that ought to be manipulated similarly, shouldn't all these StartForm classes be derived from a FormJobs class?
Anyway, redesign without everyone causing to manipulate StartForm
Apparently there are a limited number of StartForm layouts depending on AppRoot, defaultDevice etc. You seem to be missing some "else" after your if, so this list might not be accurate. Still you will get the idea:
enum StartFormLayouts
{
DefaultDevice0,
AppRoot0,
Other,
}
// class that specifies the layout of any startform
class AppJobs
{
private bool IsAppRoot0
{
get{return Appjobs.AppRoot == null || Appjobs.AppRoot == "0";}
}
private bool IsDefaultDevice0
{
get{return Appjobs.DefaultDevice == null || Appjobs.DefaultDevice == "0";}
}
public StartFormLayoug GetPreferredLayout()
{
if (this.IsAppRoot0)
{
if (this.IsDefaultDevice)
{
return StartFormLayout.DefaultDevice0;
}
else
return StartFormLayout.AppRoot0;
}
else
{
return StartFormLayout.Other;
}
}
public bool ShouldAskDirectoryCreation()
{
return (!this.IsAppRoot0 && !Directory.Exists(AppRoot));
}
}
Note that this class doesn't need StartForm, nor AppJobs. It could work with any class that wants to know if it should ask for DirectoryCreation. Since it also does not speak any language, even a Chinese StartForm could use it. After all, the StartForm is the only one who knows what language it speaks and what to do if a certain layout is requested.
Furthermore, did you notice that I used a double || to use a Boolean OR instead of a bitwise or?
And I use statements like if (a) instead of if(a=true) a C# Boolean is a real Boolean, in contradiction to Booleans in C and C++.
The class of all kinds of forms that should be able to be layout according to the requested layout contains the functions similar to your
It depends a bit of whether you decide to let it be a base class of StartForm or StartForm itself. If you want it to handle every form class that has the required controls, consider of using an interface:
public Interface IStartForm
{
public int Height {get; set;}
public Label LabelNoRoot {get;}
public Label LabelNoDevice {get; }
public Button BtnTickets {get;}
...
This way you can set the size of any form that has these labels and buttons, even if they have different names than those strings you use.
But again: if you ever only want to size StartForm, then this should be a function in StartForm.
public SetHeight(StartFormLayout layout, IStartForm startForm)
{
switch (layout)
{
case StartFormLayout.DefaultDevice0:
if (startForm.MenuStrip.Visible)
{
startForm.Height = ...;
startForm.LabelNoRoot.Location = ...
// etc
}
else
{
...
Noticed that because of this separation of concerns the AppJobs and FormJobs don't have to know each other. AppJobs and FormJobs also don't really have to know what 'StartForm` is, only that it has the labels and buttons etc that it needs to change.
class StartForm : Form, IStartForm
{
public Label LabelNoRoot {get{return this.label1; } }
...
private void FrmStart_Load(object sender, EventArgs e)
{
AppJobs layoutdesigner = new AppJobs(...);
StartFormLayout layoutdesigner = layouter.GetPreferredLayout();
FormJobs layouter = new FormJobjs();
layouter.SetHeight(this)
}
Noticed that my form didn't have a label named "LabelNoRoot", but a Label1 that should function as a LabelNoRoot. Also: because I used types instead of string, You can be certain that I can't handle a label as if it was a button. I can't by accident try to press the label. Something that could easily been done when you were using strings to identify the items you want to layout.
Extending the comments: you just remove the new part in your FormJobs and AppJobs classes.
leaving the code in i.e. in the FormJobs class like : AppJobs appObj;
Then in your main form create at some point a FormJobs obj and an AppJobs obj and set its property.
I.e. in main Form:
AppJobs appObj = new AppJobs();
FormJobs formObj = new FormJobs();
formObj.appObj = appObj;
Tho I must say i dont like that approach you are taking with this...
You should think of another way or at least refactor your code that FormJobs does not need AppJobs methods and vice versa in a way that all calls to FormJobs and AppJobs come from your main form.

Calling object from mainform.cs in other forms?

i want to call anything from mainform (mainform.cs) from GraficDisplay (namespace)
in the other (namespace) : GraphLib , but i can't , would any one tell me why? and how can i resolve this problem? Its been giving me hard time since the start of the project, every time I try these errors appear:
When I call:
mainform.toolstriplabel1.text = "87";
this appears:
The name 'mainform' does not exist in the current context
and if I call this:
GraficDisplay.MainForm.toolstriplabel1.text = "87";
this appears:
The name 'GraficDisplay' does not exist in the current context
I mean I even can't call the GraficDisplay (namespace) in GraphLib (namespace)
also the MainForm is public and partial.
I usually don't follow links here either but CodeProject is a rather reliable source imo, so I had a look.
Edit: I was confused as to what you want. Here is what you seem to actually wnat:
The problem is about referencing a form or part of it from another form or part of it. It is further a problem of dealing with a Library, that really shouldn't be messed up be adding namespaces of an example application or dependencies etc..
So what you want is loose coupling.
Here is a solution that uses references in the library objects and register methods to fill the references. If you don't register anything the library will work normally.
This solution can be changed and expanded but I'll leave it at registering two objects: One is a Control, eg.g a TextBox; the other is a Component e.g. a ToolStripItem. If you want to reference only the ToolStripItem you can omit the references to the Control and the RegisterCtl methods.
In hat case you can and should also substitute 'Component' for 'ToolStripItem' to make things thighter!
First you go to the ultimate consumer of the actions, PlotterGraphSelectCurvesForm. Here you add these two blocks of code:
public partial class PlotterGraphSelectCurvesForm : Form
{
private int selectetGraphIndex = -1;
private PlotterGraphPaneEx gpane = null;
// block one: a Control reference (if you like!):
Control myTextCtl;
public void RegisterCtl(Control ctl) { if (ctl != null) myTextCtl = ctl; }
// block one: a Component reference:
Component myTextComp;
public void RegisterComp(Component comp) { if (comp != null) myTextComp = comp; }
//..
Next you code what you want to happen, maybe like this:
void tb_GraphName_TextChanged(object sender, EventArgs e)
{
if (selectetGraphIndex >= 0 && selectetGraphIndex < gpane.Sources.Count)
{
DataSource src = gpane.Sources[selectetGraphIndex];
String Text = tb_GraphName.Text;
// all controls have a Text:
if (myTextCtl != null) myTextCtl.Text = Text;
// here you need to know the type:
if (myTextComp != null) ((ToolStripItem) myTextComp).Text = Text;
//..
}
In theory all you now need to do is to register the TextBox and/or the ToolStripItem in the Mainform.. However, there is a complication: The PlotterGraphSelectCurvesForm is not called from the Mainform! Instead it is called from a UserObject PlotterGraphPaneEx, which in turn is sitting in the MainForm. In the same sprit of not messing up the library by creating dependencies you simply add the very same references and registration methods to this UO as well:
public partial class PlotterDisplayEx : UserControl
{
#region MEMBERS
Control myTextCtl;
public void RegisterCtl(Control ctl) { if (ctl != null) myTextCtl = ctl; }
Component myTextComp;
public void RegisterComp(Component comp) { if (comp != null) myTextComp = comp; }
//..
Now you can actually register things, both in the MainForm..:
public MainForm()
{
InitializeComponent();
display.RegisterCtl(aDemoTextBox);
display.RegisterComp(toolstriplabel1);
//..
..and in the UO:
private void selectGraphsToolStripMenuItem_Click(object sender, EventArgs e)
{
if (GraphPropertiesForm == null)
{
GraphPropertiesForm = new PlotterGraphSelectCurvesForm();
GraphPropertiesForm.RegisterCtl(myTextCtl);
GraphPropertiesForm.RegisterComp(myTextComp);
}
//..
Now when you open the Properties form and change the LabelText you can see both the text in the Graphs and the text in both the Menu and the TextBox change..

Use of 'this' in an event

I need to retrieve some property of an element that trigger the event in this context:
SoundEffect alarm;
public MainPage()
{
InitializeComponent();
Pad1.MouseLeftButtonUp += new MouseButtonEventHandler(makeasound);
Pad2.MouseLeftButtonUp += new MouseButtonEventHandler(makeasound);
Pad3.MouseLeftButtonUp += new MouseButtonEventHandler(makeasound);
}
Pad1,2 and 3 are the names of some Ellipse I have in my xaml. Now if I try to do this in the code executed by the event ( declared immediately after the sample code above):
private void makeasound(object sender, MouseButtonEventArgs e)
{
string text = this.Name;
textBlock1.Text = text;
}
The Text Block becomes empty, so I guess the Name of the triggering element never gets there.
Now, things get more messy if I'm trying to retrieve a custom property of the "pads" called "Son", declared with the dependency method , which is a string, like this:
private void makeasound(object sender, MouseButtonEventArgs e)
{
string text = this.Son;
textBlock1.Text = text;
}
VS reports error:
'PhoneApplication.MainPage' does not contain a definition for 'Son' and no extension method 'Son' accepting a first argument of type 'PhoneApplication.MainPage' could be found (are you missing a using directive or an assembly reference?)
Where Phoneapplication is the name of the app and the main namespace of the code behind.
As if it weren't simple enough, what I'm tryin to do is this:
The custom property is actually an INT. I know I declared the dependency right since VS let me compile. Each Pad has this custom property storing an int, and I need to retrieve it to access an array element. The function triggered is this:
private void makeasound(object sender, MouseButtonEventArgs e)
{
int x = this.Son;
var sons = new[] { "sons/firstsound.wav", "sons/secondsound.wav", "sons/thirdsound.wav" };
string target = sons[x];
StreamResourceInfo info = Application.GetResourceStream(
new Uri(target, UriKind.Relative));
alarm = SoundEffect.FromStream(info.Stream);
Microsoft.Xna.Framework.FrameworkDispatcher.Update();
alarm.Play();
}
So, I declare an array storing URI's for sounds that I'd like to play("son" means sound in french, I'm from Belgium). I then use the INT associated with the triggering element to access the URI of a sound, then I play this sound.
The reason I do this is because I'd like to let the user change the INT value for each pad and therefore choose what sound each pad plays. The fact that I seem to have no choice but to declare this array each time the function is called (otherwise it's not in context) is not very elegant but I guess I can live with that ( array will have 50-60 elements in it)
So, for those who read this far, my problem is to use a property of the triggering event, which seems to be harder when it's a custom property. I put the rest of the logic in case someone had advices.
I thank anyone who read this message and who could maybe help me sorting this out. I read online documentation and I have two good c# books, but I havent found a solution for me.
Have a nice day.
EDIT: Some others are willing to help so here is the declaration of the dependency property(Sorry Daniel, hadn't seen you commented my original post)
namespace MyNamespace
{
public static class MyClass
{
public static readonly DependencyProperty SonProperty = DependencyProperty.RegisterAttached("Son",
typeof(string), typeof(MyClass), new PropertyMetadata(null));
public static string GetSon(UIElement element)
{
if (element == null)
throw new ArgumentNullException("element");
return (string)element.GetValue(SonProperty);
}
public static void SetSon(UIElement element, string value)
{
if (element == null)
throw new ArgumentNullException("element");
element.SetValue(SonProperty, value);
}
}
Mynamespace is nested inside the main namespace.
this refers to the current instance of MainPage. Not to the pad that was clicked. That's the sender:
var pad = (Pad)sender;
var text = pad.Name;
textBlock1.Text = text;
Son is an attached property, not a normal one. You can get its value like this:
var pad = (Pad)sender;
var son = MyClass.GetSon(pad);
Please note that you have declared it as a string. Seeing how you want to use it, it seems to make more sense to declare it as an int.
this refers to the instance of the type in which the method is defined in, in this case, MainPage. If you want to get the instance of the type that triggered the event, that's what's in the sender parameter:
private void makeasound(object sender, MouseButtonEventArgs e)
{
textBlock1.Text = ((Pad)sender).Name;
}

C# - using ColorDialog across forms

I have a windows form application. On the main form a user will enter a number of item, etc and then click a button which will open a new form (either a small form or a large form depending on a checkbox). Now on my main application I have a file menu - under which is settings - change background colour. This opens the colordialog. If a user does not pick anything the background colours will stay default. However if they change it on the main entry form i change the background of a few textboxes - code below.
private void warning1ToolStripMenuItem_Click(object sender, EventArgs e)
{
colorDialog1.ShowDialog();
Warn1Color = colorDialog1.Color.ToString();
if (Warn1Color != null)
{
tbWarn1Hrs.BackColor = colorDialog1.Color;
tbWarn1Mins.BackColor = colorDialog1.Color;
tbWarn1Secs.BackColor = colorDialog1.Color;
tbWarn1Msg.BackColor = colorDialog1.Color;
}
}
Now my problem is how to I get this to then change the background in the other form that opens. I was hoping I could pass the string across in the new form constructor as i do with a number of other values.
i.e - here is my code in the new form....(note - string Warn1Color was passed across in constructor and then made = to the string _Warn1Color. If it is null then background will be default yellow but it cant convert type string to system.drawing.color. Does anyone see an easy solution to this or what I could do to get this working easily.
if (_Warn1Color == null)
{
this.BackColor = System.Drawing.Color.Yellow;
}
else
this.BackColor = _Warn1Color;
Pass the Color on via the Constructor not a string. If this is not possibly for whatever reason, you could create a ColorConfigClass that holds the required Color and you can set it when used.
You should create a static class to store your configuration data such as this colour style. You can then set this value once you have prompted the user for the change and you can also call the Color value from any other form when you need to use it.
Your static class should look something like this...
public static class StyleSettings{
private static Color _warn1Color = Color.FromArgb(255, 0, 0);//default colour
public static Color Warn1Color {
get { return _warn1Color; }
set { _warn1Color = value; }
}
}
Then you can use this in your example method like...
private void warning1ToolStripMenuItem_Click(object sender, EventArgs e)
{
if (colorDialog1.ShowDialog() == DialogResult.OK)
{
StyleSettings.Warn1Color = colorDialog1.Color;
tbWarn1Hrs.BackColor = StyleSettings.Warn1Color;
tbWarn1Mins.BackColor = StyleSettings.Warn1Color;
tbWarn1Secs.BackColor = StyleSettings.Warn1Color;
tbWarn1Msg.BackColor = StyleSettings.Warn1Color;
}
}
I assume you used a string because you wanted to be able to pass null, and System.Drawing.Color being a struct can not be null.
In which case either use Nullable ( http://msdn.microsoft.com/en-us/library/b3h38hb0%28v=vs.80%29.aspx ) which can be null or you can consider some other value as "default", say alpha=0.
To pass a value in your constructor simply go to the code file for the form (the one where you code the stuff for the events) and find the constructor function (has the same name as the form) e.g.:
namespace MyApp
{
public partial class MyForm : Form
{
public MyForm()
{
InitializeComponent();
}
...
And add the parameters to it:
namespace MyApp
{
public partial class MyForm : Form
{
public MyForm(System.drawing.color background)
{
InitializeComponent();
...do whatever you want with background...
}
...
Of course you also need to edit the places you create this form, e.g. change
form = new MyForm();
form.Show();
to
form = new MyForm(backgroundColour);
form.Show();

Categories

Resources