gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 19:48:52 25 4
gpt4 key购买 nike

我希望从 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com