Visual Basic Referencing .Net Objects In An Array - arrays

I have a big list of objects in the Design view of Visual Basic 2010 that I need to change a bunch of properties for, so of course I tried using an array rather than taking 50-60 lines for a repetitive task. But there seems to be an issue referencing to the object and it seems to be just taking the information from it. I know that was a shitty explanation, but maybe you'll understand it when you see it.
Dim objectsToClear As Array = _
{lblDailyRoundTrip, lblDaysWorked, lblFillBoxes, lblMilesPerGallon, lblMonthlyInsurance, _
lblMonthlyMaintenance, lblMonthlyParking, tbDailyRoundTrip, tbDaysWorked, tbMilesPerGallon, _
tbMonthlyInsurance, tbMonthlyMaintenance, tbMonthlyParking}
For i = LBound(objectsToClear) To UBound(objectsToClear)
objectsToClear(i).Text = ""
objectsToClear(i).Visible = False
Next

Try this instead:
Dim objectsToClear As Array = { lblDailyRoundTrip,
lblDaysWorked,
lblFillBoxes,
lblMilesPerGallon,
lblMonthlyInsurance,
lblMonthlyMaintenance,
lblMonthlyParking,
tbDailyRoundTrip,
tbDaysWorked,
tbMilesPerGallon,
tbMonthlyInsurance,
tbMonthlyMaintenance,
tbMonthlyParking }
For Each item In objectsToClear
item.Text = String.Empty
item.Visible = False
Next item
P.S. - you REALLY should have Option Strict On, and you should have strongly typed your array.

Since you seem to be interested in changing only .Text and .Visible properties, then you can just find the control by name, like this:
Dim returnValue As Control()
returnValue = Me.Controls.Find(objectsToClear(i), True)
Note: The True argument is for whether or not to search all children, which it sounds like you want to do. Read Control.ControlCollection.Find Method documentation for more information.
Now that you have a collection of controls that match the name you specified, loop through the controls in that collection and set the property values, like this:
For Each c As Control In returnValue
c.Text = ""
c.Visible = False
Next

Related

Libreoffice Base - how to call a control event from a macro?

