How can I access my method from another class - c#

I'm very new to c#, I started a few days ago, so please excuse me if it is basic.
I have two forms, the first one is like a login page, where someone enters their name. On my "Info.cs" class, it reads this name via a setter, into a variable, and my Getter called "GetCardName" returns this Name. I now made a new form where I want to access this name via the GetCardName getter, just dont know how too. Heres the code :
Here is some of the "info.cs" class code:
private string CardName { get; set; } = "";
public string GetCardName()
{
return this.CardName;
}
public void SetName(string name = "")
{
this.CardName = name;
}
And here is the code from the other form that is just trying to call GetCardName():
private void Form2_Load(object sender, EventArgs e)
{
lblWelcome.Text = Info.GetCardName();
}

When creating Form2 you need also pass it reference to the other form to get its properties.
So when creating and showing Form1 you should also create Form2 to pass that reference. Example (not tested) code:
var form1 = new Form1();
var form2 = new Form2(form1);
form1.Show();
and Form2 should be like:
public class Form2
{
private Form1 _form1;
public Form2(Form1 form1)
{
_form1 = form1;
// ... other initialization code
}
// ... other class declarations
}
General solution is: you need to persist reference to the Form1 being shown to the user and then pass that reference to Form2 whenever you create it.

You have two options :
you can create an instance of the class that you want to call
EX : Info infoVar = new Info(); (now you can use infoVar to call any methods of the Info.cs class)
you can make Info class a STATIC class (probably not what you want to do, but still helpful for the future perhaps) This makes it possible to call the info class directly without having to create a variable of that class but has some drawbacks. (more info here)

There is few ways to achieve what you want:
Public static property:
public class Info
{
public static string CardName { get; set; } = string.Empty;
}
You can access it or set value to it directly by:
private void Form2_Load(object sender, EventArgs e)
{
// Set
Info.CardName = "Some name";
// Get
lblWelcome.Text = Info.CardName;
}
Public non-static property:
public class Info
{
public string CardName { get; set; } = string.Empty;
}
You can access it or set value to it directly too, but need to create Info class instance before:
private void Form2_Load(object sender, EventArgs e)
{
Info info = new Info();
// Set
info.CardName = "Some name";
// Get
lblWelcome.Text = info.CardName;
}
Private static field with separated public static Get and Set methods:
public class Info
{
private static string cardName = string.Empty;
public static string GetCardName()
{
return cardName;
}
public static void SetCardName(string name = "")
{
cardName = name;
}
}
You can access GetCardName and SetCardName without creating Info class instance:
private void Form2_Load(object sender, EventArgs e)
{
// Set
Info.SetCardName("Some name");
// Get
lblWelcome.Text = Info.GetCardName();
}
Private non-static field with separated public non-static Get and Set methods:
public class Info
{
private string cardName = string.Empty;
public string GetCardName()
{
return cardName;
}
public void SetCardName(string name = "")
{
cardName = name;
}
}
You can access GetCardName and SetCardName after creating Info class instance:
private void Form2_Load(object sender, EventArgs e)
{
Info info = new Info();
// Set
info.SetCardName("Some name");
// Get
lblWelcome.Text = info.GetCardName();
}
Difference between fields and properties was pretty nice explained here: What is the difference between a field and a property?. In short, properties are "wrappers" over fields, which usually are private and you can't access to them directly or modify. It is a part of Member Design Guidelines. Also properties allow to add some validations through property setter to be sure that valid value is stored at cardName field, e.g.:
public class Info
{
private string cardName = string.Empty;
public string CardName
{
get => cardName;
set
{
// Check that value you trying to set isn't null
if (value != null)
cardName = value;
// Or check that name is not too short
if (value.Length >= 3) // Card name should be at least of 3 characters
cardName = value;
}
}
}

info myInfo=new info();
lblWelcome.Text = myInfo.GetCardName();

Related

C# How to Restrict write of a global variable to only the class where it is initialized (so other classes only can read it)?

As the title states I'm looking for a way how to solve following:
namespace Test
{
public partial class SetVariable : Form
{
public string test = "";
public SetVariable()
{
InitializeComponent();
}
private void button2_Click(object sender, EventArgs e)
{
test = "test"
}
}
}
and in a second form I want to read it, but also want to restrict the user from making any changes to the variable (by accident or on purpose), as all the variables are only to be set in the SetVariable Form, and then be used across all other forms that are planned.
namespace Test
{
public partial class GetVariable : Form
{
public GetVariable()
{
InitializeComponent();
}
private void button2_Click(object sender, EventArgs e)
{
if (SetVariable.test == "test")
{ //doSomething;}
}
}
}
}
If I make the variable a public readonly, than I cant write to it in the form where its supposed to be written. Is there another way of initalizing a global variable which is only changable in the form where its created?
Thanks in advance.
Change:
public string test = "";
to:
public string test { get; private set; }
Also see https://stackoverflow.com/a/3847982/34092 .
Make public property private set.
public partial class SetVariable : Form
{
public string Test {get; private set;}
//Just in case if you want to set value to Test property from other class.
//If you want Test property readonly to other
//class you don't need this method.
public void SetTest(string test)
{
Test = test;
}
}
public class Main
{
SetVariable sv = new SetVariable();
sv.SetTest("Some Value"); //unwanted to scenario. Just in case if you want
//read Test value
string testValue = sv.Test; //allowed
//set Test value
sv.Test = "Other value"; //not allowed.
}

