提问人:Paras 提问时间:3/3/2023 更新时间:3/3/2023 访问量:184
当控件的名称发生更改时,使用 Control.ControlCollection.Find 在 Windows 窗体应用程序中查找多个控件
Find multiple controls in a windows form application using Control.ControlCollection.Find when the name of the control is changing
问:
我是 c# 和 Windows 窗体的初学者。我想使用Controls.ControlsCollection.Find在表单中查找多个文本框(存在于组框中)。(请注意,组框是在运行时使用表单中的按钮动态加载的)。
我使用 for 循环来改变控件(TextBox)的名称以查找(Tb{a})。 然后,我使用 foreach 循环访问数组中的控件。
我尝试使用for循环来改变文本框的名称。我希望它能用这些文本框创建一个控制数组。稍后,我将该值转换为浮点数并将其添加到“L”
private float FindTextBoxes()
{
for (int i=1; i < a+1; i=i+2)
{
Control[] textboxes = this.Controls.Find($"Tb{i}",true);
}
float L = 0;
foreach (Control ctrl in textboxes)
{
if (ctrl.GetType() == typeof(TextBox))
{
L = L + float.Parse(((TextBox)ctrl).Text);
}
}
return L;
}
我得到的错误是: 错误 CS0103 名称“文本框”在当前上下文中不存在。 如何解决这个问题?
感谢所有帮助。 谢谢。
答:
1赞
MrSpt
3/3/2023
#1
变量必须在循环之外定义。
private float FindTextBoxes()
{
List<TextBox> textboxes = new List<TextBox>();
float L = 0;
for (int i=1; i < a+1; i=i+2)
{
textboxes.AddRange(Controls.Find($"Tb{i}",true).OfType<TextBox>());
}
foreach (TextBox ctrl in textboxes)
{
L += float.Parse(ctrl.Text);
}
return L;
}
评论
0赞
Paras
3/3/2023
你好@MrSpt , 上面的代码有效。但是我想知道列表框的元素是否有索引?,因为我也可以访问集合中的特定文本框。
0赞
MrSpt
3/3/2023
您应该为此创建一个单独的问题。
0赞
Paras
3/3/2023
好的,我会注意到这一点。对于这个问题,如果我想以其他方法访问列表框,是否必须将列表框声明为字段?请帮助解决这个@MrSpt。
0赞
MrSpt
3/3/2023
是,使用字段或属性。关于你的第二个问题,也许这篇文章对你有所帮助。stackoverflow.com/questions/6504336/......
评论