Can not update List Box Selected Collection in code - vba

I have a list box on a form being populated from a query, with items selected on basis of matching a delimited list. So sSystemString equals something like "A;B;C"
Then I load records A,B,C,D,E,F from the SQL Server DB and only A,B,C should be selected.
Is there a native way to do this in MS Access (2010). I'm using an ADP in this case.
I'm doing it via code but I can't the selected property does not reflect my changes, nor does the form.
Here's my code:
Dim rs As New ADODB.Recordset
Dim sSystemString As String
If Not IsNull(Me.OpenArgs) Then sSystemString = Me.OpenArgs
' Load this list box with SRC Systems
Call rs.Open("SELECT DISTINCT System FROM dbo.System WHERE System IS NOT NULL", _
CurrentProject.Connection, adOpenForwardOnly, adLockReadOnly)
Do Until rs.EOF
lstSrcSystems.AddItem (rs.Fields(0))
If InStr(sSystemString, rs.Fields(0)) > 0 Then
lstSrcSystems.Selected(lstSrcSystems.ListCount - 1) = True
End If
rs.MoveNext
Loop
My code definitely hits the lstSrcSystems.Selected(lstSrcSystems.ListCount - 1) = True line.
After running this line, inspecting the property in the immediate window still returns 0 (it doesn't change). On the form, the item is also not selected.
UPDATE: I just checked my code again and now it is being updated, but the next AddItem apparently unselects it again.
I suspect I have some weird combination of properties that make this read only, but I can select items interactively, and indeed when I extract the selected items back off in code, the Selected property works as expected - i.e. I select an item on the form and it reflected in this property.
The form is unbound and is called from a button on another form with this code:
DoCmd.OpenForm "fSiteList", acNormal, , , acFormEdit, acDialog, Me.SRCSystems

The problem was actually that lstSrcSystems.AddItem (rs.Fields(0)) was resetting the Selected state. I can't find any mention of this behaviour or how to turn it off. I altered my form as follows:
Form / Data properties all blank (unbound)
List Control / Data / Control Source: blank
List Control / Data / Row Source: SELECT statement populating my list
This has the effect of populating the list but not binding the list or form to anything. (I found that binding it stopped me interactively editing data on it)
Form_Load code behind the form was changed to select already existing items:
Private Sub Form_Load()
Dim sSystemString As String
Dim iIndex As Integer
' List is bound to site list (from connections)
' Highlight those that are listed
If Not IsNull(Me.OpenArgs) Then sSystemString = Me.OpenArgs
iIndex = lstSrcSystems.ListCount
Do While iIndex > 0
If InStr(sSystemString, lstSrcSystems.ItemData(iIndex)) > 0 Then
lstSrcSystems.Selected(iIndex) = True
End If
iIndex = iIndex - 1
Loop
End Sub
I'm still curious to know whether there is a more 'built in' way to achieve this: edit a delimited string field.

Related

"NotOnList" event not recognizing that new data has, in fact, been added

This used to work but now it doesn't. Did Microsoft change something?
I'm attempting to understand the behavior of a combo box in MS Access. I created a table named "Colors" with 2 fields: ID (Autonumber, primary key) and Color (short text). I made a form with a combobox with "LimitToList" set to Yes. The Row Source is the table "Colors". For the NotInList event I have the following code:
Private Sub Colors_NotInList(NewData As String, Response As Integer)
Dim rst As DAO.Recordset
If MsgBox(NewData & " is not in list. Add it?", vbOKCancel) = vbOK Then
Response = acDataErrAdded
Set rst = CurrentDb.OpenRecordset("Colors")
With rst
.AddNew
!Color = NewData
.Update
End With
Else
Response = acDataErrContinue
ctl.Undo
End If
End Sub
If I enter a color not in the table I get the prompt to add it to the list. On clicking OK I get the Access error that I must select an item on the list. The new color I just entered does appear on the list and if I select it everything works fine. But I didn't used to have this second step of selecting it after it's been entered.
I've spent way to much time on what should be a simple task. Can anyone help? Thanks!

VS 2022 project is missing the x64 option, only has Any CPU as option

I am at my wits end. I have a VS 2022 VB Winforms application that was working perfectly fine up until last night. Now I am getting numerous errors, most of which state "Value of type 'ComboBox()' cannot be converted to 'ComboBox()' because 'ComboBox' is not derived from 'ComboBox'". Another error staes "'DropDownWidth' is not a member of 'ComboBox'". The only thing I noticed is that the solution platform now reads "Any CPU" instead of "x64". I did not change any code that has to do with the combobox routines so the errors seemed to have come out of nowhere and the x64 solution platform is no longer an option. Any ideas? I included my code where the errors started popping up.
Public Class GlobalVar
Public Shared cmbBurgType() As ComboBox = {frmSearchNOC.cmbSearchBurgType, frmAddEntry.cmbAddBurgType}
Public Shared cmbSex() As ComboBox = {frmSearchNOC.cmbSearchSex, frmAddEntry.cmbAddSex}
Public Shared cmbRace() As ComboBox = {frmSearchNOC.cmbSearchRace, frmAddEntry.cmbAddRace}
Public Shared cmbPrefix() As ComboBox = {frmSearchNOC.cmbSearchHomeStreetPrefix, frmAddEntry.cmbAddHAddressPrefix}
Public Shared cmbSuffix() As ComboBox = {frmSearchNOC.cmbSearchHomeStreetSuffix, frmAddEntry.cmbAddHAddressSuffix}
Public Shared cmbState() As ComboBox = {frmSearchNOC.cmbSearchHomeState, frmAddEntry.cmbAddHAddressState}
Public Shared cmbPrecinct() As ComboBox = {frmSearchNOC.cmbSearchHomePrecinct, frmAddEntry.cmbAddHAddressPrecinct}
Public Shared cmbTattooLoc() As ComboBox = {frmSearchNOC.cmbSearchTattooLocation, frmAddEntry.cmbAddTattoo}
End Class
Public Sub LoadPresetDBDataCombobox(tableName As String, colName As String, objArray() As ComboBox)
Dim longestEntry As String = ""
Dim curText As String = ""
Dim sqliteReader As SQLiteDataReader
Dim sqliteReadCmd As SQLiteCommand
'clear combobox items
For Each curBox As ComboBox In objArray
curBox.Items.Clear()
Next
OpenDBConn() 'opens the database connection
sqliteReadCmd = GlobalVar.dbConn.CreateCommand()
sqliteReadCmd.CommandText = "Select " & colName & " FROM " & tableName
sqliteReader = sqliteReadCmd.ExecuteReader()
sqliteReadCmd.Dispose() 'disposes read command after it is used
'iterate through table
Using sqliteReader
While sqliteReader.Read
curText = sqliteReader.GetString(colName) 'gets the current table value for the selcted column
'places value into each combobox in array
For Each curBox As ComboBox In objArray
curBox.Items.Add(curText)
Next
'determines the length of the longest string to size to properly dize the drop down width to fit text
If (curText.Length > longestEntry.Length) Then
longestEntry = curText
End If
End While
'assigns the dropdownwidth based on an everage character width of 6 pixels
For Each curBox As ComboBox In objArray
curBox.DropDownWidth = ((longestEntry.Length * 7) + 10)
Next
sqliteReader.Close() 'close object
longestEntry = ""
End Using
CloseDBConn() 'closes the database connection
End Sub
Private Sub OpenChildForm(childForm As Form, formIndex As Integer)
If (currentChildForm IsNot Nothing) Then
currentChildForm.SendToBack()
End If
currentChildForm = childForm 'assigns passed in form as current form
childForm.TopLevel = False 'indicated the form is not top level because the main form is top level
childForm.Dock = DockStyle.Fill 'docks form to fill main form's panel
pnlMain.Controls.Add(childForm) 'adds form to the main panel on the main form
pnlMain.Tag = childForm 'associate form to main panel on main form
childForm.BringToFront() 'brings the related form to the front
childForm.Show()
Select Case formIndex
Case 0 'search noc form
'reloads various data from db into comboboxes in case items were added while on another tab
LoadPresetDBDataCombobox("BurgType", "typeName", GlobalVar.cmbBurgType) 'tattoo location
LoadPresetDBDataCombobox("Sex", "sexName", GlobalVar.cmbSex) 'sex
LoadPresetDBDataCombobox("Race", "raceName", GlobalVar.cmbRace) 'race
LoadPresetDBDataCombobox("StreetPrefix", "prefixName", GlobalVar.cmbPrefix) 'street prefix
LoadPresetDBDataCombobox("StreetSuffix", "suffixName", GlobalVar.cmbSuffix) 'street suffix
LoadPresetDBDataCombobox("State", "stateName", GlobalVar.cmbState) 'state
LoadPresetDBDataCombobox("Precinct", "precinctName", GlobalVar.cmbPrecinct) 'home precinct
LoadPresetDBDataCombobox("BodyPart", "bodyPartName", GlobalVar.cmbTattooLoc) 'tattoo location
Case 1 'browse results form
Case 2 'add entry form
'reloads various data from db into comboboxes in case items were added while on another tab
LoadPresetDBDataCombobox("BurgType", "typeName", GlobalVar.cmbBurgType) 'tattoo location
LoadPresetDBDataCombobox("Sex", "sexName", GlobalVar.cmbSex) 'sex
LoadPresetDBDataCombobox("Race", "raceName", GlobalVar.cmbRace) 'race
LoadPresetDBDataCombobox("StreetPrefix", "prefixName", GlobalVar.cmbPrefix) 'street prefix
LoadPresetDBDataCombobox("StreetSuffix", "suffixName", GlobalVar.cmbSuffix) 'street suffix
LoadPresetDBDataCombobox("State", "stateName", GlobalVar.cmbState) 'state
LoadPresetDBDataCombobox("Precinct", "precinctName", GlobalVar.cmbPrecinct) 'home precinct
LoadPresetDBDataCombobox("BodyPart", "bodyPartName", GlobalVar.cmbTattooLoc) 'tattoo location
Case 3'user settings form
Case 4 'administrator form
End Select
End Sub
Above, the errors come into play with all the GlobalVar parameters as well as the dropdownwidth call:
LoadPresetDBDataCombobox("StreetPrefix", "prefixName", GlobalVar.cmbPrefix)
curBox.DropDownWidth = ((longestEntry.Length * 7) + 10)
I tried updating VS 2022 and then reinstalled it. Neither of which worked, obviously, considering I'm asking this question. It's probably something simple and stupid but I am fried and could use some help.
Thanks to anyone who spent time reading my question. I have no idea how or when the following import got added to one of my routines but I commented it out and all the errors went away:
Imports System.Windows.Controls
I noticed it when I was copying code from my broken project to a new project to see when the errors start popping up. My best guess is that it was importing a combobox control that was different from the combobox I was trying to pass into the routine, but any comments that explain the reason are appreciated.

Check if data exist in file

I need help. I want to check if user exists by entering their ic number and I want to display another rest of their data by using file in visual basic. Unfortunately, an error occurs while doing that. I need help. If the user exists, then It will display automatically name, email, address and so on but if a user doesn't exist, then it shows message box. Here I attached the image of the display screen and the code. Please help me. Thank you.
Public Class Form1
Private Sub btnSearch_Click(sender As Object, e As EventArgs) Handles btnSearch.Click
Dim userFile As String = "C:\Users\HP\Desktop\userdata.txt"
Dim inputFile As String
If System.IO.File.Exists(userFile) = True Then
Dim objReader As New System.IO.StreamReader(userFile)
Dim intIc As Integer
Dim intCount As Integer = 0
Dim strName As String
Dim strEmail As String
Dim intPhoneNum As String
Dim strAdd1 As String
Dim strAdd2 As String
Dim intPostcode As String
Dim strState As String
Do While objReader.Peek() <> -1
intIc(intCount) = Convert.ToInt64(objReader.ReadLine())
If (intIc(intCount).Convert.ToInt64(objReader.ReadLine())) Then
strName(intCount) = objReader.ReadLine()
strEmail(intCount) = objReader.ReadLine()
intPhoneNum(intCount) = Convert.ToInt32(objReader.ReadLine())
strAdd1(intCount) = objReader.ReadLine()
strAdd2(intCount) = objReader.ReadLine()
intPostcode(intCount) = Convert.ToInt32(objReader.ReadLine())
strState(intCount) = objReader.ReadLine()
lblName.Text = strName
lblEmail.Text = strEmail
lblNum.Text = intPhoneNum
lblAdd1.Text = strAdd1
lblAdd2.Text = strAdd2
lblPostcode.Text = intPostcode
lblState.Text = strState
objReader.Close()
Else
MessageBox.Show("User Does Not Exist")
End If
intCount = intCount + 1
Loop
Else
MessageBox.Show("File Does Not Exist")
End If
End Sub
End Class
Your task, the easy way:
make a new project
add a DataSet to this new project
open the DataSet, in the properties call it something sensible
Right click the surface, add a new datatable, name it Person
Right click the datatable, add a column, name it IC. Right click, add column, name it Name. Keep going until you added all the fields you want to track(email,phone,address1 etc)
save the DataSet
open the form
show the datasources window (view menu.. other windows)
expand the nodes til you can see Person
click the drop down next to Person, switch from DataGridview to Details
drag Person onto the form. Text boxes, labels etc appear. In the tray at the bottom more things appear
add a textbox to the form and call it searchTextBox
add a search button to the form, double click it, add this line of code to the click handler:
personBindingSource.Filter = '[ic] LIKE '" & searchTextBox.Text & "'"
If personBindingSource.Count = 0 Then MessageBox.Show("No records")
double click the form background to add a form load event handler, put this line of code:
If IO.File.Exists("data.xml") Then .ReadXml("data.xml")
switch back to designer, single click the form background and switch to event properties of the form, add a handler to the form closing event:
.WriteXml("data.xml")
That's it, you now have a program that will open, read and fill the DataSet with data from the data.xml file, it will search it when you type something in the ic box, the text boxes use databinding to show values automatically, and when you close the program it will save updates data. The only task now is to load the xml file with data.
When the textboxes were added to the form you should also have seen a bar appear across the top with some left/right controls in and a green plus. Click the green plus, type some data in, click it again, type more data. Navigating back, if you're adding new data, will commit the data. If you're looking at existing data, editing it then navigating will commit it
After you added some data, you can search for existing data using the search box. When you've searched for a single value it should be the only thing shown and the nav will show "1 of 1". To get back to the mode where all data is showing, put a single asterisk in the search box and hit search; it should show the number records in the top bar and you can scroll them with the arrows.
If you already have lots of data in a file, like you use in your question, you can read it in a loop (like you do in your question, except don't use that code exactly cos it has loads of errors) as a one time thing and assign it into the datatable, or you can manipulate it directly into being XML in a text editor. This is easy to do if you have a capable text editor but I'll not offer any particular advice on it in case you don't have a large amount of existing data. Ask a new question if you do

Sub to add controls works when called from one sub but the other

I am getting an error that I just can't figure out. I wrote a sub that opens a form in Design view, deletes all of the dynamic controls, then adds the requested number.
The sub gets called in two different ways. The user opening the form (via a Main Menu form) to fill out a new form (so the dynamic controls are deleted then recreated) OR after the form is created, the user can click a button on the form to add more rows of controls. Both the Main Menu and button form call the same sub, BUT when the button is clicked the code gets stuck and error 29054 'Microsoft Access can't add, rename, or delete the control(s) you requested.' is thrown. The button to debug is deactivated so I can't see what line is actually getting stuck, but when I step through the code this is the last line before the error pops up (the last indent block in the context below):
With Application.CreateControl("BOM5", acComboBox, acDetail, frm.Controls("Tabs").Pages(PageNum).Name, , ChangeTypeLeft, LastControlTop, ChangeTypeWidth, ControlHeight)
The rest of the code is as follows.
DoCmd.OpenForm "BOM5", acDesign
Set frm = Application.Forms("BOM5")
' Cycle through controls and set LastControlTop based on the last dynamic control, if any
For i = 0 To frm.Controls.Count - 1
Set ctl = frm.Controls(i)
Debug.Print ctl.Name
If ctl.Tag Like DYNAMIC_TAG & "*" Then
If ctl.ControlType = acComboBox Or ctl.ControlType = acTextBox Then
LastControlTop = ctl.Top + ControlHeight + ControlPadding
FormRowCount = FormRowCount + 1
End If
Else
FormRowCount = (FormRowCount / 6) + 1 ' Convert number of fields to number of rows then add one to start new batch of controls
Exit For
End If
Next
PageNum = frm.Controls("Tabs").Pages.Count - 1 ' .Pages has an index of 0. Getting PageNum to follow suit with the -1
' Add controls for inputting parts
For FormRowCount = FormRowCount To NewControlCount
With Application.CreateControl("BOM5", acComboBox, acDetail, frm.Controls("Tabs").Pages(PageNum).Name, , ChangeTypeLeft, LastControlTop, ChangeTypeWidth, ControlHeight)
.Name = "ChangeType" & FormRowCount
.Tag = DYNAMIC_TAG
.RowSourceType = "Table/Query"
.RowSource = "ChangeType"
End With
The last for loop has 5 other With Application.CreatControl statements, but I just showed the first one. The other 5 are similar except text boxes instead of combo.
I've had this error before, but I think I resolved it by moving the DoCmd.OpenForm statement to a different part of the code (like out of an if statement or for loop or somewhere that wasn't letting it get called) but I don't think that will resolve it. Besides, the first for loop iterates correctly since I see it grabbing the control height of the last dynamic control.
You can't do this. A form or report can only hold a certain amount of controls, deleted or not, so - eventually - it will not accept more controls. At that point, you must recreate the form from scratch.
So, don't delete the controls. Create those you may need and, at any time, hide those not needed and rename the rest if necessary.

Pop up window with textbox after selecting checkbox

all
I am working on a project with vb.net and MySQL database.
Now for taking information I have added few checkboxes, and in case if user selects a checkbox named other I want a window to appear and it should have a text box and when user enters the text at that box, the details should be stored in db.
As you haven't provided much information I may can't answer exactly your question but check if this can help.
First Add LINQ to SQL (.dbml File) - Let's name it as XYZ and Dataset (.xsd File) - let's name this as XYZ too, to your project and then drag and drop your database table in both the files and save all.
Now going into your form which contains the check box you mentioned.
Add this code to you checkbox click_event.
If checkbox1.checked = True Then
Dim insertValue As String = ""
insertValue = InputBox("Enter text to insert", YourTitle, "")
If inserValue <> "" Then
Dim db as New XYZDataContext
Dim NewRec As New YourTableName With {.ColumnName = insertValue}
db.YourTableName.InsertOnSubmit(NewRec)
db.SubmitChanges()
Msgbox("Value added!")
End If
checkbox1.checked = False
End If
create your window in the designer and give it a name like someWindow. then in your code open the window from the click event of your checkbox. when you close the window don't dispose it. just hide it me.hide so when you window closes you can retrieve the data from your textbox.
Sub Test ()
Dim wd_SomeInfo as new someWindow
wd_SomeInfo.showdialog()
Dim result As String = wd_SomeInfo.txt_sometextbox.text
If result = "" Then cancel....
End Sub