简体   繁体   English

我有多个标签,该如何在C#中以编程方式遍历它们

[英]I have multiple labels how do I go to loop through them programmatically in C#

I have multiple labels (label1,label2,label3,etc) I want to loop through them programmatically. 我有多个标签(label1,label2,label3等),我想以编程方式遍历它们。 I have done this in vb.net but the same does not work in C#. 我已经在vb.net中完成了此操作,但在C#中却无法正常工作。

I get the error 我得到错误

An explicit conversion exist. 存在显式转换。

What is the right way to do this? 什么是正确的方法?

Below is the code for VB.net which works but it does not for C# 以下是适用于VB.net的代码,但不适用于C#

C# C#

UserControl uc1 = tabPage1.Controls["lblprice" + control];

vb.net vb.net

Do While count < 18

        Dim uc1 As UserControl = TabPage3.Controls("AbsenceUC" & count.ToString & "")
        Dim TxtEmployeeID As TextBox = uc1.Controls("txtEmpId")
        Dim TxtAbsenteeCode As TextBox = uc1.Controls("TextBox2")
        Dim txttext As String = TxtEmployeeID.Text
Loop

You can loop through all of the labels on that form with this code: 您可以使用以下代码遍历该表单上的所有标签:

var labels = tabPage1.Controls.OfType<Label>();
foreach (Label lbl in labels)
{
    // lbl.Content = "Do stuff here..."
}

The error is because you need to cast the result. 该错误是因为您需要强制转换结果。

Label uc1 = (Label)tabPage1.Controls["lblprice" + control];

You can loop over all controls like this 您可以像这样遍历所有控件

 foreach (Control c in this.Controls)
  {
            if (c is Label) // Here check if the control is label 
            {
                c.BackColor = Color.Red; // you code goes here

            }
  }
while(count < 18)
{      
    //Find string key 
    var uc1 = tabPage3.Controls.Find("AbsenceUC", true).Where(x=> YOUR WHERE CLAUSE HERE).Single();

    //Cast your controls to TextBoxes
    TextBox TxtEmployeeID = uc1.Controls.Find("txtEmpId", true).Single() as TextBox;
    TextBox TxtAbsenteeCode = uc1.Controls.Find("TextBox2", true).Single() as TextBox;
    String txttext = TxtEmployeeID.Text;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM