Relying on the exact structure of the markup is a very brittle approach. As soon as you touch the markup, you'll have to go back through your code to update the number of
.Parent
nodes you traverse.
A better approach would be to walk up the control tree, looking for a container of a specified type:
public static class ControlTreeExtensions
{
public static TContainer ClosestContainer<TContainer>(this Control theControl) where TContainer : Control
{
if (theControl == null) throw new ArgumentNullException("theControl");
Control current = theControl.NamingContainer;
TContainer result = current as TContainer;
while (current != null && result == null)
{
current = current.NamingContainer;
result = current as TContainer;
}
return result;
}
}
You can then use this method to find the closest container of a particular type, remembering to check for
null
if a container of the specified type is not found:
protected void txt_consumption_TextChanged(object sender, EventArgs e)
{
TextBox txtcons = (TextBox)sender;
GridViewRow currentRow = txtcons.ClosestContainer<GridViewRow>();
if (currentRow != null)
{
calculateperdozen(currentRow);
}
}