C# Array of Controls
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 repeati开发者_开发百科ng 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 :]
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;
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;
}
}
}
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
}
精彩评论