-2

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.

stuartd
  • 70,509
  • 14
  • 132
  • 163
Ismael
  • 11
  • 1
  • 4
  • 1
    Tag is neither int nor string. What do you store in tag. What value? What type? Show the code, please. –  Jun 18 '21 at 16:25
  • 1
    Yes, as @OlivierRogier said. int Nbancos = (int) Gb_Bancos.Tag; should work if Tag contains a number. – Steve Jun 18 '21 at 16:27

1 Answers1

1

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

int nb = Convert.ToInt32(Gb_Bancos.Tag);

but do you know that you can avoid all this using

int nb = Gb_Bancos.Controls.OfType<TextBox>().Count();

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.

Steve
  • 213,761
  • 22
  • 232
  • 286
  • The property Tag has always the number of textboxes in Gb_Bancos (a groupbox). It's created with zero. – Ismael Jun 18 '21 at 18:38
  • Steve. I tried your suggestion and it worked. Thank you! Your second suggestion also works. – Ismael Jun 18 '21 at 18:39