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

标签 c# winforms

我在面板中有一个 DropDownList 控件,这个面板依次放置在 SplitContainerpanel1 中。我将 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");

关于c# - 如何访问放置在面板中的控件的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9448560/

相关文章:

c# - 如何防止后台线程中的异常终止应用程序?

c# - 用多态替换条件如何

c# - 如何在选择或取消选择其父节点时自动选择或取消选择所有子节点?

c# - 集合中接口(interface)与对象引用的优势

c# - 如何为 Devexpress XtraGrid 控件中的特定列进行数据绑定(bind)?

c# - 插入记录后如何从SQL Server获取标识值

c# - 在 asp.net-core 中将模型的属性别名为不同的名称

c# - Winforms 选择哪种设计模式/敏捷方法论

C# Windows 窗体标签 BackgroundImage

c# - 从线程中的 GUI 对象检索属性