C# - Accessing a list of Objects from one class to another

I am having this very strange problem where i am creating a list of some objects in one class then trying to access it in another class but it's coming empty in other class:
My first class where i am populating the list:
namespace dragdrop
{
struct BR
{
private string var;
public string Var
{
get { return var; }
set { var = value; }
}
private string equalsTo;
public string EqualsTo
{
get { return equalsTo; }
set { equalsTo = value; }
}
private string output;
public string Output
{
get { return output; }
set { output = value; }
}
private string els;
public string Els
{
get { return els; }
set { els = value; }
}
private string elsOutput;
public string ElsOutput
{
get { return elsOutput; }
set { elsOutput = value; }
}
}
public partial class Form1 : Form
{
//******************
private List<BR> list = new List<BR>(); //This is the list!
//******************
internal List<BR> List
{
get { return list; }
set { list = value; }
}
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
string[] vars = new string[] { "Name", "Gender", "Age", "Address", "email" };
comboBox1.DataSource = vars;
}
private void button1_Click(object sender, EventArgs e)
{
BR b = new BR();
b.Var = comboBox1.SelectedItem.ToString();
b.EqualsTo = textBox1.Text;
b.Output = textBox2.Text;
list.Add(b);
//*****************
textBox1.Text = List.Count.ToString(); //This gives the correct count value!
//*****************
//this.Close();
}
}
}
I am accessing it in second class like:
namespace dragdrop
{
public partial class Ribbon1
{
private void Ribbon1_Load(object sender, RibbonUIEventArgs e)
{
}
private void button1_Click(object sender, RibbonControlEventArgs e)
{
Form1 form = new Form1();
List<BR> l = form.List; ;
//*******************
MessageBox.Show(form.List.Count.ToString()); //This strangely gives count 0!
//*******************
}
}
}
I have even tried making everything public in first class but no matter what i do, im always getting empty list in second class.
The is no relation what-so-ever between Form1 and Ribbon1, how can one then access an instance of the other?
With this:
Form1 form = new Form1(); // new instance of Form1
List<BR> l = form.List; ; // of course the list is empty in a new instance!
you can never access values from another instance of Form1.
Since I have no idea how your classes are connected I cannot give you more advice than have a look at this good overview of OO-relationships. You have to connect them somehow for it to work, I would very much recommend composition // aggregation (same thing, different schools).
All i needed to do was make the list a static member in class one, that solved the issue of having different value when i tried to create a new instance of Form1 in Ribbon1 class.
private static List<BR> list = new List<BR>();

C# assign textbox value to a variable in another class in another file

I have created a simple form "people" and there is another file "Information.cs"
In main for assign text box "txt_lname" value to a variable
String lastname = txt_lname.Text;
Then I want to use this value within "information class" (It is a thread class)
How can I use it ?
(I have commented the place I wanted to use that value)
Main Form
namespace users
{
public partial class people : Form
{
public people()
{
InitializeComponent();
}
private void btn_login_Click(object sender, EventArgs e)
{
String lastname = txt_lname.Text;
}
}
}
Information Class
namespace users
{
class Information
{
int[] idno = new int[10];
int[] age = new int[10];
string[] fname = new string[10];
// Here I want to assign txt_lname.Text value to a variable
lastname = txt_lname.Text; // This code is not working
public void run()
{
while (true)
{
for (int i = 0; i < 600; i++)
{
//Some code here
try
{
Thread.Sleep(100);
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString(), "Error", MessageBoxButtons.OKCancel, MessageBoxIcon.Error);
}
}
}
}
}
}
* Can I use value of a variable within run method in thread class ? if cannot then why ?
You have to create an instance of Information on your form and then pass the data to said instance. A classes' code won't magically be executed just because you added it to your project, you have to actually create an instance of the class.
So lets create and initialize an instance of Information on the form:
public partial class people : Form
{
private Information _information;
public people() {
InitializeComponent();
_information = new Information();
}
}
You can now pass stuff to your instance of Information. But to do that you need a way to pass it, or in this case Information needs a way to receive a LastName. There's more than one way to do this but a common approach is to expose a LastName property on Information:
public class Information
{
...
public string LastName { get; set; }
...
}
And now you can pass the value to the LastName property:
private void btn_login_Click(object sender, EventArgs e) {
_information.LastName = txt_lname.Text;
}
Note: When you want to execute the run method on Information you'll do it through the instance just like when you're setting the LastName:
private void btn_run_click(object sender, EventArgs e) {
_information.run();
}
Make the Information class Static
public static class Information
And in your main form you can use it like
Information.LastName = txt_lname.Text;
But you also need to declare LastName as property. So add
public string LastName {get; set;}
into your Information Class.

