Using an Instantiated Class in another Class - c#

Please excuse my ignorance, I am transitioning from VB6 to C# (very steep learning curve). I have googled this to death and I am not able to figure this out. I instantiated a Class on my main form:
namespace App1_Name
{
public partial class Form1 : Form
{
public cConfig Config = new cConfig();
}
}
In my Config Class I am instantiating two other classes:
namespace App1_Name
{
class cConfig
{
//Properties
public cApplication Application = new cApplication();
}
}
In my cApplications Class I have the following:
namespace App1_Name
{
class cApplication
{
//Properties
public string ApplicationName { get { return "App Name"; } }
}
}
So in another class I am looking to use the class I instantiated on Form1 as so:
namespace App1_Name
{
class cXML
{
public void Method1()
{
Console.WriteLine(Config.Application.ApplicationName);)
}
}
}
But I am getting an error that states "Config" doesn't exist in the current context, what am I doing wrong here?

Don't you miss instance of Form1?
Form1 form = new Form1();
Console.WriteLine(form.Config.Application.ApplicationName);
because you are working with properties... not static classes and static methods.

I think you want this:
Console.WriteLine(Form1.Config.Application.ApplicationName);
EDIT: Dampe is correct; you need an instance of Form1, since Config is not a static member of the class. Please refer to his answer.

All of the above, or a one-liner:
Console.WriteLine(new Form1().Config.Application.ApplicationName);

Ok, in order to get my original code to work I made the cApplication Static. This is because I was instantiating the cXML in Form1's Form_Load event so the above solutions just created an endless loop.
What I did to resolve the issue was to pass the Config Class as a reference to the cXML class as follows:
namespace App1_Name
{
public partial class Form1 : Form
{
public cConfig Config = new cConfig();
}
private void Form1_Load(object sender, EventArgs e)
{
cXML XML = new cXML();
XML.Config = Config; //Passing the Config Class by Reference to cXML
}
}
In the cXML class I am doing the following:
namespace App1_Name
{
class cXML
{
public cConfig Config;
public string AppName
{
Console.WriteLine(Config.Application.AppName);
}
}
}
This does exactly what I originally set out to do. My new question is is this an acceptable way of doing this?

Related

C#: Referencing an instance of a class that was made in another class

I need some help with C#.
Let's say I have 3 classes. MainMenu, Form1 and Data.
I have created an instance of Data (referenced as StoreData) in MainMenu.
public partial class MainMenu : Form
{
public Data StoreData = new Data();
}
I want to be able to access this instance of StoreData in Form1. How do I reference it or import it?
You can either
Make StoreData static 🤮 in a static class MyAWesomeStatic and call MyAWesomeStatic.StoreData or even in MainMenu class iteself.
Pass a reference of StoreData to Form1 either via the constructor or a property when you create it.
or pass a reference of MainMenu to form1 and call mainMenu.StoreData when needed.
However, another option might be to use Dependency Injection (DI) and Loosely Couple all this. Have a Singleton instance and pass the in-memory Data Store as some sort of Service (which is what the cool kids might do).
Update
Sorry, still at the beginning stages of learning C#. What does it mean
to make a class static?
Given your current level of knowledge and all-things-being-equal, i think the easiest approach might be just pass in a reference
public class Form1
{
public Data StoreData { get; set; }
}
...
var form = new Form1();
form.StoreData = StoreData;
form.Show();
If you want to reference one class within another class (and don't want to make anything static), composition is one way to go.
You want to reference field of MainForm in Form1, so you want to reference MainForm itself. Thus, you need to create field in Form1 of MainForm type:
public class Form1 : Form
{
...
public MainForm mf { get; set; }
...
}
Now, you can access StordeData with mf.StordeData within Form1.
You could make StoreData static in a static class, something like this:
public static class Form1
{
public static Data StoreData { get; set; }
}
Suppose your StoreData class have one property
public class StoreData
{
public int MyProperty { get; set; }
}
Add static property to your mainform.cs and assign value to MyProperty = 1
public partial class MainMenu : Form
{
public static StoreData Data { get; set; } //static property
private void MainMenu_Load(object sender, EventArgs e)
{
Data = new StoreData { MyProperty = 1 };
}
}
And access your StoreData property inside Form1.cs like
public partial class Form1 : Form
{
private void Form1_Load(object sender, EventArgs e)
{
var id = MainMenu.Data.MyProperty;
}
}
Try once may it help you
Result:

Visual C# Access item from other class file

im writing an application in visual studio and im trying to access a rich text box from an other class. This doesnt seem to work for me. Also how to i call a function from an other class?
My code:
namespace Test{
public partial class Form1 : Form
{
public Form1()
{
// I want from this place to access the MyClass.test("hello");
}
}
}
namespace Test{
class MyClass
{
public void test (string text)
{
// here i want to do richtextbox1.clear(); but the textbox is not available
}
}
}
can be done in many ways. My favorite would be to declare the object of the "MyClass" class within "Form1" by passing the "this" pointer as an argument. Thus, the object of the "MyClass" class will have access to all the members and public functions "Form1". Included RichTextBox1.
namespace Test{
public partial class Form1 : Form
{
MyClass MyClassObject;
public Form1()
{
InitializeComponent();
MyClassObject=new MyClass(this);
MyClassObject.test("hello");
}
}
}
namespace Test{
class MyClass
{
Form1 parent;
public MyClass(Form1 parentForm)
{
parent=parentForm;
}
public void test (string text)
{
parent.richtextbox1.clear();
}
}
}
You don't want to do this. You can for example do it like this:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
var myClass = new MyClass(this.richtextbox1);
myClass.SetTextBoxText("hello");
}
}
class MyClass
{
RichTextBox _textBox;
public MyClass(RichTextBox textBox)
{
_textBox = textBox;
}
public void SetTextBoxText(string text)
{
_textBox.Clear();
_textBox.Text = text;
}
}
This uses constructor injection to pass the textbox to operate on to the contstructor. In Form1's constructor the MyClass is instantiated with a reference to the textbox, which is initialized in InitializeComponent(). Then when you call SetTextBoxText, the class clears the associated textbox's text and then sets it to the passed text.
This is more specific than the commonly suggested method: just pass the entire Form1 instance to MyClass's constructor after making the textbox public, but that way you cannot reuse MyClass for other forms.
But as you see, it's pretty pointless to do. You can let Form1 contain this.richttextbox1.Text = "hello"; directly.
It is not quite clear from your question, but I'm supposing your richtextbox1 is located at Form1.
By default all UI elements of form has private acess modifier - that's why you can't access your richtextbox1 from outer class.
You can change it's access mmodifier to public - but I strongly encourage you not to do it.
Instead write some method in Form1 class like
public void ClearRichTextBox()
{
richtextbox1.Clear();
}
and use it.

