Access instance of class from MainWindow - c#

I have an application with MainWindow and another class called MyClass. MyClass has a method in it that I need to access from the MainWindow class. MyClass is loaded when the application loads. How do I call the method in MyClass from MainWindow without creating a new instance of MyClass:
MyClass class = new MyClass();
?

The straight forward answer to your question is to mark class method as static. That will allow you calling it from any place.
On the other hand, it's probably is not what you really need. Thus, if you create MyClass on application start inside Application class then you need to expose MyClass instance, for example, through application property. Look at the example code.
public class MyClass
{
public void Method()
{
// ...
}
}
The code of your App:
public partial class App
{
public MyClass MyClassInstance { get; private set; }
private void Application_Startup(object sender, StartupEventArgs e)
{
MyClassInstance = new MyClass();
}
}
And the code of window where you call method of your class:
public partial class MainWindow : Window
{
private void Button_Click(object sender, RoutedEventArgs e)
{
((App)Application.Current).MyClassInstance.Method();
}
}

Sounds very suspect, but you do what you are saying by making that method static
public partial class MainWindow
{
public void MethodInMainWindow()
{
// Don't need to create a new instance of MyClass
MyClass.MethodInMyClass();
}
}
public class MyClass
{
public static void MethodInMyClass()
{
// ....
}
}
Here is a little bit of documentation on static vs instance

Related

How to design these classes the best way?

