ControlType = "System.Windows.Forms.WindowsFormsApplication1." + "PictureBox1";
System.Reflection.Assembly asm;
asm = typeof(Form).Assembly;
ControlObject = (System.Windows.Forms.Control)asm.CreateInstance(ControlType);
ControlObject.Name = ControlName;
The next code generated following exception for me:
ControlObject.Name = ControlName;
NullReferenceException was unhandle
Object reference not set to an instance of an object.
Assembly.CreateInstance is expecting a type name and you appear to be passing it the name of an instance of a type (namely, a PictureBox named PictureBox1.). Therefore, ControlObject is null and thus ControlObject.Name will throw a NullReferenceException.
It's not clear what you're trying to do, but that is why you are encountering the problem that you are. If you're trying to create a new instance of PictureBox I don't see why you don't just say new PictureBox(); this class has a public parameterless constructor. Alternatively, if you insist on reflection, you could say
controlType = PictureBox1.GetType();
controlObject = Activator.CreateInstance<Control>(controlType);
We could help more if we knew what you were trying to do instead of just throwing code that doesn't work at us and expecting us to solve world hunger.
Additionally,
ControlType = "System.Windows.Forms.WindowsFormsApplication1." + "PictureBox1";
Please rename this variable to controlType. You should use camel case for variable names.
Why do you have your application class WindowsFormsApplication1 living in the system namespace System.Windows.Forms? Don't do this.
You're probably trying to write
ControlObject = new PictureBox();
Looks like CreateInstance returns null, which means the type wasn't found in the assembly. Is PictureBox1 a type or an object?
Surly your application is not in System.Windows.Forms namespace
"System.Windows.Forms.WindowsFormsApplication1." + "PictureBox1"
Try:
ControlObject = (System.Windows.Forms.Control)asm.CreateInstance(typeof(PictureBox));
or just
ControlObject = new PictureBox();
to create a new instance of control.
Or maybe you want to find an existing PictureBox control on your form?
It means that asm.CreateInstance(ControlType); is returning null.
So, ControlType has a wrong value. It is supposed to recieve as parameter a type http://msdn.microsoft.com/en-us/library/dex1ss7c.aspx and it seems that you are sending an instance PictureBox1.
It should be ControlType = "System.Windows.Forms.PictureBox";
Related
I am building the xamdatachart axes in the code behind as below:
NumericYAxis yAxis = new NumericYAxis() { IsInverted=true, MajorStrokeThickness= 0 };
NumericYAxis yAxis_right = new NumericYAxis() { IsInverted = false, MajorStrokeThickness = 0 };
To set yAxis's location to OutsideLeft and yAxis_right's location to OutsideRight, I added following part:
yAxis.MinimumValue = 0;
yAxis.Title = "Depth";
yAxis.LabelSettings.Location = AxisLabelsLocation.OutsideLeft;
yAxis_right.MinimumValue = 0;
yAxis_right.Title = "Net Production";
yAxis_right.LabelSettings.Location = AxisLabelsLocation.OutsideRight;
But get error as
"Cannot set a property on object 'Infragistics.Controls.Charts.AxisLabelSettings' because it is in a read-only state."
Any insights on why it happens?
I found this link useful from their website and I did follow the same but I get above error.
The error is being thrown because some property in LabelSettings is read-only aka get-only property. From your code, only Location property is being assigned so i would believe that property doesn't have a public set, causing an error when you try.
I searched for NumericYAxis class and found this:
http://help.infragistics.com/Help/Doc/wpf/2012.1/clr4.0/html/InfragisticsWPF4.Controls.Charts.XamDataChart.v12.1~Infragistics.Controls.Charts.AxisLabelSettings~LocationProperty.html
So Location is both a Dependency property (and this is static read-only) and a also the name of a member property (with get and set). When you type yAxis_right.LabelSettings.Location only one suggestion appears in Visual Studio?
Apparently this is a known issue in Xamdatachart.
here is the Infragistics's response and workaround to it.
This is essentially due to the AxisLabelSettings object being frozen, and so it gets placed in a read-only state. The workaround to this issue is to create a new AxisLabelSettings object and assign it to your axes' LabelSettings property. You can use the following code for this:
AxisLabelSettings settings = new AxisLabelSettings() { Location = AxisLabelsLocation.OutsideRight };
yAxis.LabelSettings = settings;
I am new to C# and this question seems dubious but please bear with me. I have an XmlSerializer that works perfectly when written as follows (small code snippet) :
public static AbstractResponseMessageData Execute(AbstractRequestMessageData objRQ, string strComponent)
{
StreamWriter rqWriter = null;
StreamReader rsReader = null;
try
{
Cursor.Current = Cursors.WaitCursor;
String requestType = objRQ.GetType().Name;
MessageBox.Show(requestType);
String xmlRequest = "";
var serializer = new XmlSerializer(typeof(ARC_LOGONRQ));
Unforunately, as ARC_LOGONRQ is a type from an abstract data request, it is not the case that it is always the type I am needing. The only way I even knew it was the type that would get this first request to work was by using the MessageBox in my code. I figured I would simply write something like this to circumvent the issue:
Type acType = Type.GetType(requestType);
and then use acType instead of ARC_LOGONRQ in my serializer. That throws a "Type or Namespace could not be found" error however. Replacing ARC_LOGONRQ with objRQ.GetType() or objRQ throws the same error as well.
I do not understand why I get this error when using acType, nor how I should properly go about serializing objRQ without specifying the actual data type (which I can't do).
Many thanks.
FURTHER INFO:
Using the serializer:
var serializer = new XmlSerializer(typeof(objRQ.GetType()));
I also get a "Type or Namespace could not be found" error. I think it is because the type ARC_LOGONRQ appears to be arbitrary, or not in System.
You can always get the Type of an object by calling GetType. Try this:
var serializer = new XmlSerializer(objRQ.GetType());
Use typeof to obtain a Type at compile time. Use GetType to obtain a Type at run time .
I have WinForm called Form1 and there are Button1, MemoEdit1 and 2 TextBoxes named TextBox1 and TextBox2. At runtime user should be able write C# code in MemoEdit1 in order to manipulate the TextBox controls. F.e: at runtime user typed into MemoEdit1 simple code like: TextBox2.Text = "Hello" + TextBox1.Text;
So, when I click on Button1, I need to compile and execute the code.
Question may sound so simple as I am a newbie in compiling/executing code during runtime in C#.
Could you pls, help?
Thanks.
Take a look on this snippet
public class Evaluator
{
public void Eval(string Code)
{
Microsoft.CSharp.CSharpCodeProvider Provider = new Microsoft.CSharp.CSharpCodeProvider(); // Create an provider
System.CodeDom.Compiler.ICodeCompiler Compiler = Provider.CreateCompiler(); // Create An Compiler
System.CodeDom.Compiler.CompilerParameters Parameters = new System.CodeDom.Compiler.CompilerParameters(); // Create a parameters of the compiler
Parameters.GenerateInMemory = true; // It should generate the compiled assembly in the memory
System.CodeDom.Compiler.CompilerResults Results = Compiler.CompileAssemblyFromSource(Parameters, Code); //Compile it
///Now you just need to use reflection to call its methods
object SomeClass = Results.CompiledAssembly.CreateInstance("ClassName"); //Name of the class you want to create an instance
var Method = SomeClass.GetType().GetMethod("MethodName"); //Name of the Method you want to call
Method.Invoke(SomeClass, null); // change null for the argument it needs
}
}
if you want to just write code you will have to add the an class and a Method to wrap the user code and then you call it through the Invoke, you will probably have to reference your own assembly into this assembly
I'm trying to create controls at runtime using Reflection.
In my case, I get a string like Label or Button and I would like to create a object Label or Button of it.
Assembly WinFormasm = Assembly.Load("System.Windows.Forms,Version=2.0.000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089");
Control label = (Control)Activator.CreateInstance(WinFormasm.GetType("System.Windows.Forms."+type));
When I execute this, I get the error:
File or assembly name 'System.Windows.Forms,Version=2.0.000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089', or one of its dependencies, was not found.
I don't realy know what is wrong there. I have also tried:
try
{
Type cntrl = Type.GetType("System.Windows.Forms.Button,System.Windows.Forms, Culture=neutral, Version=2.0.0.0, PublicKeyToken=b77a5c561934e089", true);
label1.Text += cntrl.ToString() + " ";
}
catch(Exception e)
{
label1.Text += e.ToString() + " ";
}
Trying this, I got an execution error: he can't create the type and returns null. If I change the gettype string into System.Int32, it works.
How can I create a control item using a string?
What's wrong with the following?
Button cntrl = new Button();
If you're hardcoding the values why do you need to use reflection?
Your version number is wrong for System.Windows.Forms:
var assembly = Assembly.Load("System.Windows.Forms, version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089");
Then to create the desired control type, just specify the type name:
var type = "Button";
var control = (Control)Activator.CreateInstance(assembly.GetType("System.Windows.Forms." + type));
to create the controls from string
you need to use Activator class
check this link
http://bytes.com/topic/c-sharp/answers/236152-how-create-control-instance-dynamicly-text had a quite intesting idea to solve the problem with a little fix it worked for me.
I get the type of form (controls are standing in a form right) from that type I get the assembly.
From the assembly I get the object by calling the gettype function with the parameters of the type of control I would like.
Finally I cast it to a control type.
private Control createcontrol(string type)
{
Type typen = typeof(Form);
Assembly assem = typen.Assembly;
//Assembly assem = Assembly.LoadFrom(typeof(Form).ToString());
Type controlType = assem.GetType("System.Windows.Forms."+type); // GetType(controlType);
object obj = Activator.CreateInstance(controlType);
Control control = (Control)obj;
return control;
}
Thanks for the help folks!
string ControlType = "TextBox";
Assembly FormAssembly = Assembly.GetAssembly(typeof(Form));
Control MyControl = (Control)FormAssembly.CreateInstance("System.Windows.Forms." + ControlType);
Just change ControlType value.
I have a main form that is launched and then it can go to any of the other forms I have created. But the kicker is that I have written a class that I call that returns a string with the name of the form to go to.
Currently I don't have this working so I am going from form to form like this (statically written linking code):
this.Hide();
CloudAccess nextForm1 = new CloudAccess();
//Where CloudAccess is the class of the next form.
nextForm1.ShowDialog();
What I want is something like this:
FormController pick = new FormController();
//Where FormController is the Class I create an object of and ask what's next
string next = pick.whereToGo(); //lets say it returns "CloudAccess"
this.Hide();
next nextForm1 = new next(); //next is desired to be the contents of the string
nextForm1.ShowDialog();
The problem is that I don't know how to use the returned string to make the new object and use it. I've been looking at Invoke and Reflection topics like this one: Use string value to create new instance
But I'm new to C# and I'm not sure how to apply that to this scenario.
Thoughts? Thanks!
Here's the working code from what fejejosco said:
string asdf = "CloudAccess";
Type CAType = Type.GetType("namespace." + asdf);
Form nextForm2 = (Form)Activator.CreateInstance(CAType);
nextForm2.ShowDialog();
Thanks!
Get the type of the form: Type.GetType("name.space." + formname), so if your class is name.space.CloudAccessForm, then pass in CloudAccessForm as formname, and it will give you the type. Then you can instantiate it with Activator.CreateInstance(type). Then cast it to a Form, and show it.