Multi-Criteria Search via three comboxes in vb.net with sql back end - sql

I am currently working in VB.net with an sql back end server. I have a windows form application with a datagridview and 3 combo boxes that have data from three different columns in the datagridview. So far I have used IF statements for multi-criteria searches. This method has proven to be a long and inefficient way to write this code. It is literally a long run of IF statements saying if combobox1.selectedindex does not equal 1 and combobox 2 and 3 are still on the -1 index then search with just the first combo box. Then I write the code for every single possibility of the comboboxes being filled out. Whether it is 2 or all of them, or just one of them. I am wondering if there is a solid tutorial or a way to loop through these comboboxes to make this code quick and simple.

Something like this should get you started. It defines a list of combo boxes which you want to check and then determines which ones have a SelectedIndex <> -1. If it doesn't then the value is recorded.
' Build a list of values based on combo boxes with a selected index.
Dim values As New List(Of String)
' Build an array of combo boxes we want to process.
For Each cb As ComboBox In New ComboBox() {comboBox1, comboBox2, comboBox3}
' Check if the current combo box has an index selected.
If cb.SelectedIndex <> -1 Then
' It does - record its value.
values.Add(cb.Text)
End If
Next
' Do something with the values.
MessageBox.Show(String.Join(", ", values.ToArray))
' For example, build a where clause.
' If you do this, be sure to sanitize the values.
MessageBox.Show("WHERE 0=1 " & String.Join(" OR Field=", values.ToArray))

Related

How do I use ONE control source with MULTIPLE combo boxes from a USER FORM, in Access?

I am currently developing A quote sheet for work, I have 21 Combo boxes that are all populated by the same row source. The problems that I am having are When all my combo boxes are set to the same control source all the list values in the combo box are filtered and set to one value. For example combo box 1 is selected and prep is selected now the other 20 combo boxes are set to prep, and I can't select the other options. Now if I have no control source for my combo boxes than previous example works. If I select combo box 1 and set it to prep then I can select combo box 2,3,4... and put any value I want for each one. I want to be able to have each combo box with its own value.
The reason I am wanting the combo boxes to have the same control source is so when a combo box has a selected value it will add a new record to my table. So if 10 combo boxes have values selected then there will be 10 new rows added to my table when I click my add record button.
I am thinking a maybe having a loop do the work, but am not to familiar with with using vba to run sql??
You can't use the same control sources to generate multiple records on the same form. They must be unbound. At least, I don't know how to make that work the way you have it set up, but can still help.
Delete the control sources but keep the row sources.
You will need a query to save the values to your table:
INSERT INTO MyTableName ([MyFieldName]) VALUES ('[ComboboxValue]');
Copy this code and paste in query builder. Overwrite "MyTableName" and "MyFieldName" with the appropriate object names for where you want a single combobox value to be saved. It only adds one row at a time. [ComboboxValue] will be the parameter we use to pass each combo value to the query to execute.
Name the query whatever you want and save it. I will use the placeholder "MyQuery," make sure you update it!
Create a command button on your form, and in its On Click event, paste in this VBA code (you will need to update the combobox references where I use Me!ComboboxName):
Dim qdf As DAO.QueryDef
Dim combo As String
Set qdf = CurrentDb.QueryDefs("MyQuery")
combo = Me!Combobox1Name
qdf!ComboboxValue = combo
qdf.Execute
combo = Me!Combobox2Name
qdf!ComboboxValue = combo
qdf.Execute
'Copy those three lines for each combobox, adjust your combobox references accordingly,
'or use a loop
'End your procedure like this:
Set qdf = Nothing
If you are using a multi-column combobox, you may need to adjust the reference from Me!Combobox1Name to Me!Combobox1Name.Column(1).

Write individual listbox items into different text boxes and repeat until all text boxes are full

