c# - 遍历标签并更改值 c#

标签 c# winforms loops

我希望从 XML 文档中更新一些标签文本。

标签被命名为supName1supName2

我有一个 for 循环,它遍历 List.Count 中的所有 XML 节点。

var n = list.Count;
        for (int i = 0; i < n; i++)

我需要更新每个 list.count 的标签文本,但我不知道如何引用标签。

根据我的 VBA 经验,它类似于 "supName"+i 但我无法为 C# 弄明白。

我试过以下;

var label = (Label)Controls["supName" + i];

但是当尝试按如下方式使用它时它返回 null;

label.Text = list[i].Attributes["name"].Value;

最佳答案

您需要通过标签的 Name 属性在表单中找到标签,但必须记住,它们可能放置在子控件上,而不是表单本身。这里对你有帮助的方法是ControlCollection.Find()您可以调用表单的 Controls 属性,该属性表示表单的 ControlCollection:

int n = list.Count;
for(int i=0; i<n; i++)
{
    // the second argument "true" indicates to 
    // search child controls recursivly
    Label label = Controls.Find($"supName{i}", true).OfType<Label>().FirstOrDefault(); 
    if (label == null) continue; // no such label, add error handling
    label.Text = list[i].Attributes["name"].Value;
}

关于c# - 遍历标签并更改值 c#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42072198/

相关文章:

c# 将http请求发送到azure存储

c# - 在 CaSTLe Windsor 中,如何覆盖使用 FromThisAssembly() 注册的类型

c# - ASP.NET Core 使用中间件修改 HTTP 请求 header

c# Panel with auto scroll - 在控件焦点上重置滚动条位置

c# - 使用 Linq 在运行时确定表

c - 如何使用循环访问矩阵的元素

java - 不兼容的类型 : Card cannot be converted to java. lang.String

c# - 如何在 .NET Core 中获取操作系统、计算机处理器信息、总 RAM、正在使用的 RAM 等?

Java、MongoDB 将游标转换为数组

vb.net - Form.ShowDialog() 不显示表单