我有一个 Form
,其中包含多个不同的控件,例如 ComboBox
、TextBox
和 CheckBox
。我正在寻找一种通用的方法来在遍历这些控件时从它们获取值。
例如,像这样:
foreach(Control control in controls)
{
values.Add(control.Value);
}
是否可能或者我是否需要分别对待每个控件
?
最佳答案
试试这个:
Panel myPanel = this.Panel1;
List<string> values = new List<string>();
foreach (Control control in myPanel.Controls)
{
values.Add(control.Text);
}
但请确保您只获得所需的控件。您可以像检查类型一样
if(control is ComboBox)
{
// Do something
}
关于c# - 从多个控件获取值的通用方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11033536/