简体   繁体   English

C#组合框下拉列表项类型

[英]C# Combobox dropdownlist item type

I have a form with sixteen combo-boxes, each with the DropDownStyle property set to DropDownList . 我有一个带有十六个组合框的表单,每个组合框的DropDownStyle属性设置为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. 我的WinForm的经验是有点生疏,但如果我没有记错, this.Controls只会给你带来的直接控制下的主要形式。 If you have any subcontrols, like a Groupbox, they will be under that groupbox's . 如果您有任何子控件(如Groupbox),它们将位于该Groupbox的。 Controls . 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 . 您可以显式地迭代Groupbox的控件,也可以使用递归遍历表单的所有子控件,如此处所示

You have to detect the control and its type for ComboBox... This means you have to deal with nested loop to detect the controls 您必须检测ComboBox的控件及其类型...这意味着您必须处理嵌套循环才能检测控件

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);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM