0

Basically I have 3 arrays of different types:

control = new Control[2] { txtRecordDelimeter, txtFieldDelimeter };
name = new string[2] { "Record Delimiter", "Field Delimiter" };
exists = new bool[2] { false, false };

...essentially I would like to create a loop that checks whether the string existed in an object passed into a constructor, if did, set the bool of the respective index to true and then ammend the respective control with a new value.

Originally I had a bunch of if statements and repeating code so I wanna cut that out with a for loop.

However, for example, when I attempt to reference control[0].whatever I get the same list from IntelliSense regardless of whether or not the control is a text box or a combo box etc.

I'm guessing I'm missing something simple here like not referencing an instance of the control per se, but I'd be greatful if someone could explain what I'm doing wrong or suggest a better way to achieve this!

Thanks :]

1
  • hey :] you get the same list from intellisense because what you are looking at are Control(s), not TextBoxes (or whatever) Commented Feb 4, 2011 at 23:54

3 Answers 3

4

Your Control[] array contains Control objects, not TextBox'es etc. You have to cast each particular object in order to use other properties. You can try this:

if(Control[i] is TextBox) (Control[i] as TextBox).Text = "Yeah, it's text box!";
if(Control[i] is CheckBox) (Control[i] as CheckBox).Checked = true;
Sign up to request clarification or add additional context in comments.

Comments

0

I think you mean something like this:

for(int i = 0; i < control.Length; i++)
{
    TextBox textBox = control[i] as TextBox;
    if(textBox != null)
    {
        if(textBox.Text == name[i])
        {
            exists[i] = true;
            continue;
        }
    }
}

1 Comment

Is it not possible to do something like this: txtcontrol = new Control[2] { (TextBox)txtRecordDelimeter, (ComboBox)cboSendEPC }; and then do: if control[0].GetType == TextBox {} etc?
0

you are getting same list from intellisense because all the elements in array are of Control type. You will need to Explicitely cast the Control to (TextBox) or (ComboBox).

lie this:

foreach(Control ctrl in control)
{
   TextoBox tbx = ctrl as TextBox;
   if(tbx != null)
   {
         //do processing
         continue;
   }
   ComboBox cbx = ctrl as ComboBox;
   if(cbx != null)
   {
         //do processing
         continue;
   }
   //and so on

}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.