I'm programming in Visual Basic.
I have one form.
Form 1 contains:
nameTextBox
addNameButton
namesListBox
generateButton
week1TextBox
week2TextBox
week3TextBox
week4TextBox
The user needs to go to Form 1 and type a name in the text box, then add the name to the List Box. The user will add 4 names to the List Box. So, the ListBox will contain the names: Adam, Brenda and Carol.
When the generateButton is clicked, the 3 names have to be written to the text boxes in that order. So week1TextBox should contain "Adam", week2TextBox should contain "Brenda", etc... but once the last name (in this case "Carol") is written into the text box, the loop should start over. Ultimately, there may be up to 50 week text boxes (so week50TextBox). So the loop needs to repeat over and over.
As there is a lack of source code in your question, I'm really not sure exactly how the layout should look, I can only offer some advice/suggestions.
I would recommend creating your listbox control, input textbox, and button to add names to the listbox. In addition to these, though, also add a scrollable panel. (Not sure what the exact term for that control is in VB.net; it's been a long time since I've worked with that language.) Because it sounds like there might be a variable number of items on the panel, when the user goes to generate the list of names, I would use the following rough pseudocode:
Dim OutputTexts As New ArrayList ' This is only here if you want to work with these textboxes later
Private Sub CreateOutput() Handles btnGenerate.Click
pOutputPanel.Controls.Clear()
OutputTexts.Clear()
Dim NextX As Integer = 0 ' Pretty much unnecessary value, but included in case you want to mess with this
Dim NextY As Integer = 0
For i As Integer = 0 To Convert.ToInt32(txtWeekCount.Text)
Dim txtName As New TextBox
txtName.Text = lbNameList.Item(i Mod lbNameList.Items.Count)
txtName.Location = new Point(NextX, NextY) ' Play with this as necessary
NextY += 50 ' Play with this as necessary
OutputTexts.Add(txtName)
pOutputPanel.Controls.Add(txtName)
Next
End Sub
Again, this is very much pseudocode, so I would not encourage copying and pasting, but give it a read, make sure you understand all of it, and then try implementing something similar. There might be an easier way to do it, but I have not programmed in VB.NET in probably over 2 years (at least). Nonetheless, the most important thing in here is the following line: lbNameList.Item(i Mod lbNameList.Items.Count). By Mod-ing your indexing variable, you will be accessing items sequentially, and then repeating from the start of the ListBox items collection once i is out of range.
I would also encourage you to dynamically generate your TextBox controls as needed rather than manually adding in 50 or more TextBox controls.

How to make a reset button in excel

I am trying to make a reset button that will replace any value the user has selected with the value TOTAL inside a number of comboboxes. Using the record macro i selected the combobox but i can't figure out how to insert the value. The following code gives out the 424 error.
ActiveSheet.Shapes.Range(Array("ComboBox2")).Select.Value = TOTAL
the part that i added to the macro is the .Value=TOTAL
Anyone knows what i should do? Please take note that i don't want to clear the comboboxes; I want to give them a specific value.
In case that combo boxes are Form controls use OLEFormat.Object.ListIndex to select the item.
In case that the combo boxes are ActiveX controls use OLEFormat.Object.Object.ListIndex (note in this case the first item in the list has index 0).
Then iterate through all Combo-boxes you want to reset and set ListIndex to index of item "TOTAL". In this example the item "TOTAL" is on the first place in the list so for Form Combo-box (if used) ListIndex = 1 and for ActiveX Combo-box ListIndex = 0. HTH
(You are probably using ActiveX Combo-boxes, but in the example the older Form Combo-boxes are used as well just for the case).
Sub ResetToTotal2()
Dim combos
Dim combo
Dim comboObject
combos = Array("ComboBox1", "ComboBox2", "ComboBox3")
For Each combo In combos
Set comboObject = ActiveSheet.Shapes(combo).OLEFormat.Object
If TypeName(comboObject) = "DropDown" Then
comboObject.ListIndex = 1
Else
comboObject.Object.ListIndex = 0
End If
Next combo
End Sub

Searching a bound Combo Box for User Input

