Implement global menu in Basic4android - menu

I am developing an application that has many activities. Is there any way to implement the same menu to all activities?

You can use a code module to create the menu.
Sub CreateMenu(Act As Activity)
Act.AddMenuItem("m1", "m1")
Act.AddMenuItem("m2", "m2")
Act.AddMenuItem("m3", "m3")
End Sub
You can then call this method from other activities. The events will be handled in each activity.

Related

Get the name of the Command Button I just clicked [duplicate]

I have a bunch of TextBox-Button pairs on a form. When the button is clicked I want to insert the value of the text box into a database. The name TextBoxes and Buttons follow a naming standard, for example Value1Tb - Value1Cmd and Value2Tb - Value2Cmd.
My problem is that since I want to do the same for every button I would like the possibility to write a Sub like:
Private Sub AnyButton_Click(sender As CommandButton)
Dim tb As TextBox
Set tb = GetTBByName(s.Name)
PutValueToDatabase(s.Name,tb.Text)
End Sub
But I cannot find a way to point the Click-event of a Button to a different sub than the standard Name_Click().
Anybody know a way around this, that doesn't involve me writing 50 or so different Name_Click() subs?
If you are OK to use Form Controls rather that ActiveX, as it looks as though you may be at the moment, then Chris' solution seems good.
However if you need ActiveX CommandButtons then you are unable (as the VBA compiler will tell you, "Procedure declaration does not match...") to have parameters in the callback for the click event, and you are unable to raise the event from multiple objects, although you do of course know which button raised the event (since the relationship is 1 CommandButton = 1 Sub).
So... I would go with something like:
Private Sub Value1Cmd_Click()
Call TheMethod(Value1Cmd)
End Sub
Private Sub Value2Cmd_Click()
Call TheMethod(Value2Cmd)
End Sub
Private Sub TheRealMethod(sender As CommandButton)
' Do your thing '
Dim tb As TextBox
Set tb = GetTBByName(s.Name)
PutValueToDatabase(s.Name,tb.Text)
' Etcetera... '
End Sub
Requires a stub for each button, so some copying and pasting to begin with, but then easy to maintain etcetera as all _Click event callbacks are pointing at the same method...
Edit:
E.g.
Sub AutoWriteTheStubs()
Dim theStubs As String
Dim i As Long
For i = 1 To 10
theStubs = theStubs & "Private Sub Value" & CStr(i) & "Cmd_Click()" & vbCrLf _
& " Call TheMethod(Value" & CStr(i) & "Cmd)" & vbCrLf _
& "End Sub" & vbCrLf & vbCrLf
Next i
Debug.Print theStubs
End Sub
It seems that what you want is to get the name of the clicked button. If you are creating buttons like this:
(where 'i' increments in a loop)
Set btn = Sheet1.Buttons.Add( , , , ,)
With btn
.OnAction = "btnSub"
.Caption = "Upadate"
.Name = "btn" & CStr(i) & "Cmd"
End With
and then defining a generic "private sub btnSub()" for all the buttons, you could at least get the name of the button that was clicked using Application.Caller. Something like:
Private Sub btnSub()
Dim ButtonName As String
ButtonName = Application.Caller
MsgBox ("Hello:" & ButtonName)
End Sub
Hope it helps!
I decided to make this an answer because I am doing something similar and I confirmed that it works.
You can store the OLEobjects in a Collection, of arbitrary size, containing Custom Class Objects that include the OLEobjects and associations and the events that you need. Thus you can completely avoid any code stubs.
Create a Custom Class to bind the Button and TextBox pairs.
Declare the Button object WithEvents.
Include your call-back in the exposed button event handler in the Class Module.
Put a Public routine in a Standard Module to initialise a Collection of these Custom Class objects by spanning the Form Controls. You can also use this to Add the controls programmatically as a 'reBuild' option. The Collection can be inside another Class Module with all of the management routines, but it needs to be Instantiated and loaded in a Standard Module.
Put a public routine in a standard module to receive the call-backs with whatever context you need. This can also be in a Worksheet Module if it makes for better encapsulation. You can use late binding to reference the callback or CallByName.
You need to bear in mind that the Module of the Form will recompile every time you add a control, so you have to be careful where you put your code.
My application has the controls directly on the Worksheet Surface, so I can't put the the Collection Class in, or source any initialisation of the Collection from the Worksheet module. This would amount to self modifying code and it grinds excel to a halt.
I dreamed this idea up through bloody-minded idealism (not necessarily a good thing) but, of course, I was not the first one to think of it as you can see here. #Tim Williams explains it in his answer. You can also google VBA Control Array Events to see plenty of similar examples including an excellent article by #SiddharthRout. In line with the VB6 analogy, he uses an Array instead of a Collection to achieve the same result.
I'll try to post some code later. My application is a bit different so it will take a lot of work to trim it down, but the principle is the same.
The other thing to bear in mind is that VBE really struggles with this type of thing so don't worry if it is loading up you processors. After you re-start with VBE off, all will be fine.
I have this same situation, and I just have a click event for every button that is a wrapper to the function I want to call. This also allows you to pass sheet-specific parameters if you need to.
Example:
Public Sub StoreButton_Click()
' Store values for transaction sheet 3/27/09 ljr
Call StoreTransValues(ActiveSheet)
End Sub
I just published (Open Source) the Event Centralizer for MSForms.
Citation: "The Event Centralizer for MSForms is a VBA programming tool that allows all sorts of custom grouping when writing handlers for the events occurring in UserForms.
With the Event Centralizer for MSForms, it is easy for example to have all TextBoxes react the same way when the Enter event occurs, or all except one, or only those with a particular Tag value.
Thanks to its events logs system, the Event Centralizer for MSForms is a powerful learning and debugging help."
I can't explain here how it works. I tried to do it on the site.
Set the event to =FunctionName(parameter).
A bit late but this may help someone else:
If you have a function called OpenDocumentById(docID as integer), then each control calling the function would have in the event the following:
cmd1's On Click event:
=OpenDocumentById([DocID])
cmd2's On Click event:
=OpenDocumentById([DocID])
etc...

Are there disadvantages in putting code into Userforms instead of modules?

Are there disadvantages in putting code into a VBA Userform instead of into a "normal" module?
This might be a simple question but I have not found a conclusive answer to it while searching the web and stackoverflow.
Background: I am developing a Front-End Application of a database in Excel-VBA. To select different filters I have different userforms. I ask what general program design is better: (1) putting the control structure into a separate module OR (2) putting the code for the next userform or action in the userform.
Lets make an example. I have a Active-X Button which triggers my filters and my forms.
Variant1: Modules
In the CommandButton:
Private Sub CommandButton1_Click()
call UserInterfaceControlModule
End Sub
In the Module:
Sub UserInterfaceControllModule()
Dim decisionInput1 As Boolean
Dim decisionInput2 As Boolean
UserForm1.Show
decisionInput1 = UserForm1.decision
If decisionInput1 Then
UserForm2.Show
Else
UserForm3.Show
End If
End Sub
In Variant 1 the control structure is in a normal module. And decisions about which userform to show next are separated from the userform. Any information needed to decide about which userform to show next has to be pulled from the userform.
Variant2: Userform
In the CommadButton:
Private Sub CommandButton1_Click()
UserForm1.Show
End Sub
In Userform1:
Private Sub ToUserform2_Click()
UserForm2.Show
UserForm1.Hide
End Sub
Private Sub UserForm_Click()
UserForm2.Show
UserForm1.Hide
End Sub
In Variant 2 the control structure is directly in the userforms and each userform has the instructions about what comes after it.
I have started development using method 2. If this was a mistake and there are some serious drawbacks to this method I want to know it rather sooner than later.
Disclaimer I wrote the article Victor K linked to. I own that blog, and manage the open-source VBIDE add-in project it's for.
Neither of your alternatives are ideal. Back to basics.
To select different filters I have differnt (sic) userforms.
Your specifications demand that the user needs to be able to select different filters, and you chose to implement a UI for it using a UserForm. So far, so good... and it's all downhill from there.
Making the form responsible for anything other than presentation concerns is a common mistake, and it has a name: it's the Smart UI [anti-]pattern, and the problem with it is that it doesn't scale. It's great for prototyping (i.e. make a quick thing that "works" - note the scare quotes), not so much for anything that needs to be maintained over years.
You've probably seen these forms, with 160 controls, 217 event handlers, and 3 private procedures closing in on 2000 lines of code each: that's how badly Smart UI scales, and it's the only possible outcome down that road.
You see, a UserForm is a class module: it defines the blueprint of an object. Objects usually want to be instantiated, but then someone had the genius idea of granting all instances of MSForms.UserForm a predeclared ID, which in COM terms means you basically get a global object for free.
Great! No? No.
UserForm1.Show
decisionInput1 = UserForm1.decision
If decisionInput1 Then
UserForm2.Show
Else
UserForm3.Show
End If
What happens if UserForm1 is "X'd-out"? Or if UserForm1 is Unloaded? If the form isn't handling its QueryClose event, the object is destroyed - but because that's the default instance, VBA automatically/silently creates a new one for you, just before your code reads UserForm1.decision - as a result you get whatever the initial global state is for UserForm1.decision.
If it wasn't a default instance, and QueryClose wasn't handled, then accessing the .decision member of a destroyed object would give you the classic run-time error 91 for accessing a null object reference.
UserForm2.Show and UserForm3.Show both do the same thing: fire-and-forget - whatever happens happens, and to find out exactly what that consists of, you need to dig it up in the forms' respective code-behind.
In other words, the forms are running the show. They're responsible for collecting the data, presenting that data, collecting user input, and doing whatever work needs to be done with it. That's why it's called "Smart UI": the UI knows everything.
There's a better way. MSForms is the COM ancestor of .NET's WinForms UI framework, and what the ancestor has in common with its .NET successor, is that it works particularly well with the famous Model-View-Presenter (MVP) pattern.
The Model
That's your data. Essentially, it's what your application logic need to know out of the form.
UserForm1.decision let's go with that.
Add a new class, call it, say, FilterModel. Should be a very simple class:
Option Explicit
Private Type TModel
SelectedFilter As String
End Type
Private this As TModel
Public Property Get SelectedFilter() As String
SelectedFilter = this.SelectedFilter
End Property
Public Property Let SelectedFilter(ByVal value As String)
this.SelectedFilter = value
End Property
Public Function IsValid() As Boolean
IsValid = this.SelectedFilter <> vbNullString
End Function
That's really all we need: a class to encapsulate the form's data. The class can be responsible for some validation logic, or whatever - but it doesn't collect the data, it doesn't present it to the user, and it doesn't consume it either. It is the data.
Here there's only 1 property, but you could have many more: think one field on the form => one property.
The model is also what the form needs to know from the application logic. For example if the form needs a drop-down that displays a number of possible selections, the model would be the object exposing them.
The View
That's your form. It's responsible for knowing about controls, writing to and reading from the model, and... that's all. We're looking at a dialog here: we bring it up, user fills it up, closes it, and the program acts upon it - the form itself doesn't do anything with the data it collects. The model might validate it, the form might decide to disable its Ok button until the model says its data is valid and good to go, but under no circumstances a UserForm reads or writes from a worksheet, a database, a file, a URL, or anything.
The form's code-behind is dead simple: it wires up the UI with the model instance, and enables/disables its buttons as needed.
The important things to remember:
Hide, don't Unload: the view is an object, and objects don't self-destruct.
NEVER refer to the form's default instance.
Always handle QueryClose, again, to avoid a self-destructing object ("X-ing out" of the form would otherwise destroy the instance).
In this case the code-behind might look like this:
Option Explicit
Private Type TView
Model As FilterModel
IsCancelled As Boolean
End Type
Private this As TView
Public Property Get Model() As FilterModel
Set Model = this.Model
End Property
Public Property Set Model(ByVal value As FilterModel)
Set this.Model = value
Validate
End Property
Public Property Get IsCancelled() As Boolean
IsCancelled = this.IsCancelled
End Property
Private Sub TextBox1_Change()
this.Model.SelectedFilter = TextBox1.Text
Validate
End Sub
Private Sub OkButton_Click()
Me.Hide
End Sub
Private Sub Validate()
OkButton.Enabled = this.Model.IsValid
End Sub
Private Sub CancelButton_Click()
OnCancel
End Sub
Private Sub UserForm_QueryClose(Cancel As Integer, CloseMode As Integer)
If CloseMode = VbQueryClose.vbFormControlMenu Then
Cancel = True
OnCancel
End If
End Sub
Private Sub OnCancel()
this.IsCancelled = True
Me.Hide
End Sub
That's literally all the form does. It isn't responsible for knowing where the data comes from or what to do with it.
The Presenter
That's the "glue" object that connects the dots.
Option Explicit
Public Sub DoSomething()
Dim m As FilterModel
Set m = New FilterModel
With New FilterForm
Set .Model = m 'set the model
.Show 'display the dialog
If Not .IsCancelled Then 'how was it closed?
'consume the data
Debug.Print m.SelectedFilter
End If
End With
End Sub
If the data in the model needed to come from a database, or some worksheet, it uses a class instance (yes, another object!) that's responsible for doing just that.
The calling code could be your ActiveX button's click handler, New-ing up the presenter and calling its DoSomething method.
This isn't everything there is to know about OOP in VBA (I didn't even mention interfaces, polymorphism, test stubs and unit testing), but if you want objectively scalable code, you'll want to go down the MVP rabbit hole and explore the possibilities truly object-oriented code bring to VBA.
TL;DR:
Code ("business logic") simply doesn't belong in forms' code-behind, in any code base that means to scale and be maintained across several years.
In "variant 1" the code is hard to follow because you're jumping between modules and the presentation concerns are mixed with the application logic: it's not the form's job to know what other form to show given button A or button B was pressed. Instead it should let the presenter know what the user means to do, and act accordingly.
In "variant 2" the code is hard to follow because everything is hidden in userforms' code-behind: we don't know what the application logic is unless we dig into that code, which now purposely mixes presentation and business logic concerns. That is exactly what the "Smart UI" anti-pattern does.
In other words variant 1 is slightly better than variant 2, because at least the logic isn't in the code-behind, but it's still a "Smart UI" because it's running the show instead of telling its caller what's happening.
In both cases, coding against the forms' default instances is harmful, because it puts state in global scope (anyone can access the default instances and do anything to its state, from anywhere in the code).
Treat forms like the objects they are: instantiate them!
In both cases, because the form's code is tightly coupled with the application logic and intertwined with presentation concerns, it's completely impossible to write a single unit test that covers even one single aspect of what's going on. With the MVP pattern, you can completely decouple the components, abstract them behind interfaces, isolate responsibilities, and write dozens of automated unit tests that cover every single piece of functionality and document exactly what the specifications are - without writing a single bit of documentation: the code becomes its own documentation.

