Solved

Array of controls in VB.NET

Posted on 2011-09-12
29
253 Views
Last Modified: 2012-05-12
Hello all,

I have to do a piece of software for a restaurant. The restaurant has 200 tables and the owner is asking me to place 200 little textboxes (with the number 1..200). These textboxes will be background colored as GREEN (FREE TABLE) and RED (Table with customers on it). He also wants to show the money been spent on that table when he clicks on the little textbox.

My problem is that I can do this really easy with VB6, but I have no clue on how to use a control (textbox) with the same name, and different index in .NET

Please help! :P

Thanks

Paula
0
Comment
Question by:pvg1975
  • 9
  • 8
  • 6
  • +2
29 Comments
 
LVL 75

Expert Comment

by:käµfm³d 👽
ID: 36525810
You can create an array of controls in this manner:

Dim tables(200) As TextBox

Open in new window


You might find lists easier to work with, though:

Dim tables As New System.Collections.Generic.List(Of TextBox)(200)

Open in new window

0
 
LVL 75

Assisted Solution

by:käµfm³d 👽
käµfm³d   👽 earned 50 total points
ID: 36525820
P.S.

You can index a List the same way you index an array. Also, The space is requested in the above, but the tables themselves (TextBoxes) are not. You could easily instantiate the slots of whichever you pick by doing something like:

Array
For i As Integer = 0 To 199
    tables(i) = New TextBox()
Next

Open in new window


List
For i As Integer = 0 To 199
    tables.Add(New TextBox())
Next

Open in new window

0
 
LVL 17

Accepted Solution

by:
nepaluz earned 300 total points
ID: 36525973
You can actually have different names for the textboxes and reference this in the click event, e.g
Dim tbList As New List(Of TextBox)
For x = 1 To 199
    Dim tBox As New TextBox With {.Name = "Table" & x, .Text = "Table" & x}
    AddHandler tBox.Click, AddressOf xTable
    tbList.Add(tBox)
Next

Open in new window

And in the click handler
Sub xTable(ByVal sender As TextBox, ByVal e As System.EventArgs)
    Dim TableName = sender.Name
    'here do your thang!
End Sub

Open in new window

0
MIM Survival Guide for Service Desk Managers

Major incidents can send mastered service desk processes into disorder. Systems and tools produce the data needed to resolve these incidents, but your challenge is getting that information to the right people fast. Check out the Survival Guide and begin bringing order to chaos.

 

Author Comment

by:pvg1975
ID: 36526002
Thanks guys, but how do I position the 200 textboxes on the screen? I gotta have 10 rows of 20 textboxes each.

Thanks.
0
 

Author Comment

by:pvg1975
ID: 36526011
Is there any X-Y value I can use?
0
 
LVL 17

Expert Comment

by:nepaluz
ID: 36526023
First, you have to get the size of each textbox (get or set ....?). Eitherway, you need to know the size of the textbox.
0
 
LVL 83

Expert Comment

by:CodeCruiser
ID: 36526145
Do you have to use textboxes? How about grid? Listbox? If you have to then you try this FlowLayout control


http://www.codeproject.com/KB/miscctrl/CSharpFlowLayoutPanel.aspx
0
 
LVL 40

Assisted Solution

by:Jacques Bourgeois (James Burger)
Jacques Bourgeois (James Burger) earned 150 total points
ID: 36526829
nepaluz has the right way of associating the TextBoxes with an event that will handle them all in the same procedure.

CodeCruiser has it with the FlowLayoutPanel control.

I would add that if you need to pair the TextBoxes with something else, say a label to ID each TextBox, first create a UserControl, use the FlowLayoutPanel to put them on the screen, and the AddHandler to associate them with a Click procedure that will handle the color.
0
 

Author Comment

by:pvg1975
ID: 36527119
Yes, but when I place the code the textboxes wont draw, and I dont know how to align them and place them on the right place of the screen
0
 
LVL 40

Assisted Solution

