-
Control Array in VS 2010
I'm trying to lern VS 2010 from VB 6 and one of the things i'm hawing a problem whid is control array.
In vb 6 if you create a text box it's named "Text1" and if you yust copy it and paste it it renames to "Text1(0)" and the new one's name is "Text1(0)"
and the code would lock like this
Code:
Private Sub CMD1_Click()
i=0
do while i <=3
R = Int(6 * Rnd + 1)
Text1(i).Text = S
i=i+1
loop
End Sub
then it would print for each loop the random result in one of the text boxes corresponding to i.
How do i do this in VS 2010?
-
Re: Control Array in VS 2010
it sould be "Text1(0)" and Text1(1)" sorry for dubble post dident find the edit button
-
Re: Control Array in VS 2010
Control Arrays no longer exist in .NET because they aren't needed at all. You can just cycle through any grouping of controls; and controls are already members of control groups. Your code would look something like this in .NET:
Code:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim r As New Random
Dim i As Integer
For Each c As TextBox In Me.Controls.OfType(Of TextBox)()
i = r.Next(6) + 1
c.Text = i.ToString
Next
End Sub
-
Re: Control Array in VS 2010
i = r.Next(6) + 1
I think that should be:
i = r.Next(7)
but I forget how the VB6 rnd function worked.
-
Re: Control Array in VS 2010
in the code you provided how do i know in whitch textbox the anser vill be writen?
-
Re: Control Array in VS 2010
c is the textbox, so c.Name would show you the name of the textbox. The code Jenner provided would loop through all the textboxes on the form (not counting those that are in a container control on the form). If you wanted to interact with one specific textbox, that would be somewhat different, but the code shown would replicate the code you have, except that there is some difference between Rnd and the Random class in that the Random class is vastly easier to firgure out the range of the random number.
-
Re: Control Array in VS 2010
Control arrays is one of the things I do a lot in VB6, guess I could just group controls inside panels and acces them like this then...? :confused:
Code:
' random
For Each c As TextBox In Me.Panel1.Controls.OfType(Of TextBox)()
i = r.Next(6) + 1
c.Text = i.ToString
Next
i = 0 ' increment numbers to textboxes in panel2
For Each c As TextBox In Me.Panel2.Controls.OfType(Of TextBox)()
i = i + 1
c.Text = i.ToString
Next
The textboxes are filled in the reverse order they were added at design time! :rolleyes:
-
Re: Control Array in VS 2010
This is the whole code i'm trying to convert from vb 6
Code:
T = 0 ' is the sum of all dice's
R = 0 'R is a random number betwene 1-6
i = 1
q = antal 'q is how meny dice's i use and increases on a 6
P = 0 'is used to emty the textboxes
sex = 0 ' is used to count hom meny times the dice is 6
Do While i <= q
R = Int(6 * Rnd + 1)
S = R
Text2(i - 1).Text = S
If R = 6 Then
q = q + 1
sex = sex + 1
ElseIf R < 6 Then
T = T + R
i = i + 1
End If
Loop
i'm also trying to get it to wurk whid this
Code:
Private Sub SKILL1_PLUS_Click(C As Integer)
If SKILL(C).Text = "" Then
ElseIf SKILL(C).Text < 5 Then
SKILL(C).Text = 5
Poäng = Poäng - 1
ElseIf SKILL(C).Text > 4 And SKILL(C).Text < 10 Then
SKILL(C).Text = SKILL(C).Text + 1
Poäng = Poäng - 1
ElseIf SKILL(C).Text > 9 And SKILL(C).Text < 15 Then
SKILL(C).Text = SKILL(C).Text + 1
Poäng = Poäng - 2
ElseIf SKILL(C).Text = 15 Then
ElseIf SKILL(C).Text < FÄRD_GRUND(C).Text Then
SKILL(C).Text = FÄRD_GRUND(C).Text
End If
POÄNG_RÄK.Text = Poäng
End Sub
its the same prog but different funktions if you want i can upploade the project uncompiled so you can get a feal for what i want to do or i can take pictures.
-
Re: Control Array in VS 2010
Control arrays are not supported in VB.NET because there are better alternatives to it.
Though there are many ways to it,
In the simplest form, you can easily get the effect of a control array like this.
vb.net Code:
Dim MyTextBoxes() As TextBox = {TextBox1, TextBox2, TextBox3, TextBox4, TextBox5, TextBox6}
Do that at the form level, and you should be able to use the MyTextBoxes just like you used control arrays.
-
Re: Control Array in VS 2010
ok how do i call it so it increases whid i in a code like this
Code:
Public Class Form1
Dim q As Integer
Dim i As Integer
Dim r As Integer
Dim tot As Integer
Dim MyTextBoxes() As TextBox = {TextBox1, TextBox2, TextBox3, TextBox4, TextBox5, TextBox6}
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Randomize()
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
q = 1
i = 1
tot = 0
Do While i <= q
r = Int(Rnd() * 6) + 1
tot = tot + r
If r = 6 Then
q = q + 1
ElseIf r < 6 Then
MyTextBoxes(i) 'getting a error "Expression is not ametod."
i = i + 1
End If
Loop
TextBox7.Text = tot
End Sub
End Class
-
Re: Control Array in VS 2010
Code:
MyTextBoxes(i).Text = i.ToString
-
Re: Control Array in VS 2010
Whid that and MyTextBoxes(i).Text = r.ToString i get this error when i press the button "Use the "new" keyword to create an object instance."
-
Re: Control Array in VS 2010
Can you show the declaration of MyTextBoxes? Did you declare as I suggested?
-
1 Attachment(s)
Re: Control Array in VS 2010
Araced a rar file so you can hawe a lock at it if you fel for it its done in VS 2010
Code:
Public Class Form1
Dim q As Integer
Dim i As Integer
Dim r As Integer
Dim tot As Integer
Dim MyTextBoxes() As TextBox = {TextBox1, TextBox2, TextBox3, TextBox4, TextBox5, TextBox6}
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Randomize()
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
q = 1
i = 1
tot = 0
Do While i <= q
r = Int(Rnd() * 6) + 1
tot = tot + r
If r = 6 Then
q = q + 1
ElseIf r < 6 Then
MyTextBoxes(i).Text = i.ToString
i = i + 1
End If
Loop
TextBox7.Text = tot
End Sub
End Class
get the same error if i change it to MyTextBoxes(i).Text = r.ToString
-
Re: Control Array in VS 2010
A couple points:
1) Get away from using Randomize and Rnd. Those are legacy VB6 methods which have been replaced, and greatly improved, by the Random object. Jenner showed an example of using the Random object back in post #3. There is no longer any need for the Randomize call, and it shouldn't be made. Random.Next is considerably easier than Rnd, as you just specify the range that you want a random value to fall into, and you get it, without the multiplication and addition of 1.
2) Turn Option Strict ON. You will get lots of errors when you do because you have a bunch of implicit conversions in there which will have to be turned into explicit conversions. However, there are good reasons to do this. For one thing, you will catch lots of subtle bugs that would otherwise just cause you trouble. Another reason is that the code will run faster. Those implicit conversions are shorter to write, but they take more compiler time to perform.
-
Re: Control Array in VS 2010
Quote:
Originally Posted by
Edgemeal
Control arrays is one of the things I do a lot in VB6, guess I could just group controls inside panels and acces them like this then...? :confused:
What's the panel for? The form has a controls collection, too.
Quote:
The textboxes are filled in the reverse order they were added at design time! :rolleyes:
Don't rely on that. The textboxes are added based on the way they were added to the controls collection which can be found in the .designer.vb file for the form.
-
Re: Control Array in VS 2010
Quote:
Originally Posted by
Pradeep1210
Code:
MyTextBoxes(i).Text = i.ToString
Could you show an example how you are getting that to work becasue I get the same error as the OP does in post #12.
One way I got it to work was like this, but if its anything like VB6 you avoid using strings whenever possible as they are slow.
Code:
' - VB10 -
Public Class Form1
'Form contains 3 text boxes named: TextBox1, TextBox2 and TextBox3
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
' add some text to each text box
For I As Integer = 1 To 3
Me.Controls.Item("TextBox" & I).Text = "I'm Textbox #" & I.ToString
Next
End Sub
End Class
-
Re: Control Array in VS 2010
In that case, you are using a string that is a key into a Dictionary. Is that slow? Well, it is slower than using an integer, but it may not be all that slow, depending on how the indexing of the Dictionary works. In general, I don't prefer it either, though.
You should not be getting that error using Pradeep's code, but it has to do with how you set up the MyTextBoxes array or list. Drago87 made a mistake here:
Code:
Public Class Form1
Dim q As Integer
Dim i As Integer
Dim r As Integer
Dim tot As Integer
Dim MyTextBoxes() As TextBox = {TextBox1, TextBox2, TextBox3, TextBox4, TextBox5, TextBox6}
The problem is that this line:
Dim MyTextBoxes() As TextBox = {TextBox1, TextBox2, TextBox3, TextBox4, TextBox5, TextBox6}
will run before the constructor (Sub New) runs. The first line in Sub New (you can find the constructor in the .designer.vb file for the form if you have not written a custom constructor) is a call to the function InitializeComponents. That function can also be found in .designer.vb. If you look at the function, you will see that it creates all of the controls and adds them to the form. However, by putting that declaration at form scope, it is running before the constructor, which means that it is running before InitializeComponents has created all those textboxes. Therefore, the textboxes are Nothing at that time, which is why you get the error.
To solve this, either add your own constructor (which has to call InitializeComponents as its first line) and set up the array there, or set up the array in the Load event.
-
Re: Control Array in VS 2010
OK thanks, these quick tests worked for me.
Code:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim MyTextBoxes() As TextBox = {TextBox1, TextBox2, TextBox3}
For i As Integer = 0 To 2
Debug.Print(MyTextBoxes(i).Name)
Next
End Sub
Or
Code:
Public Class Form1
Dim MyTextBoxes() As TextBox
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
MyTextBoxes = {TextBox1, TextBox2, TextBox3}
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
For i As Integer = 0 To 2
Debug.Print(MyTextBoxes(i).Name)
Next
End Sub
End Class
-
Re: Control Array in VS 2010
Ok ty for all the help only one last question if i want to use a button as a contoll array do i write it like this?
Code:
Public Class Form1
Dim MyButtons1() As Button
Dim MyTextBoxes() As TextBox
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
MyButtons1 = {Button1, Button2}
MyTextBoxes = {TextBox1, TextBox2, TextBox3, TextBox4}
End Sub
End Class
and call it like this
Code:
Private Sub MyButtons1_Click(c As Integer) Handles MyButtons1.Click
MyTextBoxes(c).Text = MyTextBoxes(c + 2).Text
End Sub
then it will copy whats in text box 3 to text box1 if i press button 1 and copy text box 4 to text box 2 if i press button 2
-
Re: Control Array in VS 2010
The signature of the click event handler is not correct, so it won't work like that. However, there is a better way:
1) Get rid of the button array, it isn't needed.
2) Double click on one of the buttons so that you get the proper signature of the handler, which will look something like this:
Code:
Public Sub Button1_OnClick(ByVal sender as Object, e as EventArgs) Handles Button1.Click
End Sub
I may have a few minor pieces of that wrong, such as the type of the e argument, and the names of the events, but that's why you let VS write it for you.
3) Now you can chain all the other buttons onto that one handler. See that Handles at the end? Just change that to:
Handles Button1.Click,Button2.Click,Button3.Click, and so forth.
Now the one handler routine will handle the click events for all of the buttons that you have attached it to. So how do you determine which button called it? That's what the sender argument is. In this case, you can do this:
Dim btn = DirectCast(sender,Forms.Button)
and voila, you have the button that raised the event. If you just left the name Button1, Button2, and so forth, you can strip the number off the right side of the button. Alternatively, all controls have a Tag property, which can hold anything. It is intended for things like this. You can put 1, 2, 3, and so forth as the Tag of each button. You would then be able to improve that last line to this:
Code:
MyTextBoxes(CInt(DirectCast(sender,Forms.Button).Tag)).Text =
MyTextBoxes(CInt(DirectCast(sender,Forms.Button).Tag) + 2).Text
A single line, though a mighty complex one. I am casting sender to a button, which it actually is, getting the Tag property, converting that to an integer, and using it as an index into the array of textboxes.
-
Re: Control Array in VS 2010
Where sould i put Dim btn = DirectCast(sender,Forms.Button)?
in Public Class Form1 or Private Sub Form1_Load
and i get errors whid that line
in publick class i get " 'sender' is not decleard. it maybe inaccessible due to the protection level" and "Type 'Forms.Button' is not defined."
and in form1_load i only get "Type 'Forms.Button' is not defined."
-
Re: Control Array in VS 2010
You're asking where you should cast the sender and you've already tried one of the two options and it said that sender wasn't defined. That should pretty much answer that question. As for the other, just use Button.
-
1 Attachment(s)
Re: Control Array in VS 2010
Ok this is the code
Code:
Public Class Form1
Dim MyTextBoxes() As TextBox
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click, Button2.Click
MyTextBoxes(CInt(DirectCast(sender, Button).Tag)).Text = MyTextBoxes(CInt(DirectCast(sender, Button).Tag) + 2).Text
End Sub
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim btn = DirectCast(sender, Button)
MyTextBoxes = {TextBox1, TextBox2, TextBox3, TextBox4}
End Sub
End Class
and ive attached a picture of the visual part
but when i try pressing the buttons i get "Object reference not set to an instance of an object." for the line "MyTextBoxes(CInt(DirectCast(sender, Button).Tag)).Text = MyTextBoxes(CInt(DirectCast(sender, Button).Tag) + 2).Text"
-
Re: Control Array in VS 2010
If you're going to be doing all these control clusters that all behave identically, then it's best to just make a single UserControl and repeat THAT on your forms. A simple UserControl is like a micro-form that holds other controls and the code for how they all work together. So you could make a single UserControl with 2 TextBoxes and a Button, and write the code for the button event in the UserControl.
Then you drop two or however many of those UserControls on your form you need.
-
Re: Control Array in VS 2010
Do you know of a good guide for it in VS 2010?
-
Re: Control Array in VS 2010
You don't really need a guide. Just add a UserControl to your project just like you add a Form. Design it just like you design a Form. Finally, add it to a Form just like you do any other Control. There's nothing different about it to what you have already done.
-
Re: Control Array in VS 2010
Right. Best to hack your way through it, then come on here and ask "Is there some more standardized or proper way to do this?" and we'll fill in the gaps. If you're looking at online examples of VS.NET code... ANY VS.NET code for that matter, things will start popping out. Go ahead, mimic it, emulate it, even if it doesn't make sense to you at first. We'll fill in the gaps for you, that's what we're here for.
You don't learn anything by not trying; so above all, that's what users of this forum want you to do first. You got a pretty good start going on, keep at it and gestalt of the language will come.
-
Re: Control Array in VS 2010
Ok i hawe now done a usercontrol and made it lock like i want it and coded it like i want.
How can i import and use it in my prog send info to and read fom it?
-
Re: Control Array in VS 2010
Go back to your form. If you look at your tool-box on the left, you'll see your UserControl now at the top of the list in a special area at the top with a gear as it's default icon. If it's not there, try clicking "Build->Build Solution" and see if it appears after that. Sometimes it takes closing and reopening the form for the development environment to realize you made a new UserControl and add it to the toolbox.
Then you just click and drag it onto your form. You talk to it like any other control, through it's properties and events. The UserControl has some basic properties that are part of it's class, but specific ones you'll have to make yourself. Same with events. It has some basic events as part of it's class, but if you want any custom events to trigger, you'll need to create them.
Examples:
Maybe my UserControl has a textbox that I want to be able to read and edit. I can make a property to read/write it:
Code:
Public Property MainText() As String
Get
Return TextBox1.Text
End Get
Set(ByVal value As String)
TextBox1.Text = value
End Set
End Property
It's really not that much typing, after you type "Public Property (name) As (type) and hit enter, Visual Studio will automatically create the Get and Set parts for you. You just need to type in the details; i.e. Get what? Set what?
Now in my form, all I need to do is:
Code:
UserControl1.MainText = "Blah"
Maybe my usercontrol has a button I want the main form to know when it gets pressed. I can make an Event like this and call it when I press the button on my UserControl. So, in my UserControl's code:
Code:
Public Event ButtonPressed(ByVal sender As Object, ByVal e As EventArgs)
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
RaiseEvent ButtonPressed(Me, e)
End Sub
Now, when it's on my form, I can make an EventHandler function like this:
Code:
Private Sub UserControl11_ButtonPressed(ByVal sender As Object, ByVal e As System.EventArgs) Handles UserControl11.ButtonPressed
'Do something
End Sub
Notice how I set up "sender" to be my UserControl in the above. I told it to use "Me" in the RaiseEvent statement.
UserControls are units of isolation as well. All the controls used to create the UserControl are only accessible from WITHIN the UserControl. It's like a Black-Box. To pipe anything into or out of it, you'll need to make some properties and events as I stated. Don't make properties and events for EVERYTHING, only make what you need to use. It cuts down on unnecessary code and makes for a better program. Only make tons of properties and events if you need them; for example, if you're making some special, full-featured control that you plan to use on many other projects.
-
Re: Control Array in VS 2010
Dident realy get how i would add it i hawe draged the gear to the form and it is placed next to the Menu strip icone.
The smal immage on the button left is the UserControl the one in the middle is my form as it is now and the one to the right is how i want it tobe after ive added 2 of maby 20 User controls.
-:EDIT:-
Found it used the wrong usercontol
-:EDIT2:-
I'm hawing a little problem sending
this is in my UserControl
Code:
Public Class UserControl1
Dim Poäng As Integer
Dim Points As Integer
Public Property Poäng_Send() As Integer
Get
Return Poäng
End Get
Set(ByVal value As Integer)
Poäng = value
End Set
End Property
Public Property Points_Send() As Integer
Get
Return Points
End Get
Set(ByVal value As Integer)
Points = value
End Set
End Property
End Class
i also need to know how i do to make it feel when i change the text in one of the textboxes
where sould i incert this code?
Code:
UserControl1.MainText = "Blah"
but in my case it sould be more like this i think
Code:
points=UserControl1.Points_Send
Ore i'm i miles away?
-
Re: Control Array in VS 2010
-
Re: Control Array in VS 2010
No, you're right on the money. You'd put that line wherever you need to get the value of your usercontrol on the form; just like if you were getting the value of any other control. Think of UserControls as "mini-sub-forms". You can make them all self-contained like a little black box so their code doesn't clutter up the form you're working with. It makes for less coding and a lot less headaches and maintenance.
-
Re: Control Array in VS 2010
I'm getting 2 errors whid this code
Code:
Private Sub UserControl11_ButtonPressed(ByVal sender As Object, ByVal e As System.EventArgs) Handles UserControl11.ButtonPressed
points = UserControl1.Points_Send
End Sub
Handles clause requiers a WithEvent variable defined in the containing type or one of its base types.
Reference to a non-shered member requires an object reference.
However if i use this code i only get the lime error
Code:
Private Sub UserControl11_MouseClick(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles UserControl11.MouseClick,
points = UserControl1.Points_Send
End Sub
-
Re: Control Array in VS 2010
The first error is because you didn't make an event called "ButtonPressed" in your UserControl. My example shows how to add one but it's only an example. You need to make your own events according to what you want your control to do. MouseClick works because ALL controls have a default MouseClick event. It fires when you click anywhere on the control.
You named your usercontrol "UserControl1". So when you put one on your form, it made a control named "UserControl11". This is just like all other controls. A TextBox is just called a "TextBox", but when you move it to your form, it makes the first one "TextBox1"
What the second error means, is you're referring to the GENERIC name of the control, and not the SPECIFIC control that is sitting on your form.
If you change the line to read: points = UserControl11.Points_Send
Then everything will be fine. Better yet, rename your UserControl to something better than "UserControl1".
-
Re: Control Array in VS 2010
I renamed UserControl1.vb to Stats.vb but it still shows as UserControl1 in the toolbox and the controll is still named UserControlx where x is the number even after saving and restarting VS i even tryied to Build a sulotion.
-:EDIT:-
Got it to wurk but now i hawe anouther problem how do i write the code so that when i change a textbox in the main Form (named EoN.vb) it vill change a value in the Usercontroll (now named Stats)?
-
Re: Control Array in VS 2010
The fact that you renamed the code file has no effect on the class. Logically, the code file and the class should have the same name, but there's no requirement that they do. Also, if a single code file contains multiple types, the names obviously can't all match.
-
1 Attachment(s)
Re: Control Array in VS 2010
What i want is to make it look like the attached picture (done)
Then what i want it to do is when i press the red button in Stats1 or 2 it will increase Skillpoints and decrease Points after this
Code:
SkillPoints Points
0-5 -1 point
5-10 -1 per point
11-15 -2 per point
Same if i press the black button it will increase Points and decrease SkillPoints (think i got it)
The only thing left is to when i change the walue in points i need to sent the new walue to the usercontrol Stats. As stated in my last posts -:EDIT:-
-
Re: Control Array in VS 2010
You're working very hard on this, and at this point, I think you just need a good, solid example to work with. My next post will have a small project attached with an example of a form and a usercontrol that does something similar to what you're trying to do for you to pick apart and study. :)
-
Re: Control Array in VS 2010
-
2 Attachment(s)
Re: Control Array in VS 2010
Ok, here's an example of a form and a user control similar to what you're doing. It should give you an example of how things are done in .NET.
The project file is here:
Attachment 80011
The binary is included if you don't want to re-compile it. The output looks like this:
Attachment 80010
The user control code is as follows:
Code:
Public Class Stats
Private strStatName As String
Private intValue As Integer
Private intTotalPoints As Integer
Private intPointsUsed As Integer
'A custom constructor to simplify making a new control.
Public Sub New(ByVal statName As String)
InitializeComponent()
Me.StatName = statName
Me.Value = 0
End Sub
'The property for name of our stat
Public Property StatName() As String
Get
Return strStatName
End Get
Set(ByVal value As String)
strStatName = value
lblStatName.Text = strStatName
End Set
End Property
'The property for the current value of the stat
Public Property Value() As Integer
Get
Return intValue
End Get
Set(ByVal value As Integer)
intValue = value
lblValue.Text = intValue.ToString
intPointsUsed = CalculatePointsUsed(intValue)
End Set
End Property
'A read-only property for the amount of points the current stat value uses
Public ReadOnly Property PointsUsed() As Integer
Get
Return intPointsUsed
End Get
End Property
'A write-only property to set the total points the control has to work with
Public WriteOnly Property TotalPoints() As Integer
Set(ByVal value As Integer)
intTotalPoints = value
End Set
End Property
'An event to signal when the stat value has been changed
Public Event StatChanged(ByVal sender As Object, ByVal e As EventArgs)
'What happens when I hit the + button
Private Sub btnAdd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAdd.Click
If intValue + 1 > 15 Then Exit Sub 'Stat can't go above 15!
Dim intPointShift As Integer = CalculatePointsUsed(intValue + 1) - CalculatePointsUsed(intValue)
If intTotalPoints - intPointShift < 0 Then Exit Sub 'Not enough points to raise stat!
'Add 1 to the current value.
Me.Value += 1
'Raise the "StatChanged" event so the parent form knows the value changed.
RaiseEvent StatChanged(Me, New EventArgs)
End Sub
Private Sub btnSub_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSub.Click
If intValue - 1 < 0 Then Exit Sub 'Stat can't go below 0!
'Subtract 1 from the current value.
Me.Value -= 1
'Raise the "StatChanged" event so the parent form knows the value changed.
RaiseEvent StatChanged(Me, New EventArgs)
End Sub
Private Function CalculatePointsUsed(ByVal statValue As Integer) As Integer
'This is the formula for calculating the total point-cost of the stat.
'0 = 0 points. 1 through 5 = only 1 point. 6 through 10 = 1 point per
'level, plus 1 for the 1-5 range. 11 through 15 = 2 points per level, plus
'5 points for the 6 through 10 range and 1 more for the 1 through 5 range.
'The math formulas have been simplified to the case structure below.
'If it's anything outside the 0 through 15 range, it'll return 999 which
'can be used as an error-check.
Select Case statValue
Case 0
Return 0
Case 1 To 5
Return 1
Case 6 To 10
Return statValue - 4
Case 11 To 15
Return (2 * statValue) - 14
Case Else
Return 999
End Select
End Function
End Class
-
Re: Control Array in VS 2010
...and the form's code:
Code:
Public Class Form1
'Set my total points
Private Const STARTING_POINTS As Integer = 50
'Set current point count
Private intTotalPoints As Integer = STARTING_POINTS
'On my form, I just have a simple Label and Panel. The panel is where I'm going to put my user controls.
'I'll populate it when the form opens.
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Me.lblPoints.Text = String.Format("Points: {0}", intTotalPoints)
'Define my stats
Dim myStats() As String = {"Strength", "Intelligence", "Wisdom", "Dexterity", "Constitution", "Charisma"}
Dim i As Integer
'Loop through the stats, make a control for each
For Each statName In myStats
Dim c As New Stats(statName)
c.TotalPoints = STARTING_POINTS
c.Top = i * c.Height
'This line links the "StatChanged" event in the user control with the event handler below
AddHandler c.StatChanged, AddressOf StatChanged
'Add the stat control to the panel
Me.Panel1.Controls.Add(c)
i += 1
Next
End Sub
Private Sub StatChanged(ByVal sender As Object, ByVal e As EventArgs)
'If one of those stat controls changes, we need to recompute the total points remaining
Dim intCount As Integer
'Add up each stat control's point usage
For Each c As Stats In Me.Panel1.Controls.OfType(Of Stats)()
intCount += c.PointsUsed
Next
'Subtract it from the max and we got our new point total
intTotalPoints = STARTING_POINTS - intCount
'Inform all the stat controls what the new total is
For Each c As Stats In Me.Panel1.Controls.OfType(Of Stats)()
c.TotalPoints = intTotalPoints
Next
'Update the label on the form
Me.lblPoints.Text = String.Format("Points: {0}", intTotalPoints)
End Sub
Private Sub btnDone_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDone.Click
'The Done button will record the final values in the stat controls to a dictionary. Using a dictionary
'has a lot of benefits. If later, I want to know what the character's strength is, all I need to do is:
'myStrength = finalStats("Strength")
'Better though would be to make a custom character class.
'This routine will also build a nice block of text with the stats and their values, as shown in the messagebox.
Dim finalStats As New Dictionary(Of String, Integer)
Dim strResults As New System.Text.StringBuilder
For Each c As Stats In Me.Panel1.Controls.OfType(Of Stats)()
finalStats(c.StatName) = c.Value
strResults.AppendLine(String.Format("{0,-13} = {1,3}", c.StatName, c.Value))
Next
MessageBox.Show(strResults.ToString)
End Sub
End Class
-
Re: Control Array in VS 2010
how can i call the main Form (form1) from the user control whid this code
Code:
Private Sub Form1_TextChangeForm(ByVal sender As Object, ByVal e As System.EventArgs) Handles Form1.TextChangeForm
TextBox1.Text = Form1.Poäng_GetForm
End Sub
The red Form1 i get "Handles clause requires a WithEvent variable defined in the containing type or one of its base types."
If i instead write Me i get "Event 'TextChangeForm' cannot be found." but i hawe defined if in the main form like this
Code:
Public Event TextChangeForm(ByVal sender As Object, ByVal e As System.EventArgs)
-
Re: Control Array in VS 2010
Is your Event on the form or on the usercontrol?
UserControl events need 4 things to make things happen on the parent form.
First, they need the Event definition in the UserControl code. This is because something is happening on the UserForm and we want to alert everything else that it's occurring.
Second, we need at least one RaiseEvent call in the code of the UserForm. This is the actual point where the code triggers the Event. If you don't have this, your Event will never fire because nothing will actually trigger it.
Third, you need a function on the parent form to Handle the Event. This is called an Event Handler. They usually, but not always, have "Handles ControlName.EventName" after them. This code instructs the parent form what to do when the control triggers it's event.
Last, you need a handler wiring. Normally, when you drag a control onto a form, this is done for you automatically. In the designer code of your form it will automatically put:
Dim WithEvents ControlName As ControlType
The "WithEvents" parts means "Set up the event wiring for all events on this control". Now, if you noticed, in my example, I created all my controls dynamically. I only wanted to wire up my one event, so I did it manually. This is where the AddHandler line comes in. I'm telling it "Add a handler link between this control's event and this function on this form."
Does this answer your question?
-
Re: Control Array in VS 2010
Not realy i'l post my code
The code you posted was good but it had to meany thing i never used before
i did a whole new prject to se if i could make the form and usercontrol speack whid each other
Form1.vb code
Code:
Public Class Form1
Dim poängform As Integer
Public Event TextChangeForm(ByVal sender As Object, ByVal e As System.EventArgs)
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
End Sub
Public Property Poäng_GetForm() As Integer
Get
Return poängform
End Get
Set(ByVal value As Integer)
poängform = value
End Set
End Property
Private Sub TextBox1_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox1.TextChanged
poängform = TextBox1.Text
RaiseEvent TextChangeForm(Me, e)
End Sub
Private Sub Skills_TextChangeSkill(ByVal sender As Object, ByVal e As System.EventArgs) Handles Skills1.TextChangeSkill, Skills2.TextChangeSkill
TextBox1.Text = Skills1.Poäng_GetUser
End Sub
End Class
Skills.bv code
Code:
Public Class Skills
Dim PoängUser As Integer
Public Event TextChangeSkill(ByVal sender As Object, ByVal e As System.EventArgs)
Private Sub Form1_TextChangeForm(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.MouseMove
TextBox1.Text = Form1.Poäng_GetForm
End Sub
Public Property Poäng_GetUser() As Integer
Get
Return PoängUser
End Get
Set(ByVal value As Integer)
PoängUser = value
End Set
End Property
Private Sub TextBox1_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox1.TextChanged
PoängUser = TextBox1.Text
RaiseEvent TextChangeSkill(Me, e)
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
PoängUser = Form1.Poäng_GetForm + PoängUser + 1
TextBox1.Text = PoängUser
RaiseEvent TextChangeSkill(Me, e)
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
PoängUser = Form1.Poäng_GetForm + PoängUser - 1
TextBox1.Text = PoängUser
RaiseEvent TextChangeSkill(Me, e)
End Sub
End Class
i hawe one textbox in the form and one in the usercontrol and 2 buttons in the usercontrol.
and i'm using 2 usercontrols
What i want is if i change the one in the form to lets say 100 the text boxes in the usercontrols to 100 (only to see that its transfeard) later i'm yust going to sent it a integer and when i press button1 the textbox in the form would increase whid 1 and the one on the form decrease whid 1 and reversed when i press button 2
Code:
When i start the prog
0
/ \
/ \
0 (0) 0(0)
after i hawe manualy increased the textbox on the form
100
/ \
/ \
0 (100) 0(100)
Press the increse button on the usercontrol 1
99
/ \
/ \
1 (99) 0(99)
press the increase button on the usercontrol 2
98
/ \
/ \
1 (98) 1(98)
-
Re: Control Array in VS 2010
Ok, you don't need the Event or property or anything on the Form since the form is the parent of the controls. If you change the value of the TextBox, then all you want to do is update the controls. You KNOW they're called Skills1 and Skills2, so just set them.
You need an event on UserControls because you never know what they could be sitting on.
Also, you're confused in your user control. You only have one variable: PoängUser. You need at LEAST 2 by your example, you need PoängUser to keep track of how many TOTAL points are left, and you need one to track what the control is set at. Look at your own example. You have your first usercontrol set to 1 (99) and your second to 0 (99). That's two numbers you need.
Code:
Public Class Form1
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
End Sub
Private Sub TextBox1_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox1.TextChanged
Skills1.Poäng_GetUser = TextBox1.Text
Skills2.Poäng_GetUser = TextBox1.Text
End Sub
Private Sub Skills_TextChangeSkill(ByVal sender As Object, ByVal e As System.EventArgs) Handles Skills1.TextChangeSkill, Skills2.TextChangeSkill
TextBox1.Text = Skills1.Poäng_GetUser
End Sub
End Class
-
Re: Control Array in VS 2010
How can i make my UserControl to a array like i did the text boxes erlier like this
Code:
Dim UserControls() As TextBox
Private Sub Form1_Load
UserControl = {Skills1.TextBox2, Skills2.TextBox2}
End Sub
This is the error
"An error occurred creating the form. See Exception.InnerException for details. The error is: Object reference not set to an instance of an object."
After a lite testing i narowed the error down to this
Code:
Private Sub TextBox1_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox1.TextChanged
i = 0
Do While i <= 1
UserForm(i).Text = TextBox1.Text
i = i + 1
Loop
End Sub
and this
Code:
Private Sub Skills_Textbox(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Skills1.TextBoxChanged, Skills2.TextBoxChanged
i = 0
Do While i <= 1
If TextBox1.Text <> UserForm(i).Text Then
TextBox1.Text = UserForm(i).Text
End If
i = i + 1
Loop
End Sub