How to call value from getter and setter method

I have a class called nyoba, i tried to enter value of textBox1.Text to eek.konsentrasi.
And I don't have any idea to call value of eek.konsentrasi from another class. Anybody knows? please help me.
public class nyoba
{
private string Konsentrasi;
public string konsentrasi
{
get
{
return Konsentrasi;
}
set
{
Konsentrasi = value;
}
}
public void njajal(string hehe)
{
}
}
private void button1_Click(object sender, EventArgs e)
{
nyoba eek = new nyoba();
eek.konsentrasi = textBox1.Text;
}
public class caller
{
//how to get eek.konsentrasi variable?
}
As first, your class names should always be pascal case (first letter uppercase). Also your public property should be pascal case.
Then your Nyoba class and its property Konsentrasi are not static, means you have to initiate the class as object before you can access it's non static property.
Nyoba n = new Nyoba();
string s = n.Konsentrasi;
To access the same instance you should not create the instance inside of the button click event. Place your Nyoba instance somewhere you can access to in the form and in the Caller class.

How to use same instance name with multiple classes

I'm new to c# and I think I want to do this but maybe I don't and don't know it!
I have a class called SyncJob. I want to be able to create an instance to backup files from My Documents (just an example). Then I'd like to create another instance of SyncJob to backup files in another folder. So, in other words, I could have multiple instances of the same class in memory.
I'm declaring the object var first in my code so it is accessible to all the methods below it.
My question is: while using the same instance name will create a new instance in memory for the object, how can I manage these objects? Meaning, if I want to set one of the properties how do I tell the compiler which instance to apply the change to?
As I said in the beginning, maybe this is the wrong scheme for managing multiple instances of the same class...maybe there is a better way.
Here is my prototype code:
Form1.cs
namespace Class_Demo
{
public partial class Form1 : Form
{
BMI patient; // public declarition
public Form1()
{
InitializeComponent();
}
private void btnCreateInstance1_Click(object sender, EventArgs e)
{
patient = new BMI("Instance 1 Created", 11); // call overloaded with 2 arguments
displayInstanceName(patient);
}
private void displayInstanceName(BMI patient)
{
MessageBox.Show("Instance:"+patient.getName()+"\nwith Age:"+patient.getAge());
}
private void btnCreateInstance2_Click(object sender, EventArgs e)
{
patient = new BMI("Instance 2 Created", 22); // call overloaded with 2 arguments
displayInstanceName(patient);
}
private void btnSetNameToJohn_Click(object sender, EventArgs e)
{
// this is the issue: which instance is being set and how can I control that?
// which instance of patient is being set?
patient.setName("John");
}
private void btnDisplayNameJohn_Click(object sender, EventArgs e)
{
// this is another issue: which instance is being displayed and how can I control that?
// which instance of patient is being displayed?
displayInstanceName(patient);
}
}
}
Class file:
namespace Class_Demo
{
class BMI
{
// Member variables
public string _newName { get; set; }
public int _newAge { get; set; }
// Default Constructor
public BMI() // default constructor name must be same as class name -- no void
{
_newName = "";
_newAge = 0;
}
// Overload constructor
public BMI(string name, int age)
{
_newName = name;
_newAge = age;
}
//Accessor methods/functions
public string getName()
{
return _newName;
}
public int getAge()
{
return _newAge;
}
public void setName(string name)
{
_newName = name;
}
}
}
You can have public List<BMI> PatientList { get; set; } instead of BMI patient;
if you have one patient you not sure which item accessing and when you assign it will replace previous one
public List<BMI> PatientList { get; set; }
public Form1()
{
InitializeComponent();
PatientList = new List<BMI>();
}
with list of BMI you can add items like below
PatientList.Add(new BMI("Instance 1 Created", 11));
PatientList.Add(new BMI("Instance 2 Created", 22));
if you need to set name of instance 1, you can get the item by index
PatientList[0].setName("John");
Or you can find the patient by one of the property by loop though the PatientList
if you need to display the patient details of "John", by using LINQ
displayInstanceName(PatientList.FirstOrDefault(p=>p.Name =="John"));
If you need to manage a collection of instances, use a List<BMI> or similar. The generic List<T> class can hold (almost) any type of object, is easy to work with, etc. It's also a vital part of the .NET toolkit that you will use many, many times.
Also, consider rewriting your BMI class to use properties more effectively:
class BMI
{
public string NewName { get; set; }
public int NewAge { get; protected set; }
public BMI()
: this("", 0)
{ }
public BMI(string name, int age)
{
NewName = name;
NewAge = age;
}
}
The accessor methods are not required unless you need them for interop with some other system. Using modifiers on the get and set accessors on the properties themselves you can make public-read/private-write properties, etc.

Categories