I'm programming in C# in Visual Studio and I'm using a Groupbox in which I insert a number of TextBoxes, depending on data I retrive from the database. As I don't know how many Textboxes there are, I store the amount in the Tag Property of the Groupbox. In another routine I use this value. But I'm receiving an error message. First case: If I try to use this value directly:
int Nbancos = Gb_Bancos.Tag;
Visual Studio says that "it's not possible to convert inplicitly type object in int." Second case: If I make an explicit convertion:
int Nbancos = (int) Gb_Bancos.Tag;
There's no error during compiling but when I run the program I receive the error message: "System.InvalidCastException:specified conversion is not valid". Third case: I tried a conversion to string:
string Nb = (string) Gb_Bancos.Tag;
int NBancos = int.Parse(Nb);
And I received the same error message above. I know it must be a silly error, but please, can anyone help me? What am I doing wrong? Thanks.
If we can assume that the Tag property is always initialized with a number (even when there are no TextBoxes) then you can simply write
but do you know that you can avoid all this using
of course this approach is not faster than the previous one but I think it will save a lot of works on that Tag property.