Reputation: 6657
Working with a GridView in C# (ASP.NET) and I'm trying to iterate over a single row. Normally it wouldn't be too difficult if I could extract the text in each cell:
string text = SecGrpGridView.Rows[0].Cells[i].Text;
However, some of the fields in my row contain Labels and I believe the only way to extract the value is using FindControl() and casting it to a Label:
Label myLabel = (Label)SecGrpGridView.Rows[0].Cells[i].FindControl("Label5");
string text = myLabel.Text;
As you can see, the second example I needed to know the ID of my label so it makes it difficult to iterate over unless I have sequentially named labels. I know that a future need will be to add more columns to my row so I'm looking for a way to iterate over this row without having to name the labels sequentially. (ie 'Label1', 'Label2', 'Label3') Is there a better way to go about this?
Upvotes: 0
Views: 1634
Reputation: 2634
You can gather all the Labels in GridView by using the following code
public static List<Label> FindLabelRecursive(Control root)
{
List<Label> labels = new List<Label>();
if (root is Label)
{
labels.Add(root as Label);
return labels;
}
foreach(Control c in root.Controls)
{
if (c is Label)
{
labels.Add(c);
}
else
{
List<Label> childLabels = FindLabelRecursive(c);
labels.AddRange(childLabels);
}
}
return labels;
}
Then do you processing based on the labels returned.
Upvotes: 1