Question: I need to manually call an object listener event (e.g. key pressed) to trigger a function. I used to do it in Access but haven't found the documentation for it in LibreOffice Base.
Context: Having retired from software development 7 years ago, I am doing a favour for a friend by building a database in LibreOffice Base. Previously experienced in Access - but more with Oracle, PL/SQL, APEX, etc! I am struggling a little in getting it to do what I know can be done!
Here is the code I've tried so far.
Sub CauseKeyPressedEventToBeFired
oDoc = ThisComponent
oController = oDoc.getCurrentController()
oVC = oController.getViewCursor()
oForm = oDoc.getDrawpage().getForms().getByName("Form")
oTextBox = oForm.getByName("Text Box 1")
oControlView = oController.getControl(oTextBox)
oControlView.setFocus()
Dim oEvent As New com.sun.star.awt.KeyEvent
oEvent.Source = oControlView
oEvent.KeyCode = com.sun.star.awt.Key.A
oControlView.keyPressed(oEvent)
End Sub
However, it doesn't seem to work on my system (LibreOffice 6.4.3.2 on Windows). I also found this post, but that code doesn't seem to work for me either.
I searched for com.sun.star.awt.XToolkitRobot, but it's not in the API documentation, perhaps because the functionality is not fully supported. Presumably, it can be obtained from com.sun.star.awt.Toolkit.
For more help, post a question on ask.libreoffice.org. I'd suggest explaining why you want to do this, because there may be a different kind of solution. Ratslinger has a lot of experience solving various database problems, and he'll probably direct you toward a simpler solution that doesn't involve this kind of event hacking.
a function (i.e. a procedure that returns a value)
Yes, that is what a function is. But "an object listener event" implies, correctly I think, that we're talking about the method of an object instead. That's what LibreOffice event listeners are in Python or Java, although in Basic, they're a little strange, using the object name as some kind of magic to determine what they apply to. Anyway, that's getting off track, because your question isn't about listening for events, but rather about triggering them.
EDIT:
The following Python code works. The problem with my earlier attempts was that oEvent.KeyChar needs to be set, and that doesn't seem to work in Basic. I can't imagine why, unless I am ignoring some obvious mistake in the Basic code.
def causeKeyPressedEventToBeFired(oEvent=None):
oDoc = XSCRIPTCONTEXT.getDocument()
oController = oDoc.getCurrentController()
oForm = oDoc.getDrawPage().getForms().getByName("Form")
oTextBox = oForm.getByName("Text Box 1")
oControlView = oController.getControl(oTextBox)
oControlView.setFocus()
oEvent = uno.createUnoStruct("com.sun.star.awt.KeyEvent")
oEvent.Source = oControlView
from com.sun.star.awt.Key import A
oEvent.KeyCode = A
oEvent.KeyChar = "a" # works in Python but strangely not in Basic
simulate_KeyPress(oEvent)
def simulate_KeyPress(oKeyEvent):
oDoc = XSCRIPTCONTEXT.getDocument()
oWindow = oDoc.CurrentController.Frame.getContainerWindow()
oKeyEvent.Source = oWindow
oToolkit = oWindow.getToolkit()
oToolkit.keyPress(oKeyEvent)
oToolkit.keyRelease(oKeyEvent)
EDIT 2:
Finally, here is working Basic code. In the earlier attempt, the type was wrong.
Sub CauseKeyPressedEventToBeFired
oDoc = ThisComponent
oController = oDoc.getCurrentController()
oForm = oDoc.getDrawpage().getForms().getByName("Form")
oTextBox = oForm.getByName("Text Box 1")
oControlView = oController.getControl(oTextBox)
oControlView.setFocus()
Dim oEvent As New com.sun.star.awt.KeyEvent
oEvent.KeyCode = com.sun.star.awt.Key.A
oEvent.KeyChar = CByte(97)
simulate_KeyPress(oEvent)
End Sub
Sub simulate_KeyPress(oKeyEvent As com.sun.star.awt.KeyEvent)
oWindow = ThisComponent.CurrentController.Frame.getContainerWindow()
oKeyEvent.Source = oWindow
oToolkit = oWindow.getToolkit()
oToolkit.keyPress(oKeyEvent)
oToolkit.keyRelease(oKeyEvent)
End Sub

Create reference table or array inside of the code

I am trying to create a function that allows me to put in a location number and the result will give me a unique location code. The problem is I want all of the referencing done inside of the macro code, not to get the information from somewhere in the spreadsheet. (this code is going into an add-in so there is no worksheet to reference from). I basically want to do a vlookup but inside of the code, not in a worksheet.
I haven't been able to find out how to do this, the code below is something like what I am looking for, I am thinking maybe the use of an array but I can't figure out how to use it the way I want.
I know this doesn't work but I am trying to do something like this below so that when I type in =GetCode(415) the result is 001
Function GetCode(LocationNum As String) As String
Dim Result As String
'Built in reference table
'
'{ "415" : "001"
' "500" : "002"
' "605" : "003"
' }
Dim varData(2) As Variant
varData("415") = "001"
varData("500") = "002"
varData("605") = "003"
Result = varData(LocationNum)
GetCode = Result
End Function
As Nathan_Sav has already mentioned, you can use a collection or dictionary instead, which are much more efficient. Here's an example using the dictionary object. Note that it uses early binding, so you'll need to set a reference to the Microsoft Scripting Runtime library (Visual Basic Editor >> Tools >> Reference).
Option Explicit
Sub test()
'set a reference (VBE >> Tools >> Reference) to the Microsoft Scripting Runtime library
'declare and create an instance of the dictionary object
Dim dic As Scripting.Dictionary
Set dic = New Scripting.Dictionary
'set the comparison mode for the dictionary to a case-insensitive match
dic.CompareMode = TextCompare
'add keys and associated items to the dictionary
dic.Add Key:="415", Item:="001"
dic.Add Key:="500", Item:="002"
dic.Add Key:="605", Item:="003"
'print to the immediate window the item associated with the specified key
Debug.Print dic("415")
'clear from memory
Set dic = Nothing
End Sub

