我有多个标签,如何在 C# 中以编程方式遍历它们
I have multiple labels how do I go to loop through them programmatically in C#
我有多个标签(label1、label2、label3 等),我想以编程方式遍历它们。我在 vb.net 中完成了此操作,但同样在 C# 中不起作用。
我收到错误
An explicit conversion exist.
正确的做法是什么?
下面是适用于 VB.net 的代码,它适用于 C#
C#
UserControl uc1 = tabPage1.Controls["lblprice" + control];
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
您可以使用以下代码遍历该表单上的所有标签:
var labels = tabPage1.Controls.OfType<Label>();
foreach (Label lbl in labels)
{
// lbl.Content = "Do stuff here..."
}
错误是因为你需要转换结果。
Label uc1 = (Label)tabPage1.Controls["lblprice" + control];
你可以像这样遍历所有控件
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;
}
我有多个标签(label1、label2、label3 等),我想以编程方式遍历它们。我在 vb.net 中完成了此操作,但同样在 C# 中不起作用。
我收到错误
An explicit conversion exist.
正确的做法是什么?
下面是适用于 VB.net 的代码,它适用于 C#
C#
UserControl uc1 = tabPage1.Controls["lblprice" + control];
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
您可以使用以下代码遍历该表单上的所有标签:
var labels = tabPage1.Controls.OfType<Label>();
foreach (Label lbl in labels)
{
// lbl.Content = "Do stuff here..."
}
错误是因为你需要转换结果。
Label uc1 = (Label)tabPage1.Controls["lblprice" + control];
你可以像这样遍历所有控件
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;
}