I have a form with sixteen combo-boxes, each with the DropDownStyle
property set to DropDownList
. I am trying to set the form so each control shows its first pre-defined value:
private void Form1_Load(object sender, EventArgs e)
{
foreach (ComboBox DropDown in this.Controls.OfType<ComboBox>())
DropDown.SelectedIndex = 0;
}
This code is not working, although individually assigning each item does. Any ideas why?
My WinForm experience is a bit rusty, but if I remember correctly, this.Controls
will only bring you those controls directly under the main Form. If you have any subcontrols, like a Groupbox, they will be under that groupbox's . Controls
.
You can either explicitly iterate your Groupbox's controls, or you can use recursion to go over all child controls of the form, like you can see here .
You have to detect the control and its type for ComboBox... This means you have to deal with nested loop to detect the controls
foreach (Control MyCtrl in this.Controls)
{
DoAllRichTextBoxes(MyCtrl);
}
void DoAllRichTextBoxes(Control control)
{
ComboBox Cmb = control as ComboBox;
TextBox TxtBx = control as TextBox;
if (Cmb == null && TxtBx == null)
{
// deal with nested controls
foreach (Control c in control.Controls) DoAllRichTextBoxes(c);
}
if (Cmb != null)
{
Cmb.GotFocus += new EventHandler(this.Tb_GotFocus);
Cmb.LostFocus += new EventHandler(this.Tb_LostFocus);
Cmb.KeyDown += new KeyEventHandler(this.VehComn_KeyDown);
Cmb.SelectedValueChanged += new EventHandler(this.AllCombos_SelectedValueChanged);
}
if (TxtBx != null)
{
TxtBx.GotFocus += new EventHandler(this.Tb_GotFocus);
TxtBx.LostFocus += new EventHandler(this.Tb_LostFocus);
TxtBx.KeyPress += new KeyPressEventHandler(this.TbCmb_KeyPress);
TxtBx.KeyDown += new KeyEventHandler(this.VehComn_KeyDown);
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.