I'm currently trying to get into C#, after doing a ton of Java. I wanted to pass my GUI Form to another class, but I run into some trouble trying to access its containers etc. from there.
This is the autogenerated Form class:
namespace Wecker
{
public partial class WeckerDesign : Form
{
public WeckerDesign()
{
InitializeComponent();
new WeckerRun(this);
}
}
}
and this is the recieving class:
namespace Wecker
{
class WeckerRun
{
WeckerDesign wdesign = new WeckerDesign();
public WeckerRun(WeckerDesign wdesign)
{
this.wdesign = wdesign;
new DisplayClock(wdesign);
}
}
}
However, when I am trying to access the container "clockfield" from the recieving class, I can't find it. However, in the passing class, I can easily get there with this.clockpanel. ... and so on.
The recieving class won't even suggest me that. In Java, I would simply pass down my class as a whole with "this" in order to have the exact same reference in the other class, which I can treat as if I would do it in the original class where I got that object reference from.
How do I do this in C#?
How is your "clockpanel" field or property defined? It will need to be public to be accessible from outside the class.
Related
I'm making c# app where I need to access method in partial class from another class.
To be more specific I want to add items to listview from class that is different from partial class but in same namespace.
I tried like this:
public partial class Aa : Form
{
public static void UpdateListView(string[] array)
{
if (ProcessNetUsageList.InvokeRequired)
{
ProcessNetUsageList.Invoke(new Action<string[]>(UpdateListView), array);
}
else
{
ListViewItem item = new ListViewItem(array[0]);
for (int i = 1; i < 4; i++)
item.SubItems.Add(array[i]);
ProcessNetUsageList.Items.Add(item);
}
}
}
and then access it from another class like:
class Test
{
test()
{
ProgramName.Aa.UpdateListView(someArray);
}
}
But its giving an error because static method can only access static variables,and my listview isnt static(i created that listview in vs designer).
If i remove static keyword from method in partial class then i cant access it.I tried to create instance of partial class but without success.Any idea is welcome
note:Im using Invoke in my UpdateListView method because later that will be running on new thread
The nature of an object-oriented language is that objects don't have universal access to modify other objects. This is a good thing.
You've provided relatively little code so it's hard to provide a perfect answer here, but there are a few paradigms that resolve this issue.
One is to pass the instance to your test class, like this:
class Test
{
test(ProgramName.Aa form)
{
form.UpdateListView(someArray);
}
}
Or, if class test actually contains the ListView, you can pass that to a static method in Aa.
class Test
{
ListView someListView;
test()
{
ProgramName.Aa.UpdateListView(someListView, someArray);
}
}
Ultimately, you should think about the logical relationship between these objects to determine how these objects should communicate.
Remove the static keyword from UpdateListView, as you have done before. In test(), you need to instantiate Aa before you access UpdateListView.
Aa temp = new Aa()
You can then access the method by using
temp.UpdateListView(someArray);
Forgive me because I know my wording is terrible. I'll just give an example.
public class MainClass{
public int someVariable;
public List<HasAClass> cList = new List<HasAClass>();
addHasAClass(HasAClass c){
cList.Add(c);
}
}
public class HasAClass{
public HasAClass(){
//Modify someVariable in some way????
}
}
public class HasASubClass : HasAClass{
public ComposedClass(){
//Modify someVariable in some way???
}
}
I having trouble finding the right words for this questions but here is what I am trying to do:
I am creating an aid for an RPG similar to dungeons and dragons. Each character can have a variety of special abilitys which can effect the characters in some way (both negative and positive). I am trying do this with a variety of subclasses which store the pertinent info and get added to the character at varying points in time. What I can't figure out is how to modify the properties of the Character(I called it Main Class in my example) when instances of the HasA class are added to it.
The HasAClass needs a reference to the owning instance, so that it can ask the parent for values and update them when required...
public class HasAClass
{
private MainClass _mainClass;
public HasAClass(MainClass mainClass)
{
_mainClass = mainClass;
_mainClass.someVaraible = 42;
}
}
You then need to pass the owner reference into the constructor of the HasAClass when they are created. If this is not possible at the time of creating the instance then you would instead need to assign it as a property after it has been created. Such as inside the addHasAClass method.
I'm working on a windows forms application in c# and I can't figure out why I can't instantiate a class object from my form code. I have several classes, and from within all of those I can instantiate instances of the other classes publicly or just within methods with no problem.
However, when I try to instantiate one of those classes from my main form, it doesn't work.
It doesn't even recognize that I've just created an instance of the class.
The real kicker is that I can successfully instantiate a class from inside a method in my frmMain class:
private void Form_Load()
{
long deltaTime; int i; int page;
if (releaseMode)
{
modCanCable can = new modCanCable();
can.WaitWhileBusy();
}
All of the classes and form classes are under the same namespace too. Please let me know if you need to me to include any more information to help me find an answer!
You can only declare the global variable at the class level. Making use of that global variable must be done inside a property, method, or function.
For a global enumerator, declare it like you would any other variable
private EnumeratorClass VariableName;
Example (following naming conventions)
private MyEnum _myVariableName;
In C# all code has to be inside of a method. The line modCanCable can = new modCanCable(); declares a private field and uses a field initializer to initialize it to a new modCanCable instance. Any other refrence to the can field must be inside of a method body.
It must be done within a method or constructor. You cannot put it just in the class.
public partial class frmMain : Form
{
modCanCable cab = new modCanCable();
public frmMain()
{
cab.property = "asd";
}
}
How can I prevent this exception to happen as I have to attain some values from one class and pass it to another class where as it's object is already in that class??
My first class is:
public partial class Rack : UserControl
{
ContainerAdmin a = new ContainerAdmin();
public Rack()
{
InitializeComponent();
}
public string getposition()
{
PositionLabel.Text = Regex.Replace(PositionLabel.Text, "[^0-9]+", string.Empty);
return PositionLabel.Text;
}
}
And my other class is :
public partial class ContainerAdmin : UserControl, IDataConsumer<ContainerAdminAssemblyAdapter>
{
public ContainerAdminAssemblyAdapter Adapter { get; set; }
Rack[] racking = new Rack[64];
}
A recursive loop will occur so I want to prevent this.
You have a situation where creating a ContainerAdmin creates an array of Racks which then creates a ContainerAdmin which then creates an array of Racks and so on. It's like a function calling itself without a stop condition and that's why you're getting the stack overflow.
To solve this problem, you have to restructure your program. In either the ContainerAdmin or Rack class, you shouldn't be creating new instances of the other. Using my psychic powers, I'd guess that the Rack objects should be provided with a preexisting ContainerAdmin object.
You are in a circular loop here. In other words you have created circular dependency here. That is why you are getting this exception.
Rack is creating instance of ContainerAdmin and ContainerAdmin is
creating instance of Rack.
I have a bunch of MDI child nodes that are all created in the same way and to reduce redundant code I'd like to be able to call a method, pass it a string (name of child node), have it create the node and add it to the parent.
I can do all the stuff except create the class from a string of a class name, how can I do this?
I'm currently using this in one of my applications to new up a class
public static IMobileAdapter CreateAdapter(Type AdapterType)
{
return (IMobileAdapter)System.Activator.CreateInstance(AdapterType);
}
It's returning an instance of a class that implements IMobileAdapter, but you could use it equally easily with a string:
public static IMyClassInterface CreateClass(string MyClassType)
{
return (IMyClassInterface)System.Activator.CreateInstance(Type.GetType(MyClassType));
}
Call it using code similar to the following:
IMyClassInterface myInst = CreateClass("MyNamespace.MyClass, MyAssembly");
Of course, the class it creates must implement the interface IMyClassInterface in this case, but with a class factory, you'd likely have all your classes implementing the same interface anyway.
Edit:
In reference to your comment, for the purpose of this discussion, think of the term "assembly" as the set of files within your vb/cs project. I'm assuming that you're doing this all within a single project [assembly] and not spreading over multiple projects.
In your case as your classes will be extending the Form object, you would do something like this.
Form myInst = CreateClass("MyExtendedForm");
Or
Form myInst = CreateClass(Type.GetType("MyExtendedForm"));
Depending on whether you get the type within your CreateClass method or outside it. You would need to cast your instance to the correct type in order to access any custom members. Consider this:
class MyCustomForm : Form
{
public int myCustomField{ get; set; }
}
I've got a custom form that extends Form adding the myCustomField property. I want to instantiate this using Activator.CreateInstance():
public static Form CreateClass(string InstanceName)
{
return (Form)System.Activator.CreateInstance(Type.GetType(InstanceName));
}
I then call it using:
Form myInst = CreateClass("MyCustomForm");
So now I have my custom form stored in myInst. However, to access the custom property [myCustomField], you would need to cast your instance to the correct form:
int someVal = ((Type.GetType("MyCustomForm"))myInst).myCustomField;
Activator.CreateInstance(Type.GetType(typeName))
If you have a string which is the name of the class, then you should be able to get a Type object therefrom, by calling Type.GetType(string). From that type, you should be able to use reflection to generate an object.