Reportviewer not visible

I am using Visual Studio 2013 Professional and vb.net. When I start a new Windows Form and drag ReportViewer to the blank form, it does not appear on the form. At the bottom, it shows ReportViewer1; however, there is no reportviewer visible. This means I can't attach the viewer to a report or database.
If I start an entirely new project, I can drag the reportVierwer. This is a big project or I would just start a new one and do it.
For some reason (on VS2015) the ReportViewer instance is not added to the Controls collection of the form inside the InitializeComponents method.
Adding this line (reportViewer being the instance of ReportViewer) fixes the problem:
this.Controls.Add(reportViewer);
You can always add it in code behind manually, or to manually edit the designer.
Add the Load event handler to the form to refresh the report viewer on Load:
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Me.ReportViewer1.RefreshReport()
End Sub
And in designer create the ReportViewer instance. In InitializeComponent:
Private Sub InitializeComponent()
Me.ReportViewer1 = New Microsoft.Reporting.WinForms.ReportViewer()
'...
'
'ReportViewer1
'
Me.ReportViewer1.Location = New System.Drawing.Point(13, 13)
Me.ReportViewer1.Name = "ReportViewer1"
Me.ReportViewer1.Size = New System.Drawing.Size(396, 246)
Me.ReportViewer1.TabIndex = 0
'...
End Sub
Friend WithEvents ReportViewer1 As Microsoft.Reporting.WinForms.ReportViewer
It's not ideal solution. When adding to your main code you are mixing presentation and logic. When modifying designer code there is a risk it will be overridden.
Perhaps some improvement would be to create yet another Form partial class where you put the above mentioned code. For instance, as LoadReportViewer method and then invoke the method from your code. This way you do not mingle designer code with logic and you don't risk the change is removed by designer.