Is there a way to make an empty array and growing it as it gets data in vb.net?

I have been working on a project, and am attempting to make a new array for data. I have tried making an empty array with Dim Name() As String = {}. I am using a ListView, and the way I have done it there are blank spots where I have gotten rid of data. This is my current code:
Sub English(ByVal Country() As String, ByVal Language() As String)
rbDisplayallData.Checked = False
lstResults.Visible = True
lstResults.Items.Clear()
lstResults.Columns.Clear()
With lstResults
.View = View.Details
.Columns.Add("English Speaking Countries", 200, HorizontalAlignment.Left)
End With
For i = 0 To 181
Dim EnglishSpeakingCountries(i) As String
If Language(i) = "English" Then
EnglishSpeakingCountries(i) = Country(i)
End If
lstResults.Items.Add(New ListViewItem({EnglishSpeakingCountries(i)}))
Next
End Sub
I am trying to get rid of these spaces.
I Was thinking if I were to compact the array or make a new one with the same data going into a new array it would fix the issue.
If you have a solution please let me know.
There are two things that could be considered an empty array
An array with no elements, i.e. a Length of zero.
An array where every element is Nothing.
All arrays are fixed-length. Once you create an array with a particular number of elements, it always has that number of elements. You can use ReDim Preserve or Array.Resize but, in both those cases, what actually happens is that a new array is created and the elements copied from the old array. The new array is assigned to the same variable but anywhere the old array is referenced, it will still have that same number of elements. Try running this code to see that in action:
Dim a1 As String() = {}
Dim a2 As String() = {"First", "Second", "Third"}
Dim b1 = a1
Dim b2 = a2
Console.WriteLine(a1.Length)
Console.WriteLine(a2.Length)
Console.WriteLine(b1.Length)
Console.WriteLine(b2.Length)
Console.WriteLine()
ReDim Preserve a1(2)
Array.Resize(a2, 6)
Console.WriteLine(a1.Length)
Console.WriteLine(a2.Length)
Console.WriteLine(b1.Length)
Console.WriteLine(b2.Length)
Console.ReadLine()
Output:
0
3
0
3
3
6
0
3
As you'll be able to see, a1 and a2 end up referring to new arrays with the specified lengths but the original arrays with the original lengths still exist and are still accessible via b1 and b2.
If you start with an array with no elements then you can use ReDim Preserve or Array.Resize to give the appearance of resizing the array but that's not really what's happening and that should generally be avoided. If you know how many elements you'll end up with then you could create an array of that size and then set each element in turn. You'd need to keep track of the next element index though, so that's still a bit tedious.
Generally speaking, if you want an array-like data structure but you want it to be able to grow and shrink as required, you should use a collection. The most common collection is the List(Of T), where T is any type you care to specify in your code. If you want to store String objects then use a List(Of String). You can call Add to append a new item to the end of the list, as well as Insert, Remove and RemoveAt methods. You can also get or set an item by index, just as you can do for array elements.
Note that a List(Of T) actually uses an array internally and uses the aforementioned method of "resizing" that array. It optimises the process somewhat though, which makes the code easier for you to write and large collections more efficient to use.
It's worth noting that, in your own code, the Columns and Items properties of your ListView are both collections, although they are slightly different to the List(Of T) class.
Looking at your original code, this:
For i = 0 To 181
Dim EnglishSpeakingCountries(i) As String
If Language(i) = "English" Then
EnglishSpeakingCountries(i) = Country(i)
End If
lstResults.Items.Add(New ListViewItem({EnglishSpeakingCountries(i)}))
Next
could be changed to this:
Dim englishSpeakingCountries As New List(Of String)
For i = 0 To 181
If Language(i) = "English" Then
englishSpeakingCountries.Add(Country(i))
lstResults.Items.Add(Countries(i))
End If
Next
Note that you're just adding items to two collections. I guess the question is whether you actually need this extra collection at all. If you do want to use it later then you need to assign it to a member variable rather than a local variable. If you don't need it later then don't create it at all. As I said, you're already adding items to a collection in the ListView. Maybe that's all you need, but you haven't provided enough info for us to know.

