Control does not exist in current context - c#

I'm sure this is something simple that I am just overlooking, but I can't figure it out. I am new to C# and I'm trying to create a calculator application. I have created my form with all of my buttons/textbox on it. Now I'm creating a new class to handle all of my methods and whatnot. My problem is that whenever I'm trying to reference controls on the form in the second class, I get the "does not exist in the current context" error. How can I solve this?
An example:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApplication2
{
public class Calculator
{
decimal currentValue = Decimal.Parse(displayValue.text);
}
}
displayValue receives the error. Thank you for any help.

The Controls can be called only from the .cs file which is linked with the form controls.
What you can do is create a parameterized constructor of your Calculator class like this:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApplication2
{
public class Calculator
{
public Calculator(string displayValue)
{
decimal currentValue = Decimal.Parse(displayValue);
}
}
}
Now, you can call this class in the form .cs where you have buttons and textboxes like this:
Calculator calculate = new Calculator(displayValue.Text);

When you create a new Windows Form Application, there's a designer (which you can interact with to add your buttons and textboxes) and the code-behind (a .cs file).
This .cs file is a partial class, meaning it is also defined by the form you are interacting with. (you can see the nitty gritty details in your .Designer.cs file)
Once you name your buttons and textboxes, you can refer to their names in the code in your partial class!
And when you compile this, your button text will change to "Hello World!"
Hope this helps.

You will find this control in partial class of the form. You can take values from it and do your operation
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
string s = textBox1.Text;
}
}

Related

C# .NET running code from an external file

I'm pretty new with C#, and I was wondering if it would be possible to move parts of code (from my main Form) to an external .cs file (still in the same solution), with the same level of access to variables and functions from my form1.cs file, as my original form1.cs file.
I'm working with the latest version of the .NET-framework and I have no other references to (external) code.
Here is a simple example of what I'm looking for:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Code1
{
public partial class Form3 : Form
{
public Form3()
{
InitializeComponent();
}
// variables
text1 = "Hello"
public void ExternalCode()
{
this.BackgroundImage = null;
Btn1.Text = "Click me";
Lbl1.Text = text1;
}
private void Btn1_Click(object sender, EventArgs e)
{
ExternalCode();
}
}
}
This form only has a button named "Btn1" and a label named "Lbl1" in it.
I would like the code inside the method SeparateCode to be in a separate file, but still with the ability to access the variables and controls from Form3, and for Form3 to still be able to execute the method in the external file (ExternalCode).
I thought of making this file a daughter of the Form3.cs, but as I said, I'm still pretty new at this so I don't really know how to.
Yes, that is possible, because the class has been declared as partial, here:
v-----v
public partial class Form3 : Form
This keyword means that the file you grabbed that code from can be one of many, all declaring their own partial content for this class.
So what you can do is add yet another file to your project, and make sure it contributes to this class. To do that you must:
Declare the class inside the file as belonging to the same namespace as the original
Declare the class inside to be the same class as the original
Note that you don't have to mention inheritance, such as the part with : Form from your original, as this will still be understood from your original file.
So, if you add a file with this content:
namespace Code1 // <-- this has to be the same
{
public partial class Form3 // <-- as does this
{
public void ExternalCode()
{
this.BackgroundImage = null;
Btn1.Text = "Click me";
Lbl1.Text = text1;
}
}
}
then you can remove ExternalCode from your original file, and it should still work just fine.
The compiler will treat all of these files as building up the same, one, class, Form3.

How to make a form visible or invisible in C# [duplicate]

