Reputation: 296
I have multiple labels (label1,label2,label3,etc) I want to loop through them programmatically. I have done this in vb.net but the same does not work in 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#
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
Upvotes: 0
Views: 858
Reputation: 1113
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];
Upvotes: 2
Reputation: 1679
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
}
}
Upvotes: 0
Reputation: 382
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;
}
Upvotes: 0