I have a question how to design the following case in a good (better) model (I'm using C#):
So far it is like this:
public class ExampleClass
{
private object ExampleClassPrivate;
public SubExampleClass SubExampleClassPublic;
-------
public void ChangeExampleClassPrivate()
{
ExampleClassPrivate = "SOMETHING";
}
private class SubExampleClass
{
private object SubExampleClassPrivate;
public SubSubExampleClass SubSubExampleClassPublic;
.
.
.
}
public class SubSubExampleClass
{
...
public void DoSomething()
{
//Do something within SubSubExampleClass
//In the end: call ChangeExampleClassPrivate()
}
}
}
I could do the following:
I create an instance of ExampleClass, let's call it "TestInstance".
Then:
TestInstance.SubExampleClassPublic.SubSubExampleClassPublic.DoSomething();
TestInstance.ChangeExampleClassPrivate();
But I don't want to execute ChangeExampleClassPrivate() manually the whole time after DoSomething(). I look for a possibility to call ChangeExampleClassPrivate() from inside of DoSomething().
How could I achieve this? I guess my class structure is not perfect, but i don't see how I could change it to work the proper way.
You can pass a reference to a prent class to all your subclasses, like this:
private class SubExampleClass
{
private object SubExampleClassPrivate;
private readonly SubSubExampleClass SubSubExampleClassPublic;
private readonly ExampleClass parent;
public SubExampleClass(ExampleClass parent)
{
// save reference to the parent object
this.parent = parent;
// pass it to subclass
SubSubExampleClassPublic= new SubSubExampleClass(parent)
}
.
.
.
}
public class SubSubExampleClass
{
private readonly ExampleClass parent;
public SubSubExampleClass(ExampleClass parent)
{
this.parent = parent; // save reference to the parent object
}
public void DoSomething()
{
//Do something within SubSubExampleClass
parent.ChangeExampleClassPrivate;
}
}
And a usage, somewhere in ExampleClass:
var instance = new SubExampleClass(this);
instance.SubSubExampleClassPublic.DoSomething();

Using class members without mentioning class name

I have a global class and an asp.net page. I want use globally declared singleton members without re-declaring the class name.
for example:
Panel.cs:
public class Panel {
public static Panel P = new Panel();
private Panel() {
}
public void DoSomething() {
HttpContext.Current.Response.Write("Everything is OK!");
}
}
sample.aspx.cs:
public partial class temp_sample :System.Web.UI.Page {
Panel p = Panel.P;
protected void Page_Load(object sender, EventArgs e) {
//regular:
myP.DoSomething();
//or simply:
Panel.P.DoSomething();
//it both works, ok
//but i want to use without mentioning 'Panel' in every page
//like this:
P.DoSomething();
}
}
Is this possible? Thank you very much!
Create base class inherited from Page
class MyPage : System.Web.UI.Page
and put your p property there once.
Than just inherit your pages from MyPage instead of System.Web.UI.Page
assuming you're just looking to implement the singleton pattern (avoid scoping a Panel property within each page):
public class Panel
{
#region Singleton Pattern
public static Panel instance = new Panel();
public static Panel Instance
{
get { return instance; }
}
private Panel()
{
}
#endregion
public void DoSomething()
{
HttpContext.Current.Response.Write("Everything is OK!");
}
}
Then reference it simply using:
Panel.Instance.DoSomething();

How to call a method in FORM class from another class but both are same namespace

class Form1 : Form
{
public void enable()
{
//1st method which i want to call from another class
}
public void display()
{
//2nd method which i want to call from another class
}
}
class Buffer : signal
{
protected override Analyse()
{
//from here i want to call two functions in form class
}
}
this is how my code looks like anyone please reply this tread.........
When creating the Buffer class, you have to pass reference to the real instance of Form1 then just use that instance. Sample code:
class Form1 : Form
{
public void InitBuffer()
{
Buffer b = new Buffer(this);
...
}
public void enable()
{
//1st method which i want to call from another class
}
public void display()
{
//2nd method which i want to call from another class
}
}
class Buffer : signal
{
private Form1 form;
public Buffer(Form1 parent)
{
form = parent;
}
protected override Analyse()
{
form.enable();
form.display();
}
}
You can't grab the true instance of Form1 just like that out of nowhere.

Logging class using delegates (NullReferenceException)

I have created a small application but I would now like to incorporate some type of logging that can be viewed via listbox. The source of the data can be sent from any number of places. I have created a new logging class that will pass in a delegate. I think Im close to a solution but Im receiving a NullReferenceException and I don’t know the proper solution. Here is an example of what Im trying to do:
Class1 where the inbound streaming data is received.
class myClass
{
OtherClass otherClass = new OtherClass();
otherClass.SendSomeText(myString);
}
Logging Class
class OtherClass
{
public delegate void TextToBox(string s);
TextToBox textToBox;
Public OtherClass()
{
}
public OtherClass(TextToBox ttb)
{
textToBox = ttb;
}
public void SendSomeText(string foo)
{
textToBox(foo);
}
}
The Form
public partial class MainForm : Form
{
OtherClass otherClass;
public MainForm()
{
InitializeComponent();
otherClass = new OtherClass(this.TextToBox);
}
public void TextToBox(string pString)
{
listBox1.Items.Add(pString);
}
}
Whenever I receive data in myClass, its throwing an error. Any help you could give would be appreciated.
Remove the empty constructor and pass the proper delegate in.
class OtherClass
{
public delegate void TextToBox(string s);
private readonly TextToBox textToBox;
public OtherClass(TextToBox textToBox)
{
if (textToBox == null)
throw new ArgumentNullException("textToBox");
this.textToBox = textToBox;
}
public void SendSomeText(string foo)
{
textToBox(foo);
}
}
Change your OtherClass to check for null:
class OtherClass
{
public delegate void TextToBox(string s);
TextToBox textToBox;
Public OtherClass()
{
}
public OtherClass(TextToBox ttb)
{
textToBox = ttb;
}
public void SendSomeText(string foo)
{
var handler = this.TextToBox;
if(handler != null)
{
textToBox(foo);
}
}
}
Now the reason you're getting the exception though is because in your myClass when you're creating a new OtherClass, you're not providing a method the delegate should "point" to. Therefore, when you're OtherClass calls textToBox(foo); there's no method behind it, and it blows up.
In myClass, you're not calling the overloaded OtherClass constructor that takes a TextToBox, so textToBox(foo) fails because textToBox has not been set.
Can you show the code where myClass is initialized and called?
You should pass in myClass constructor you OtherClass instance created in MainForm, don't create OtherClass instance in myClass it's not the instance to which you attached handler.

use class in another windows form c#?

I have a problem in a same namespace:
public partial class frmForm1 : Form // Form1
{
public class Account
{
public string Username, Password, RePassword, Name, bd, dt, dc;
}
public class ListAcc
{
public static int count = 0;
private static List<Account> UserList;
public static List<Account> Data()
{
return UserList;
}
}
public partial class frmForm2 : Form // Form2
{
private void button2_Click(object sender, EventArgs e)
{
ListAcc A; // error
string n = A<Account>[0].Usename; // error
// What should i do?
}
}
Someone can help me fix this problem? Thanks a lot!
You've nested the Account and ListAcc class inside the frmForm1 class.
Move them outside of frmForm1's class definition or change it to be frmForm1.ListAcc A;
Also, I'm not sure what you're trying to do here. This wouldn't compile no matter what you do. Are you trying to make ListAcc a generic class?
string n = A<Account>[0].Usename; // error
If you need Account in more than one class maybe it's better not to put in in the frmForm1 but in a separate file. A class inside another class is not a good idea.
public partial class frmForm1 : Form // Form1
{
public class Account
{
//some code
}
public class ListAcc
{
//SomeCode
}
}
public partial class frmForm2 : Form // Form2
{
private void button2_Click(object sender, EventArgs e)
{
//Thats will work
frmForm1.ListAcc A = new frmForm1.ListAcc();
string n = A.Data()[0].Usename;
}
}
the way your class structure is defined you need to declare the variable like this
frmForm1.ListAcc A;
Move Account class outside the frmForm1 class.
Or you should address your Account type through its "parent" type frmForm1:
frmForm1.Account

Categories

Resources