This question already has answers here:
Why is there a default instance of every form in VB.Net but not in C#?
(2 answers)
c# Show Windows Form
(4 answers)
Closed 9 years ago.
So I have a Windows Form named Settings.CS
It has nothing.. the code is only this much
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace SteamBot
{
public partial class Settings : Form
{
public Settings()
{
InitializeComponent();
}
}
}
Then I have another CLASS named Bot.CS. What I want to do is, after a specific function, I want the settings form to become visible. In VB it was just Settings.Visible = true
How do I do this in C#? Please help me.
Solution 1: if you want to display the Settings Form first time, you need to create an instance variable of that Form and call ShowDialog() method to display it.
Try This:
void SpecificFunction()
{
//--at the end of MyFunction call settings form
Settings frmSettings=new Settings();
frmSettings.ShowDialog();
}
Solution 2: if you want to display the Settings Form which was hidden before , you need to to follow the below steps make it Visible.
Step 1: identify/obtain the Settings Form by using Application.OpenForms[] Collection.
Step 2: create a new instance variable of a Form by casting the obtained Settings Form in above step.
Step 3: Call the Show() Method on the created instance variable to Show/Display the Settings form.
Try This:
void SpecificFunction()
{
//--at the end of MyFunction call settings form
Form frmSettings = (Settings) Application.OpenForms["Settings"];
frmSettings.Show();
}
Lets assume that Specific Function is a button click
private void Button1_Click(Object sender, EventArgs e )
{
Form1 myForm = new Form1();
myForm.Show();
}
Replace Form1 with the form name of your settings form !
I just created this new Form which is shown when the button is clicked:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Form f2 = new Form();
f2.Visible = true;
//f2.Show(); also works
}
}
}
You can also use 'this' if you want to manipulate the instance
give it a try

Most efficient way to call/access windows form controls in a class

I added a CSharp Class to a form project. Now I want to access the form controls from the Class.
I am using this piece of code with the implicit var as follows:
var form = frmClasses.ActiveForm as frmClasses;
Using this code, I set the form Modifiers to public, place the code is a method/function and I am able to access the form controls in the class.
The problem is each time I need to call a form control I have to use the var and the entire line of code above. Is there a simpler way that is less redundant?
Example: Each method/function in a the class will need to call the form controls thus referencing the form controls using Var.
Take a look at the code below, you will noticed that I am using Var to call each form control.
Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
namespace Classes
{
class ClsProperties
{
//VALIDATE TEXTBOX
public static void validateTextBox()
{
var form = frmClasses.ActiveForm as frmClasses;
if (form.txtMyTextBox.Text.Trim().Length == 0)
{
form.txtMyTextBox.BackColor = Color.Aquamarine;
}
}
//VALIDATE RADIO BUTTON
public static void validateRadio()
{
var form = frmClasses.ActiveForm as frmClasses;
if (form.radBtnColor.Checked == false)
{
form.lblShowError.ForeColor = Color.Aquamarine;
}
}
}
}
Form Code:
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 Classes
{
public partial class frmClasses : Form
{
public frmClasses()
{
InitializeComponent();
}
private void btnSubmit_Click(object sender, EventArgs e)
{
ClsProperties.validateRadio();
ClsProperties.validateTextBox();
}
}
}
I could put all the validation in one method but I am simply trying to show how I would call multiple methods using a class.
Is there a better way to access the form elements in a class?
Merci

Why isn't my UserControl keeping its initialization?

