如何访问放置在面板中的控件值?

时间:2012-02-25 22:15:15

标签: c# winforms

我在面板中有DropDownList控件,而此面板又放在SplitContainer的{​​{1}}中。我将修饰符属性更改为panel1的“公共”属性,但我无法从另一个类访问此控件。

DropDownList

我可以访问位于拆分容器外部的其他控件,如下所示。

//created instance of the form
Payment pForm = new Payment();

但我无法访问下拉列表控件。

1 个答案:

答案 0 :(得分:4)

拆分容器有2个面板,每个面板都有一组控件,所以:

ComboBox dropdown = pForm
    .SplitContainer1       // get the splitcontainer control of pForm
    .Panel1                // get the first panel of this container
    .Controls              // get the controls collection
    .OfType<ComboBox>()    // find all controls that are of type ComboBox
    .FirstOrDefault();     // get the first or null if none

显然,为了能够从pForm.SplitContainer1表单类之外访问Payment,您必须向其提供公共getter。

如果您想进一步限制下拉列表的名称(假设您在此面板中有多个下拉菜单):\

ComboBox dropdown = pForm.
    .SplitContainer1
    .Panel1
    .Controls
    .OfType<ComboBox>()
    .FirstOrDefault(x => x.Name == "comboBox1");