0

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
SoyDuck
  • 140
  • 2
  • 10
  • You created a `Control` so obviously the cast `control as TextBox` or anything than `Control` will return null. – Reza Aghaei Nov 06 '16 at 00:08
  • To solve the problem, first define `Control c = null;` then in each block set `c = new TextBox` or any other control which it should be and set some properties. Then after the last if block `if(c!=null)` then set common properties and at last, return c. – Reza Aghaei Nov 06 '16 at 00:12
  • I am curious why do you need this function? Why not run for instance in `Form` constructor `foreach (var c in Controls) c.ForeColor = Color.White;` – Dialecticus Nov 06 '16 at 00:22
  • im trying something new and may be useful in other aspects. clearly it doesnt work XD – SoyDuck Nov 06 '16 at 00:30
  • 1
    @steve i know what null reference is, this is no duplicated question.... – SoyDuck Nov 06 '16 at 00:37
  • 1
    The duplicate explains how casting with as could produce a null. – Steve Nov 06 '16 at 01:00

0 Answers0