by:Jacques Bourgeois (James Burger)
Jacques Bourgeois (James Burger) earned 150 total points
ID: 36527299
In order for a TextBox that you create dynamically to appear on the screen, you need to make it visible and incorporate it into some kind of container.

This is why there has been a few suggestions to use a FlowLayoutPanel. This control takes care of displaying the controls in columns or in rows, depending on how you set its properties. Look for it in the documentation and will se an example of its use.
0
 
LVL 17

Expert Comment

by:nepaluz
ID: 36528416
We do not have your form details,and neither of your programing knowledge so we can only suggest solutions to the questions you ask. If the controls are not showing, you probaby have not set their parent, do that in the declaration
Dim tBox As New TextBox With {.Name = "Table" & x, .Text = "Table" & x, .Parent = "YourParentObjectHERE"}

Open in new window

0
 

Author Comment

by:pvg1975
ID: 36529892
Hi Nepaluz, Im new at VB.NET Winforms, I only have experience in ASP.NET.

Im trying to make it work with your examples now. Sorry about this and thanks.

Paula.
0
 

Author Comment

by:pvg1975
ID: 36530198
I tried using a tablelayoutpanel with 10 columns and 20 rows, and used this code:

      For t = 1 To 10
            For x = 1 To 20
                MyTable.Controls.Add(Label1, t, x)
            Next
        Next

But it only draws one Label
0
 
LVL 17

Expert Comment

by:nepaluz
ID: 36530279
Dim tbList As New List(Of TextBox)
For t = 1 To 10
      For x = 1 To 20
          Dim tBox As New TextBox With {.Name = "Table" & x, .Text = "Table" & x}
          AddHandler tBox.Click, AddressOf xTable
          MyTable.Controls.Add(tBox, t, x)
          tbList.Add(tBox)
      Next
Next

Open in new window

0
 

Author Closing Comment

by:pvg1975
ID: 36530289
Thanks!

I made it work like this:

        Dim Counter As Integer
        For t = 0 To 19
            For x = 0 To 9
                Counter = Counter + 1
                Dim tBox As New TextBox With {.Name = "Table" & Counter, .Text = Counter}
                TABLA.Controls.Add(tBox, x, t)
            Next
        Next

I had no idea about these stuff. Thanks again guys.
0
 

Author Comment

by:pvg1975
ID: 36530308
Here's the final one

        Dim Counter As Integer
        For t = 0 To 19
            For x = 0 To 9
                Counter = Counter + 1
                Dim tBox As New Label With {.Name = "Table" & Counter, .Text = Counter, .BackColor = Color.Green, .ForeColor=Color.White}
                TABLA.Controls.Add(tBox, x, t)
            Next
        Next

It was a label, not a textbox.... sorry about that.
0
 
LVL 17

Expert Comment

by:nepaluz
ID: 36530318
actually, you will get dupicate label names there, try
Dim tbList As New List(Of Label)
For t = 1 To 10
      For x = 1 To 20
          Dim tBox As New Label With {.Name = "Table" & t & x, .Text = "Table" & x & " Row" & t, .Parent = "YourParentObjectHERE"}
          AddHandler tBox.Click, AddressOf xTable
          MyTable.Controls.Add(tBox, t, x)
          tbList.Add(tBox)
      Next
Next

Open in new window

Dont forget to set the parent to a control! (andyou willnot have these in a perfect row/column order!)
0
 

Author Comment

by:pvg1975
ID: 36530447
Thanks Nepaluz!

Is it possible to manage a click event on each label? For example, retrieve the text on the label once the label is clicked?

Thanks again :)

Paula
0
 
LVL 17

Expert Comment

by:nepaluz
ID: 36530533
Sub xTable(ByVal sender As Label, ByVal e As System.EventArgs)
    Dim TableName = sender.Text
End Sub

Open in new window

Plus a host of other things ....
0
 

Author Comment

by:pvg1975
ID: 36530780
Nepaluz, Im totally lost.... I will open a new question regarding this one.