How to sequence a custom action script after a specific dialog?

I have created a basic MSI project using InstallShield, I want to run a custom action script between two dialogs.
This shows my execute sequence, I want to move the custom action MyCustomActionScript to between the two dialogs indicated by the arrow.
How can I do this? Do I need to change things around somehow so that the dialogs are not nested (this is the way they are created naturally)? Or do I have to do something else, like run a DoAction on the target dialog? If so, will the execute sequence automatically move to the next dialog upon completion of the script, or do I have to script something to move the execution?
(Note that the script is a simple manipulation of the INSTALLDIR property, nothing complicated.)
Only the first dialog of the wizard loop is in the UI sequence. The rest are invoked by NewDialog control events. You want to look into the DoAction control event to invoke your custom action.
Custom actions scheduled in this fashion should only perform data acquisition / validation. Changes to the machine state should only occur in the execute sequence.
To run an action between LicenseAgreement and InstallSettings, you must indeed set up a control event DoAction. In this case you would add the DoAction on the behavior of LicenseAgreement's Next button so that it is invoked in the same scenarios that the Next button's NewDialog takes you to InstallSettings.

How can we create sub modules in boilerplate.js

I have a design,
Where Im having lots of products and then each product has lots of sub products.
So Now in the First Screen I want to show a dashboard which will show all of my products.
On click of each product I want to open a separate view with its own left side navigation bar and detail view. These will be my main modules
now options in left side menubar will be my sub-products. Now click of any subproduct. I want to change my detail view. These will be my sub modules
Please share some sample example if you have with yourself
Thanks in advance.
BoilerplateJS supports having nested contexts. More information is available under 'Product Modules' section in boilerplatejs.org. A nested context can be created by passing the parent context in to the child context when creating it. You can create a context for each of your products. And within that context you can create modules, which will be your sub products. Having this type of a modular structure would help you in maintaining your code.
Implementing your requirement can be done in many ways.
One method is to structure the urls of your application as follows:
www.myapp.com/index.html#productA/submodule1
www.myapp.com/index.html#productB/submodule1
You can implement the menu as a seperate module, where it will change the menu that needs to be displayed according to the first portion (productA, productB) of your URL, and your sub modules can be activated/de-activated according to the rest of the URL portion. This method allows you to bookmark the pages and bring it to the same state when a bookmarked link is triggered.

Resources