0
votes

I'm new in .NET programming.

I have a class Form1 that includes Button1_Click event. (Button1_Click creates a multiple Text Boxies at run time)

Here is the class:

Public Class Form1

    Dim shiftDown As Integer

    Dim counter As Integer


  Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs)   Handles MyBase.Load
   End Sub

  Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
       Dim textbox1 As New TextBox

       counter += 1

       shiftDown = shiftDown + 30

       textbox1.Name = "Textbox" + counter.ToString()
       textbox1.Size = New Size(170, 10)
       textbox1.Location = New Point(10, 32 + shiftDown)
       textbox1.Visible = True

       GroupBox1.Controls.Add(textbox1)

End Sub

End Class

Currently this rows:

Dim shiftDown As Integer

Dim counter As Integer

defined as global variables.

My question is, instead of the way they are, should I define these variables as properties or as static local variables in Button1_Click event?

3
naturally winforms. Just leave the code as it is. ShiftDown and Counter as member variables make sense. You tagged this OOP - what you should do is have all the logic in a class that exposes logic that you bind the controls to..Jeremy Thompson

3 Answers

3
votes

If you're building Windows Forms Application (which i think you are), try using Protected instead of Dim:

Protected shiftDown As Integer
Protected counter As Integer

This will turn the variables into local class variables instead of global.

3
votes

I would use variables rather than properties. Defining them either in the class Form1 globally to the class, as you are now, or as static variables in Button1_click will both work fine; it's a matter of personal preference.

It would be fine to leave them as they are, with the understanding that these variables can be accessed by other subs in the class Form1. You can also make them static inside Button1_click, but you will need to take care if you explicitly initialize the variables.

2
votes

If you really want to learn how to architect an .NET application i urgently suggest to watch the video by Jason Dollinger which is available here: Lab49 Archives

It is really great and it covers most of the relevant issues one comes across when in need of building a proper WPF / MVVM / .NET Application