I have a UserControl for which I think I'm initializing some of the members:
// MyUserControl.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 MyNamespace
{
public partial class MyUserControl : UserControl
{
private string m_myString;
private int m_myInt;
public string MyString
{
get { return m_myString; }
set { m_myString = value; }
}
public int MyInt
{
get { return m_myInt; }
set { m_myInt = value; }
}
public MyUserControl()
{
InitializeComponent();
MyString = ""; // was null, now I think it's ""
MyInt = 5; // was 0, now I think it's 5
}
// .........
}
}
When I insert this control into my main form, though, and call a function that checks values within MyUserControl, things don't look like they're initialized:
// MainForm.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 MyProgram
{
public partial class MainForm : Form
{
public MainForm()
{
InitializeComponent();
}
private void MyButton_Click(object sender, EventArgs e)
{
// this prints 0 rather than 5
MessageBox.Show(this.theUserControl.MyInt.ToString());
}
}
}
I'm guessing this is a really simple error but I don't know where. I've tried prepending this. to things, but this probably isn't the way to go about fixing code. :)
Thanks as always!
EDIT: Stepping into the designer code as Pete suggested showed me where the write-over was happening. First I called the constructor of the user control, and then later, the values got overwritten with default values. I hadn't specified any default values (Sanjeevakumar Hiremath's suggestion) so the default values were those of the primitive types (for int this was 0).
What you're likely seeing here is an artifact of the designer. If you ever opened up MainForm in a designer after you added MyUserControl it likely recorded the default values of MyUserControl in the generated InitializeComponent method of MainForm. These recorded values are re-assigned after the constructor of MyUserControl runs hence they're overwriting the values you set.
You can control this behavior via the use of the DesignerSerializationVisibilityAttribute
http://msdn.microsoft.com/en-us/library/system.componentmodel.designerserializationvisibilityattribute.designerserializationvisibilityattribute.aspx#Y375
Use [DefaultValue] Attribute. It lets you specify default value for a property of a control when the value is not specified in the designer.

How do I add common C# code to a Visual C# 2008 Express project/solution?

(I still feel like a complete newbie in MS Visual environments... so please bear with!)
I'm using Microsoft Visual C# 2008 Express Edition.
I have a project and in that project are two different forms. The .cs file for each form starts out:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.Common;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace MyNameSpace
{
public partial class MyFormName : Form
{
...
(...and the second is "MyFormName2" but no differences besides that)
I want to write a function that I know both forms are going to need to access. I right-clicked on my project, selected "Add", selected "New Item" then selected "Code File" and named my file "Common.cs" and it gave me a completely blank file that's in my project.
How do I set this up...? I thought I should do the following...
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.Common;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace MyNameSpace
{
}
...but then when I try to add a function like:
public void mytestfunc() {
}
within that namespace I get the following error:
"Expected class, delegate, enum, interface, or struct"
How do I set things up so I can have "mytestfunc" be available to both MyFormName and MyFormName2?
Thanks!
-Adeena
UPDATE:
Understand (now) that everything must be in a class, but then I don't understand how to really use it. Does that mean I have to create an object? This common function happens to just be some math...
so now if I have this:
namespace MyNameSpace
{
public class MyCommonClass
{
public void testFunc()
{
MessageBox.Show("Hee hee!");
return;
}
}
}
...how do I call testFunc from my Form? Must I do the following:
MyCommonClass temp = new MyCommonClass;
temp.testFunc();
or is there another way to call testFunc?
If you do something like:
namespace MyNameSpace
{
public class myclass
{
public myMethod()
{
// Code
}
}
}
You will be able to instantiate and access it. If you change it to:
namespace MyNameSpace
{
public class myclass
{
public static myMethod()
{
// Code
}
}
}
You will be able to call myClass.myMethod without instantiating a new myClass.
The short answer is that everything needs to be inside a class; I'd suggest you sit down with a basic tutorial to help you get to grips with the basics...
Code need to be inside classes.
It would look something like this:
using System;
namespace MyNameSpace
{
public class CommonHelper
{
public string FormatMyData(object obj)
{
//do something
return String.Empty;
}
}
}
If the function you call is not related to the forms, make it static
namespace myns
{
public static class myhelper
{
public static void DoSomething()
{
}
}
}
and call the method using myhelper.DoSomething();
If the function you want to call is somehow form-related, e.g. common functionality across multiple forms, derive a class from Form (does not need a visual form) and make it base class of the visual forms:
namespace myns
{
public class MyFormBase : Form
{
protected void DoSomethingWithTheForm()
{
}
}
}
and in your form's .cs:
namespace myns
{
public partial class MyFormName : MyFormBase
{
}
}

Categories