Skip to main content
 首页 » 编程设计

c#之如何访问放置在面板中的控件的值

2024年02月23日17mfryf

我在面板中有一个 DropDownList 控件,这个面板依次放置在 SplitContainer 的 panel1 中。我将 DropDownList 的修饰符属性更改为“Public”,但我无法从另一个类访问此控件。

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

我能够访问位于拆分容器之外的其他控件,如下所示。

string amount = pForm.tbAmount.Text; 

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

请您参考如下方法:

拆分容器有 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 

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

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

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