How to access Elements in another Form or class - c#

I want a program, which creates a List of Recipes, so something like a management system for Recipes. But I dont know how to access e.g. the List in the other class.
I set every freaking thing public.
public partial class Form1 : Form
{
//default constructor
public static List<Recipe> RecipeList = new List<Recipe>();
}
public partial class Form2
{
//default constructor
private void Form2_Load(object sender, Eventargs e)
{
RecipeList.Add("Chili con Carne");
}
}
public class Recipe
{
//some properties and methods...
{
I cannot access the RecipeList there. How can I reach my goal to get the input for that Recipe in Form2 but then store a List globally where I can e.g. display the List of Recipes anywhere...

u can do like this
public static List<Recipe> RecipeList = new List<Recipe>();
Form1.RecipeList.Add("Chili con Carne");

As your variable public static List<Recipe> RecipeList is static. You can use that variable by using the class name (Form1).
Here is what you can do:
public partial class Form2
{
//default constructor
private void Form2_Load(object sender, Eventargs e)
{
Form1.RecipeList.Add("Chili con Carne");
}
}

Related

C# class string used on a another Form

i have a little problem on my form Login when i Login, i want send my username on the string username in my class functions.
And when my Main Form is loaded i want this class functions get the username from my form login with my username
i have try something like this:
My form login:
public Functions FUNCTIONS = new Functions(); //for my class Functions
FUNCTIONS.Username = "Username123";
My class Functions:
public class Functions
{
public string Username = ""; //empty
}
and my Main form after login
public Functions FUNCTIONS = new FUNCTIONS();
private void Main_Load(object sender, EventArgs e)
{
MessageBox.Show("Welcome "+ FUNCTIONS.Username " to my application.");
}
When my Main Form is loaded it's don't show the username string it's keep this empty, thanks for your time and your help for fix my problem.
You could try
public class Functions
{
public static string Username { get; set; }
}
Also this way you dont need to initialize Functions with new keyword, Functions.Username would be enough
It would work because static keyword ensures that there is one instance of this peroperty for yor application lifetime. Also you could consider using singleton pattern with dependency injection, read more there :
https://csharpindepth.com/articles/singleton
Don't create new 2nd time, new creates an another Functions instance. Pass to main Form the existing one instead and assign it to the field in main Form.
public partial class LoginForm : Form
{
private Functions functions = new Functions();
public LoginForm()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
functions.Username = "Username123";
new MainForm.Show(functions);
this.Close();
}
}
public partial class MainForm : Form
{
private Functions functions;
public MainForm()
{
InitializeComponent();
}
public MainForm(Functions f) : this()
{
functions = f;
}
private void MainForm_Load(object sender, EventArgs e)
{
MessageBox.Show(functions.Username);
}
}

Calling a function in the main Form from another Class in C#

how I can call a function located in the Form class from another class?
this is my code.I want call get_data(data) in prog class?
thanks.
public partial class Form1 : Form
{
get_data(int mydata)
{
//code
}
//code
prog var1=new prog();
var1.start_data();
}
public class prog
{
public void start_data()
{
Thread ct=new Thread(do);
ct.start();
}
private void do()
{
int data=40;
get_data(data); ///?????????????this is wrog
}
}
If you need to access the current instance of your main form, you could pass it along to the class:
public partial class Form1 : Form
{
internal void get_data(int mydata)//Change to internal or public, as default is private
{
//code
}
private void button1_Click(object sender, EventArgs e)
{
prog var1 = new prog();
var1.start_data(this);//pass along instance of your main form
}
}
public class prog
{
private Form1 MainForm;
public void start_data(Form1 form)
{
MainForm = form;//set form
Thread ct = new Thread(doSmt);
ct.Start();
}
private void doSmt()
{
int data = 40;
MainForm.get_data(data); //use form
}
}
Before you can call a method from another class you need an instance of this class. One way would be to create a new instance.
But I guess you'll have an instance of this class already because it's a form an I guess you are opening this form anywhere; just use this instance.
A hint: I would not put any business logic in my form. I would put it in another class.
private void do()
{
int data=40;
Form1 form = new Form1();
form.get_data(data);
}
Don't forget to make the get_data method public because you can't access it in another class when it's private.
The method is not static so you need to actually instantiate the Form1 class.

Accessing MainForm from another class file

I have this MainForm class:
namespace homework_001{
public partial class MainForm : Form
{
public MainForm()
{InitializeComponent();}
public string Change
{
get{ return label.Text;}
set{ label.Text = value;}
}
void ButtonClick(object sender, EventArgs e)
{
Test a = new Test();
a.changer();
}
}}
And I have this class:
namespace homework_001{
public class Test
{
private MainForm form = new MainForm ();
public void changer(){
form.Change = "qqqqq!";
}
}}
Desired workflow is to change the label/text on button press.
It compiles, but nothing happens after I press the button.
What might be the issue?
What is happening is that the form you are showing is not the same as the one inside the class Test.
To make things work you should pass the form to the class Test in this way:
public class Test
{
private MainForm form;
public Test(MainForm f)
{
this.form=f;
}
public void changer(){
form.Change = "qqqqq!";
}
}}
and in your main form you do this:
public partial class MainForm : Form
{
public MainForm()
{InitializeComponent();}
public string Change
{
get{ return label.Text;}
set{ label.Text = value;}
}
void ButtonClick(object sender, EventArgs e)
{
Test a = new Test(this);
a.changer();
}
}}
done create a new object of the main form.. Instead. make the string Change public and static
and change it from test class like Mainform.Change="some text";
You're creating another MainForm object, different from the one that's actually displayed on the screen. To work on the same object you need to pass it to the Test class, like this:
Test a = new Test(this); // "this" is the MainForm object you want to work with
a.changer();
This will give Test class a reference to your MainForm object.
Now, you need to create a constructor in Test with one argument, and store the received reference to your form object in Test's private MainForm form field. You shouldn't have any trouble doing that.
change you code below:
void ButtonClick(object sender, EventArgs e)
{
Test a = new Test();
a.changer(ref this);
}
you pass the form object to function by refrence and changed that
public class Test
{
public void changer(ref MainForm form){
form.Change = "qqqqq!";
}
}
refer this link Passing Reference-Type Parameters (C# Programming Guide)

Does not exist in current context (Visual C#)

I have an error coming up saying; The name 'map' does not exist in current context. What am I doing wrong?
Sorry I am quite new to coding...
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
variables();
}
public static void variables()
{
string[,] map;
map = new string[140, 140];
}
public static void updateMap(string[,] map)
{
MessageBox.Show("a");
}
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
updateMap(map);
}
}
Create class variable string[,] map.
public partial class Form1 : Form
{
public string[,] map;
...
so your variable "map" will be accessible in all(non-static) methods of this class
Get rid of your variable method.
public static void variables()
{
string[,] map;
map = new string[140, 140];
}
instead, keep it inside your class, so all the other methods may access it.
Think of the class as the parent. All the "methods" inside the class are its children. Everything inside of the children are its "things". Children don't like to share, specially with their brothers or sisters.
That being the case you want it somewhere where the parent has control of it, and the children have to follow the parent's rules of "sharing"
Like this.
public partial class Form1 : Form
{
public string[,] map;
map = new string[140, 140];
public Form 1: Form1()
{
....
}
private void Form1_Load()
{
.....
}
public static void updateMap()
{
.....
}
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
.....
}
}
the variable map is only valid in this method because it is declared within:
public static void variables()
{
string[,] map;
map = new string[140, 140];
}
If it should be valid for the whole class, just declare it as a field:
public partial class Form1 : Form
{
string[,] map;
public Form1()
{
InitializeComponent();
}
...
}
But this is very, very basic. I highly recommend to read a book about C#:
http://www.amazon.com/s/ref=nb_sb_noss?url=search-alias%3Daps&field-keywords=c%23
You have only declared map inside the context of the variables method (not sure what this method is even for). As a result, this variable is not accessible anywhere outside of that method. You need to declare it as a class property, like so:
public partial class Form1 : Form
{
private string[,] map;
...
}
Then, initialize this on your Load method:
private void Form1_Load(object sender, EventArgs e)
{
map = new string[140,140];
}
You can then do away with the variables method and reference this property from inside your other methods as you are doing now.