Excel VBA - How to search array and return value?

I have some data that looks like this (starting in A1):
Batman
Carl Reiner
Ford
Sushi
But I have a two dimensional array, storing those names, and their type:
Dim Names()
ReDim Names(4,1)
Names(0,0) = "Batman"
Names(0,1) = "Superhero"
Names(1,0) = "Carl Reiner"
Names(1,1) = "Comedian"
Names(2,0) = "Ford"
Names(2,1) = "Car Manufacturer"
Names(3,0) = "Sushi"
Names(3,1) = "Food"
Now, I would like to loop through column A and replace those data points with their equivalent type. I thought there would be a relatively simple way to essentially search Names(x,0) for "Batman" then just replace it with Names(x,1). What's the best way to do so?
I found somewhere that you could possibly use Vlookup with this, so I tried this, to no avail:
Evaluate(WorksheetFunction.Vlookup("A1",Names,1,False)
With my thought being it would look for "Batman" and return the value in Names in the "1" dimension...But that keeps giving me an error (Type 13 Mismatch).
Thanks for any ideas/help!
edit: I found this post and seem to be getting somewhere with Application.Match("A1",Application.Index(Names,0,1),0) which returns the position of "A1" in the array. Now I just need to return the offset and get the "1" position of that...
Edit 2: I think I got it. Using MATCH to find the position of "A1" then just use the array to find it:
Names(Application.Match("A1",Application.Index(Names,0,1),0),1)
So, when A1 is Batman, it finds that position in the index, then it finds the equivalent return in the second dimension.
(Sorry for the lack of semantics, I don't have a very good idea of how to refer to this, so please let me know if I can clarify).
It seems like this would be easier using a Dictionary.
Sub testing()
Dim dic As Object
Set dic = CreateObject("scripting.dictionary")
With dic
.Add "Batman", "Superhero"
.Add "Carl Reiner", "Comedian"
.Add "Ford", "Car Manufacturer"
End With
MsgBox "Batman is a " & dic.Item("Batman")
End Sub
I think if you want to use worksheet functions, you have to put the data into a worksheet (e.g. a column or pair of columns) instead of an array. This is pretty easy to do, though, and you can use a different worksheet, or even another workbook, and there are solutions to hide these, so your users don't have to see that data cluttering the other worksheets.

Can you selectively enable or disable 'FilterDescriptors' in silverlight 4?

In Silverlight with RIA services it is very easy to implement simple data filtering with 'FilterDescriptor' instances.
However I've got a case where I have several filters and I want to enable or disable them based on other filters.
It seems like a simple 'Enabled' property would make this really easy - but there is none.
Is there a way to achieve this without just manually defining all the filters I need every time the relevant checkbox is checked. Perhaps a subclass? (I haven't had time to try this myself yet)
I am doing this by setting each one to -1 by default, and have the IgnoredValue="-1" in the FilterDescriptor. You can also use null or Nothing depending on your language your using.
Ken
Sorting / Filtering / Grouping is really will be easy with using "RIA Services DataFilter Control for Silverlight". http://riadatafilter.codeplex.com/
Use a converter to return a specific value (e.g) 0 for null value or Nothing. Then use 0 as IgnoredValue
Ok, here is what I do. I reset the filter, then set them, you can loop thru them and set them to anything you like...
Private Sub AppPickerComboBox_SelectionChanged(ByVal sender As System.Object, ByVal e As System.Windows.Controls.SelectionChangedEventArgs) Handles AppPickerComboBox.SelectionChanged
For fd As Integer = AppTranDomainDataSource.FilterDescriptors.Count - 1 To 0 Step -1
If AppTranDomainDataSource.FilterDescriptors(fd).PropertyPath = "Application_ID" Then
AppTranDomainDataSource.FilterDescriptors.Remove(AppTranDomainDataSource.FilterDescriptors(fd))
End If
Next fd
AppTranDomainDataSource.FilterDescriptors.Add(New FilterDescriptor With {.PropertyPath = "Application_ID", .Operator = FilterOperator.IsEqualTo, .Value = AppPickerComboBox.SelectedValue, .IgnoredValue = -1})
End Sub

Resources