The name does not exist in the current context. Not seeing class

I am very new to C# coding, so this may be very simple. In my Site.Master.cs, I have the following code:
GetLoggedInUserProperties();
lblLoginUser.Text = string.Format("Welcome {0}", Session[SessionVars.UserName]);
In a class file, I have put the following in a Public Class:
void GetLoggedInUserProperties()
{
string sLoginId = Program.ExtractUserName(HttpContext.Current.Request.ServerVariables["LOGON_USER"]);
HttpContext.Current.Session[SessionVars.LoginId] = sLoginId;
VerifyInAD(sLoginId);
}
There are no errors in the class file, but my Site.Master.cs cannot find the code in the class file.
I am sure there is a better way to do this, so feel free to let me know. Also, the lblLoginUser does not seem to work either. It has the same error. I have tried recreating the label and deleting the designer file (which never came back). Not sure if this is related or not.
Thank you.
You need to make your methods public or protected to be visible from the markup. So if you want to reference GetLoggedInUserProperties() from the markup, you'll need to change your method declaration to something like this.
protected void GetLoggedInUserProperties()
{
}
Make your method public
Here your class
public class ClassName
{
public void GetLoggedInUserProperties()
{
}
}
public MainWindow()
{
InitializeComponent();
ClassName instance = new ClassName();
instance.GetLoggedInUserProperties();
}
Or make your class static and call your method :
public static class ClassName
{
public static void GetLoggedInUserProperties()
{
}
}
public MainWindow()
{
InitializeComponent();
ClassName.GetLoggedInUserProperties();
}

C# Inconsistant Accessibility on public method (with ref)

I searched some fora and topics to look for the answer but I'm not able to find the solution for my problem. I'll post the code:
namespace Configurator
{
public partial class Dialog : Form
{
private DataStorage dataStorage = null;
public Dialog
{
InitializeComponent();
}
public void setDataStorage(ref DataStorage ds)
{
this.dataStorage = ds;
}
}
}
And it's being used in this class:
namespace Configurator
{
public partial class MainView : Form
{
private DataStorage dataStorage = new DataStorage();
private Dialog DialogBox = new Dialog();
public MainView
{
InitializeComponent();
}
private void newObjectButton_Click(object sender, EventArgs e)
{
DialogBox.Show();
DialogBox.setDataStorage(ref dataStorage);
}
}
}
This is the error:
Inconsistent accessibility: parameter type 'ref Configurator.DataStorage' is less accessible than method Configurator.Dialog.setDataStorage(ref Configurator.DataStorage)
Mark your class DataStorage with public and your error will go away :)
Your class Dialog is public. Your method setDataStorage is also public. This makes this method visible to all other assemblies. But how can other assemblies use that method if they do not have access to the parameter type DataStorage because that one is not visible (probably because it is marked private or internal.)

Using and instance of a class on two forms

I am struggling to get my head around the following.
I current have three forms, my main and one main class.
public partial class frmMain : Form
{
public frmMain()
{
InitializeComponent();
}
}
public partial class frmSuppliers : Form
{
public frmSuppliers()
{
InitializeComponent();
}
}
public partial class frmCustomers : Form
{
public frmCustomers()
{
InitializeComponent();
}
}
In my main program I have:
public class Program
{
public StockControl StockSystem = new StockControl("The Book Shop", 20);
}
I want to be able to access the methods from StockControl in frmSuppliers and frmMain.
I know this may be a N00b question - but its been bugging me all day!
You need to pass it to the other forms as a constructor parameter, then store it in a private field.
declare it static
public static StockControl StockSystem = new StockControl("The Book Shop", 20);
and use as
Program.StockSystem
You should add a field of type StockControl to each of your forms, and make it public, or add getter/setter to it. This means adding the following lines to each one of your forms:
private StockControl _stockCtrl;
public StockControl StockCtrl
{
get { return _stockCtrl; }
set { _stockCtrl = value; }
}
The in the cod of each form you can access your StockControl. But it will be empty (i.e. null) if you don't assign it something. This is something I'd do before opening the form. If you are in your main method:
frmSuppliers frmToOpen = new frmSuppliers();
frmSuppliers.StockCtrl = StockSystem;
frmSuppliers.Show();

Categories