Results 1 to 5 of 5

Thread: Make label ID dynamic

  1. #1
    Hyperactive Member
    Join Date
    Jul 10
    Posts
    278

    Make label ID dynamic

    Hello,

    Code:
    int i;
    i = 5;
    lblName + i .text = "Test";
    That's what i need in brevity.
    Plz help me to solve this issue.
    Thanks in advance.

  2. #2
    .NUT jmcilhinney's Avatar
    Join Date
    May 05
    Location
    Sydney, Australia
    Posts
    80,785

    Re: Make label ID dynamic

    You can get a control by name from the Controls collection of its parent, e.g.
    vb.net Code:
    1. For i = 1 To 5
    2.     Controls("Label" & i).Text = "Label" & i
    3. Next
    The item is returned as a Control reference, so if you're just using members of the Control class, e.g. Text, then that's fine. If you want to access a member of that specific type of control then you should cast as that type. Indeed, if you have Option Strict On, as you should, then you will be required to cast.
    Last edited by jmcilhinney; Sep 27th, 2012 at 04:24 AM.

  3. #3
    Hyperactive Member
    Join Date
    Jul 10
    Posts
    278

    Re: Make label ID dynamic

    Thank you, I tried make code:

    [Code]
    int i = 1;
    Controls["lblFP" + i].Text = "Test";
    [Code/]

    Give me error "Object reference not set to an instance of an object." i try adjust code to run but need help.

  4. #4
    .NUT jmcilhinney's Avatar
    Join Date
    May 05
    Location
    Sydney, Australia
    Posts
    80,785

    Re: Make label ID dynamic

    Ah whoops, I forgot I was C# land and posted VB code. It seems that you successfully translated it though. As for the error message, that means that there is no control on your form with that Name.

  5. #5
    Hyperactive Member
    Join Date
    Jul 10
    Posts
    278

    Re: Make label ID dynamic

    Hi,
    I catch where is the problem, i am using groupbox this code can't find any object on groupbox must put the label on form direct and use it.

    Do there any idea to surmount this problem?

  6. #6
    .NUT jmcilhinney's Avatar
    Join Date
    May 05
    Location
    Sydney, Australia
    Posts
    80,785

    Re: Make label ID dynamic

    Please read what I posted.
    You can get a control by name from the Controls collection of its parent
    If the GroupBox is the parent of the Label then you have to use the Controls collection of the GroupBox, not the form. This is exactly why I prefer not to post code: people just copy the code and don't actually read.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •