I have made a custom control (with the Class name as CG) with some properties:
public int type = 0;
public string control_name { get; set; }
public int decimal_pt { get; set; }
Then there is a context menu assigned to it like below while creating the control dynamically:
void addDevProc(int type)
{
if (type == 0)
{
CG Cont = new CG();
//Right Click settings
MenuItem miprop = cm.MenuItems.Add("Properties");
Cont.ContextMenu = cm;
miprop.Click = devSet;
fcon.Controls.Add(Cont);
}
}
And then I am calling a dialogbox for changing the above variables, as following:
private void devSet(object sender, EventArgs e)
{
Control_Settings cs = new Control_Settings(fcon, fcon.GetType());
var drDispSettings = cs.ShowDialog();
if(drDispSettings == DialogResult.OK)
{
ControlProps tempProps = new ControlProps();
tempProps = cs._set;
// Transfer Properties to device
switch (tempProps.UnitType)
{
case 0:
CG control = new CG();
control.id = tempProps.UnitAddress;
control.decimal_pt = tempProps.UnitDecimal;
break;
...
}
}
}
Here the _set is a property of type ControlProps.
Now I want to set the properties of fcon(focussed control) according to _set.
for that I've tried:
(fcon as CG).id = tempProps.UnitAddress; // It gives error "Object Reference not set..."
(CG)fcon.id = tempProps.UnitAddress;// Doesn't work "Control dosen't contain defination of id"
It would be great if you could point me out in correct direction. Thanks for your help!
Edit 1:
fcon
(Type of fcon is Control) is the Control on which the right click was done.
CG
is a class which stands for 'Control Graphics'.
ControlProps
is again a class with some properties and methods which are generalised for the different types of custom control that I've made, CG
is just one of them. I have done this as there are some shared properties between them.
CodePudding user response:
If fcon
is not a CG
the "as" call will return null
.
What you want to do is something like
if (fcon is CG cg)
{
cg.id = ...
}
This block of code will only run if fcon
is a CG
.
Also you would need to Iterate through parent of fcon and find the control that you are looking for, you can find the relevant info here, and then use it in the above code.
Credits, Reddit user u/lmaydev for the answer