Thanks!
0
 
LVL 75

Expert Comment

by:käµfm³d 👽
ID: 36531011
This suggestion:

Sub xTable(ByVal sender As Label, ByVal e As System.EventArgs)
    Dim TableName = sender.Text
End Sub

Open in new window


relies on implicit conversions, which is generally regarded as improper coding style. This code will not even compile if you have Option String set to On. It's better to match the actual delegate signature, which in this case calls for the first parameter to be of type Object. Given this, you would end up with something more along the lines of:

Sub xTable(ByVal sender As Object, ByVal e As System.EventArgs)
    Dim lbl As Label = DirectCast(sender, Label)

    Dim TableName = lbl.Text
End Sub

Open in new window

0
 
LVL 75

Expert Comment

by:käµfm³d 👽
ID: 36531015
..if you have Option String set to On.

**Option Strict
0
 
LVL 17

Expert Comment

by:nepaluz
ID: 36531137
Hmmm! kaufmed, you should look more closely, the code says
ByVal sender As Label

Open in new window

There is no implicit conversion there, is there?
0
 
LVL 75

Expert Comment

by:käµfm³d 👽
ID: 36531272
There is no implicit conversion there, is there?
There most assuredly is an implicit conversion there. Pity you don't know where it is. I gave a glaring hint in an earlier comment.
0
 
LVL 40
ID: 36531427
This is debatable, but I would go with nepaluz.

This is my view. I might be wrong.

At runtime, a parameter is but a pointer. The framework does not care or even perform implicit conversions. It passes the pointer and triggers an Exception if the block of memory passed is not compatible with the object expected.

Under the cover, Implicit conversion does not exists for most reference variables, because a reference variable is but a pointer. Explicit conversion exists for value objects, and a only a few reference objects that have been built. Whenever you can use DirectCast, there is no conversion involved. If you need to use CType or Convert, when Option Strict is on, then there is an implicit conversion under the hood when it is off.

Option Strict is a just a compiler option that checks over your shoulder as you code. If the application compiles on Option Strict, this means that after analysis, the compiler has determinde that there is no "danger" in using a given type in a given situation.

But we disgress, let us thing about pvg that is lost by all that stuff. We are here for him more than we are there to have interesting intellectual discussion between ourselves.



0
 
LVL 75

Expert Comment

by:käµfm³d 👽
ID: 36531598
@JamesBurger

While I respect your opinion, I contend that it is important for any new coder to understand the fundamentals of a language. Knowing about implicit/explicit conversions is just as important as know the difference between ByVal vs ByRef. Implicit conversions can lead to subtle bugs in code--IIRC correctly, this is why C# doesn't permit it to the level that VB does. It was not my intent to have a philosophical discussion as to why choose one over the other. I'm simply trying to inform pvg1975 of potential issues with a suggestion he received here. It is of no merit to anyone to provide a solution and not discuss intricacies of said solution--unless the solution is overt. In this case, I don't believe the intricacy was apparent.

P.S.

Feel free to question any of my posts. I like being kept honest  = )
0
 
LVL 17

Expert Comment

by:nepaluz
ID: 36531736
this is why C# doesn't permit it to the level that VB does
All coins have two faces, and there must be a reason why you only get a warning rather than an error with implicit conversion in VB.NET (when you have clicked the correct boxes). In my experience (and I am a newbie to in accounts), Option Strict On IS a hindrance rather than a failsafe.

Back to the case at hand, there are no intricacies worthy of discussion in the solution I offered (and was accepted). In any case, I made it a point to declare reference as a Label (thus did not need to type / direct cast it to avoid implicit conversion). And the idea of questioning contributors' solution suggestions on the flimsy pretext(s) of being kept honest certainly does not rub well with myself.
0
 
LVL 40
ID: 36531843
And I also like honesty and clarity. So...

Just as you, I feel that it is important for a new coder to know about those things. You have read some of my other posts, I am the kind of guy who usually goes into details to explain the whys instead of only throwing 3 lines of code.

