I initiate a Control
with some properties(ForeColor
,BackColor
).
I would then treat that Control
as another control(TextBox
,RichTextBox
) so i don't have to keep repeating the same properties for different controls.
When i try to further add properties to c
, it says {"Object reference not set to an instance of an object."}
Am i using as
wrong?
private Control ConvertToType(string type)
{
// create instance and set style
Control control = new Control();
control.BackColor = Color.FromArgb(20, 20, 20);
control.ForeColor = Color.White;
if (type == "TextBox")
{
TextBox c = control as TextBox;
c.Size = new Size(211, 20); // {"Object reference not set to an instance of an object."}
return c;
}
if (type == "RichTextBox")
{
RichTextBox c = control as RichTextBox;
c.Size = new Size(211, 40);
c.AcceptsTab = true;
return c;
}
if (type == "Username")
{
TextBox c = control as TextBox;
c.Size = new Size(211, 20);
c.Enabled = false;
//c.Text = loggedInUser;
return c;
}
return null;
}
Answer
as
is used to check if an object is a specified type, it returns null if the object isn't, if it is a specified type, treat the object as that type.
So yes i am using as
wrong
Solution
Make a control that contains some properties
public static TextBox FunctionName()
{
TextBox c = new TextBox();
// set properties to c
return c;
}
control = the control returned from FunctionName()
TextBox x = FunctionName();
// add more properties or change existing properties