I added the DataKeyNames attribute to the GridView to ensure unique identifiers for each row are properly managed. Then, I used the null-conditional operator (?.
) when accessing the TextBox controls, like this: string NumEmpleados = (row.FindControl("TextNumEmpleado") as TextBox)?.Text;
. This way, if the TextBox is not found, the code won’t try to access the .Text
property and will return null instead, avoiding the exception.