But 90% of my work nowadays is as a trainer, and this goes into my answers here. "Déformation professionnelle" we call it in French. One of the qualities of a good trainer is to be able to see the limits of his students. Things have to come one by one, and sometimes in a specific order when you show people how to use a new programming language. I think more as a trainer than as a programmer when I am here.

I might be wrong, but with my 14+ years of experience in giving VB courses let me think the following.

If you read the previous posts, you will find that pvg1975 is lost: "Nepaluz, Im totally lost.... I will open a new question regarding this one." And he did not come back afterward. That means that he was lost well before we started discussing the whys and hows of implicit conversions. AddHandler is not an easy concept to grasp for a beginner, who is just starting to cope with events. I am almost certain that pvg1975 did not see the AddHandler and the event procedure. He became "totally lost" when the event came back from what could well be nowhare to him. For a beginner, a Sub that does not have Control_Click in its name, and does not have have a Handles clause either, this is not an event. So he probably wondered what that code was doing there.

Instead of helping him on that matter, we started (I included), to talk about Option Strict, implicit conversions, signatures,  even Option String :-) to mix up things a little more. Most of it stuff that is new to somebody who comes from VB6. Poor pvg1975. We went on our rambling and left it in the ditch.

It is important for a new coder to understand the fundamentals of a language, but we failed him here. Too much "Expert" in our stuff to help someone who has the difficult task of going from VB6 to VB.NET developing something for someone that looks like a customer.

0
 
LVL 40
ID: 36531963
@nepaluz.

VB is configured by default so that amateur programmers are not completely lost. That is why a lot of things are not set in stone as they are in C#. Also, C# programmers usually come from a C++ or Java background, they are used to strict coding. A lot of programmers who come from VB6 have not acquired that discipline, so being able to configure the thing as you want can ease out their transition in the new world.

If you know all the little tricks, you can make VB as hard to break as C# (except for case sensitivity, and I really do not care about that one).

Project projerties... Compile. At the bottom of the screen. You can set implicit conversions as being errors. Even better, set everything as being an error. You will still get warnings from time to time for things that are of minor importance. But for the important ones, your code won't compile unless you have clean code.

The more you go in this environment, the more you find out that even things that look as a hindrance at first are great time savers because they catch potential bugs before you even compile. They make things harder as the beginning because you have so much to learn and understand as once. So if you are not programming for professional work, you can let go a bit at the start, since VB enables one to do that. But for those who wants to have fun programming, all those littles options that seems at first make things more complex will, on the contrary, make programming a lot more fun... even professionnally.

I would better add a type conversion here and there when I first write the code than having to spend hours and even days trying to pinpoint a subtil bug.
0

Featured Post

Master Your Team's Linux and Cloud Stack!

The average business loses $13.5M per year to ineffective training (per 1,000 employees). Keep ahead of the competition and combine in-person quality with online cost and flexibility by training with Linux Academy.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
Help with adding DLL file in Windows project 20 40
vb.net winforms sizing/resolution? 4 42
Can't disable touch pad on Windows 10 computer 16 45
parsing JSON help 1 20
More often than not, we developers are confronted with a need: a need to make some kind of magic happen via code. Whether it is for a client, for the boss, or for our own personal projects, the need must be satisfied. Most of the time, the Framework…
A long time ago (May 2011), I have written an article showing you how to create a DLL using Visual Studio 2005 to be hosted in SQL Server 2005. That was valid at that time and it is still valid if you are still using these versions. You can still re…
The Email Laundry PDF encryption service allows companies to send confidential encrypted  emails to anybody. The PDF document can also contain attachments that are embedded in the encrypted PDF. The password is randomly generated by The Email Laundr…
I've attached the XLSM Excel spreadsheet I used in the video and also text files containing the macros used below. https://filedb.experts-exchange.com/incoming/2017/03_w12/1151775/Permutations.txt https://filedb.experts-exchange.com/incoming/201…

840 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question