Alright Gents,
Im trying to search a vb.net combo box for an item. The combo box is already bound to dataset. The display member is set to display just a single column of the selected record. I had it set initially so the objects displayed in the combo were a customized class. In this class I specified all the properties I wanted to keep track of and that seemed to work well. However now that I am using the combo box in its bound state it is much more difficult to manipulate the data.
Mission:
To have the user type a number, if the number is contained in the ComboBox, the combo box should then move to that record so that all the other items bound to that control will update as well.
Research:
I have looked into the System.Windows.Forms.BingingManagerBase class and that seems to have the information I need. I just can't figure out the bridge between that and what I'm trying to do. I want to throw something together so I tried to simply do a SQL search against the dataset for the text in the combobox. Unfortunately that requires late binding and my targeted version of the .Net compact framework does not support that.
Here is an example of the late binding I was attempting. (Im working with VB.net 2005, Compact Framework 3.5 I believe:
For i as integer = 0 to combobox.items.count - 1
dim Dsr as Dataset.Row
dim dv as dataview
Dsr = DirectCase(Dv.row, Dataset.Row)
If Dsr(i).DesiredColumn = DesiredRow.Desiredcolumn then
'Do such and such code
End If
Next
I want to be able to search the dataset for a specific record matching a query. After I find that row matching the query I want to be able to move my combo box to the row found in the SQL query. The main problem seems to be that the Combo works in Datarowviews and my datasets are mostly cast to rows pertaining to the DS.
Anyone have some insight on this it would be much appreciated.
Thanks again!
If you know the item that should be set as selected in the combobox you can just set the ComboBox.SelectedItem Property
If you actually do really need to loop through all the items bound to the combobox then once you reach the correct one you can set the ComboBox.SelectedIndex Property.
For i As Integer = 0 To ComboBox.Items.Count - 1
Dim drv As System.Data.DataRowView = Nothing
Dim desiredColumn As String = String.Empty
drv = DirectCast(ComboBox.Items.Item(i), DataRowView)
desiredColumn = Convert.ToString(drv("Tag"))
Debug.WriteLine(desiredColumn)
Next
This seems to find the column value for every record in the combo box allowing me to find the correct index of the text I am searching for. Like I said though, if I could find a way to search through the list of items in the combobox without having to address each one, I would be grateful.

Populate Text box on access form based on the value of combo box on the same form [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
MSAccess - populate text box with value from query
I have a single form on which there exists several combo boxes and text box. one combo box value (for the Wells) will be filled independently, then I needs the text box to have its value based on the value of the wells combo box value.
I have created a query that solved the propblem partially, it requires parameter which the wells combo box value. If I ran with query a part from the form, it wroks good and asks for the parameter and it is OK.
I do think to make use of VBA, adding a code which process a SELECT statement (of the query mentioned above), then to tell it to take its parameter from the wells combo value which will ready on the form.
Can someone help on this. Can this works as I descriped.
Thanks in advance.
Mohamed
Further to my question above, I have tried the following solution:
Private Sub Well_ID_Change()
Last_Ref.ControlSource = " SELECT TOP1 New_Ref FROM" & _
" BSW_Transactions WHERE BSW_Transactions.New_Ref Is Not Null AND BSW_Transactions.Well_ID = " & Me.Well_ID.Value & _
" ORDER BY BSW_Transactions.Sample_Date DESC"
End Sub
the Last_Ref is the text box I want to fill in with result of the embedded SELECT statement in the code. The Well_ID is the combo box which value will be the parameter of the SELECT statement. The Well_ID is number field and it displays the well_name and stores the associated ID value in the table. Upon running the form after saving changes, the Last_Ref text box showed (#Name?). I guessed that the text box (is a number field) found a text in the combo box Well_ID, so I added ".Value" to the above syntax at the criteria Me.Well_ID. However the problem still exists.
May I mistaken in the syntax, would someone help on this. Can this works fine?
Thanks in advance.
Mohamed
You are doing this the wrong way around. Bind the form to a table, the wizards will do it for you, then add the combobox. Choose "Find a record on my form" from the wizard. The code or macro to do this will be generated. Once this is done, selecting a record in the combo will populate the form with the data for that record.
Try this in the AfterUpdate event of your combo box:
Private Sub MyTextBox_AfterUpdate()
MyTextBox.ControlSource = DLookup("WellsField", "WellsTable", "CriteriaField = '" & [MyComboBox] & "'")
MyTextBox.Requery
End Sub
This will tell your TextBox to lookup the value in your Wells table and the Requery ensures the value is up to date every time your combo box is updated. Note the ' in the criteria part of DLookup. These ' are only required for String values.