C# call function from outside current class

Currently have a mainForm.cs which calls a class panel.cs
panel.cs holds multiple pictureboxes with events such as _click, _mousedown, _mouseup
I wish to call a function in mainForm.cs from panel.cs
do i need to use a callback / delegate. Is there another way to access this function
I have tried
Main main = new Main();
main.functioninMain does not work
any help or direction would be appreciated.
for example
panel.cs
private void pb_button1_Click(object sender, EventArgs e)
{
this.BeginInvoke(new Action(main.functioninMain));
}
You should not instantiate another object of MainForm, which creates a duplicate and all the objects withing the new MainForm will not have the values of your actual MainForm.
Approach 1
You can try creating a static instance of you MainForm like below
public partial class MainForm : Form
{
public static MainForm Instance = null;
public MainForm()
{
InitializeComponent();
Instance = this;
}
public SomeMethod()
{
}
}
Now if you have your panel class, then you can easily access public methods and variables of MainClass
class Panel : Form
{
public Panel()
{
MainForm.Instance.SomeMethod();
}
}
Edit: Pass Handle as parameter to the form (From Ben Voigt's suggestion)
Approach 2:
As Ben suggested, it is also important to have a safer code, so much cleaner approach will be passing handle of the control as parameter and then to access them.
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
TestClass test = new TestClass();
test.ModifyText(textBox1);
}
}
public class TestClass
{
public void ModifyText(TextBox textBox)
{
textBox.Text = "New text";
}
}
If we can use delegate & events something like this
public partial class MainForm : Form
{
public MainForm()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Panel formPanel = new Panel();
formPanel.OnPanelClick += new Panel.OnPanelButtonClick(formPanel_OnPanelClick);
formPanel.Show();
}
void formPanel_OnPanelClick(string a)
{
MessageBox.Show(a);
}
}
public partial class Panel : Form
{
public delegate void OnPanelButtonClick(string a);
public event OnPanelButtonClick OnPanelClick = null;
public Panel()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
if (OnPanelClick != null)
{
OnPanelClick("from Panel.cs");
}
}
}
You should avoid circular dependencies at all costs (class A depends on class B, and class B depends on Class A).
There are so many ways to do this, but perhaps one of the easier ways is to use an interface. mainForm.cs implements it like this:
public class mainForm : IMainForm {
// This method is defined in the interface, so mainForm
// must implement it.
public string GetStringFromMainForm() {
return "Hello from MainForm";
}
public void CreatePanel() {
// pass in a reference to myself so panel knows how to
// talk to me.
var panel = new Panel(this);
}
}
And IMainForm (the interface) could look like this:
public interface IMainForm {
string GetStringFromMainForm();
}
Then your panel class can talk to the Main form without having to reference mainForm.cs explicitly:
public class Panel {
// use a private variable to keep track of main form
private IMainForm _mainForm;
// Constructor: pass in a class that implements IMainForm. It isn't
// a type of MainForm, so there's no dependency on the concrete class.
public Panel(IMainForm mainForm) {
_mainForm = mainForm;
}
public void TalkToMainForm() {
var resultFromMainForm = _mainForm.GetStringFromMainForm();
Console.WriteLine(resultFromMainForm);
}
}

Categories

Resources