Select Combobox Value Based on Textbox.Text - vb.net

I have a 'Drop Down' style combobox named EmployedCombobox1. I am trying to have EmployedComobox1 automatically select a value depending on the text that is written in a textbox located on another form.
The code below is how my EmployedCombobox is populated:
Private Sub getinstitutionname(ByVal p_institution1_id As Integer)
If sConnection.State = ConnectionState.Closed Then
sConnection.ConnectionString = Search.sqlConnect
sConnection.Open()
End If
Dim sqlAdapter As New MySqlDataAdapter
Dim sqlCommand As New MySqlCommand
Dim sqlTable As New DataTable
Dim InstitutionName As String
Dim sqlText As String = "select * from institution order by institution_name"
Dim InstitutionID As Integer
With sqlCommand
.CommandText = sqlText
.Connection = sConnection
End With
With sqlAdapter
.SelectCommand = sqlCommand
.Fill(sqlTable)
End With
EmployedComboBox1.Items.Clear()
EmployedComboBox1.SelectedIndex = -1
For i = 0 To sqlTable.Rows.Count - 1
InstitutionName = sqlTable.Rows(i)("institution_name")
InstitutionID = sqlTable.Rows(i)("institution_id")
EmployedComboBox1.Items.Add(InstitutionName)
If p_institution1_id = InstitutionID Then
EmployedComboBox1.SelectedIndex = i
End If
Next
sqlTable.Dispose()
sqlCommand.Dispose()
sqlAdapter.Dispose()
Next, the code below is me attempting to auto select the value based off a textbox.text:
Dim sqlAdapter1 As New MySqlDataAdapter
Dim sqlCommand1 As New MySqlCommand
Dim sqlTable1 As New DataTable
Dim sqlText1 As String = "select institution_name from institution where institution_name='" & Institution.InstitutionNameTextBox.Text & "'"
If Search.debugging = True Then
MsgBox(sqlText1)
End If
With sqlCommand1
.CommandText = sqlText1
.Connection = sConnection
End With
With sqlAdapter1
.SelectCommand = sqlCommand1
.Fill(sqlTable1)
End With
For i = 0 To sqlTable1.Rows.Count - 1
Me.EmployedComboBox1.SelectedItem = (sqlTable1.Rows(i)("institution_name"))
Next
sqlTable1.Dispose()
sqlCommand1.Dispose()
sqlAdapter1.Dispose()
When I run that second code, nothing gets selected in the combobox when there is text written in the Textbox.

like you say the values are the same so i would make a AutoCompleteStringCollection for the text box.
And on page load put the items that are in combo box also in the AutoCompleteStringCollection."or after you load you're combo box"
Then add it to the text box
Then for the selecting i would use AutoCompleteMode.Suggest otherwise it will select a item in the combo box if you type 1 letter in the text box.
Dim names As New AutoCompleteStringCollection()
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
ComboBox1.Items.AddRange({"yes", "no", "mmm"})
For Each item As String In ComboBox1.Items
names.Add(item)
Next
With TextBox1
.AutoCompleteMode = AutoCompleteMode.Suggest
.AutoCompleteCustomSource = names
.AutoCompleteSource = AutoCompleteSource.CustomSource
End With
End Sub
For the selecting of the combo box item , first check if the text box text exists in the combo box and then select it."like the code shows below"
i used TextBox1_TextChanged event for it.
Private Sub TextBox1_TextChanged(sender As Object, e As EventArgs) Handles TextBox1.TextChanged
If ComboBox1.Items.Contains(TextBox1.Text) = True Then
ComboBox1.SelectedIndex = (ComboBox1.FindString(TextBox1.Text))
End If
End Sub

Related

Update a ComboBox selection based on a DataGridView cell value?

I want my combo boxes to change based on the what is selected on my datagridview.
What I've tried:
Private Sub MyDataGridView_SelectionChanged2(sender As Object, e As EventArgs) Handles DataGridView2.SelectionChanged
With DataGridView2
If .SelectedRows IsNot Nothing AndAlso .SelectedRows.Count = 1 Then
Dim row As DataGridViewRow = .SelectedRows(0)
Form2.ComboBox1.Text = row.Cells(5).Value.ToString()
Form2.ComboBox2.Text = row.Cells(6).Value.ToString()
Form2.ComboBox3.Text = row.Cells(7).Value.ToString()
Form2.ComboBox4.Text = row.Cells(8).Value.ToString()
Form2.ComboBox5.Text = row.Cells(9).Value.ToString()
Form2.ComboBox6.Text = row.Cells(10).Value.ToString()
Form2.ComboBox7.Text = row.Cells(11).Value.ToString()
Form2.ComboBox8.Text = row.Cells(12).Value.ToString()
Form2.ComboBox9.Text = row.Cells(13).Value.ToString()
End If
End With
End Sub
This code has no effect, but I do feel that I am heading in the right direction.
This is how I inserted my data into the comboboxes:
Dim sqlquery As String = "SELECT * FROM Ingredientes"
Using connection As SqlConnection = New SqlConnection("x")
connection.Open()
Using comm As SqlCommand = New SqlCommand(sqlquery, connection)
Dim rs As SqlDataReader = comm.ExecuteReader
Dim dt As DataTable = New DataTable
dt.Load(rs)
ComboBox1.BindingContext = New BindingContext
ComboBox1.DisplayMember = "Articulo"
ComboBox1.DataSource = dt
' etc
On DataGridView2 properties go to SelectionMode and select FullRowSelected.
Or add this line code on the Form1_Load(sender As Object, e As EventArgs)
DataGridView2.SelectionMode = DataGridViewSelectionMode.FullRowSelect
If can also remove the ".SelectedRows IsNot Nothing AndAlso" because it will always have a value, even there is nothing selected it will return a Zero not a null.

How can I write a loop to replace this if statement for different buttons

I have an Access datatable named A. It has 90 rows and each row has 2 columns as follows:
I have a vb form that has 90 green buttons and code:
Private Sub _1st_Floor_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim myConnection As New OleDbConnection(myConnString)
Dim myCommand As New OleDbCommand("SELECT ID FROM A WHERE Busy=True", myConnection)
myConnection.Open()
Dim reader As OleDbDataReader
Dim dt As New DataTable
dt.Load(myCommand.ExecuteReader)
If dt.Rows(0).Item(0).ToString = 1 Then
Button1.BackColor = Color.Red
Button1.FlatAppearance.BorderColor = Color.Red
End If
If dt.Rows(1).Item(0).ToString = 2 Then
Button2.BackColor = Color.Red
Button2.FlatAppearance.BorderColor = Color.Red
End If
End Sub
This works fine, but I don't want to repeat the same If block over and over again for 90 buttons. How can I write a loop with just one set of code for all 90 buttons?
Loop through your records and find the corresponding buttons:
For Each row As DataRow In dt.Rows
Dim buttonName as String = "button" & row(0).ToString()
Dim cntrls() As Control = Me.Controls.Find(buttonName, True)
If cntrls IsNot Nothing Then
Dim btn As Button = TryCast(cntrls(0), Button)
If btn IsNot Nothing Then
btn.BackColor = Color.Red
btn.FlatAppearance.BorderColor = Color.Red
End If
End If
Next
This is dependent on the buttons' naming scheme being consistent.
Using your own "words" :) maybe not the most efficient way but I just wanted to write this by reusing your code as much as possible...
Private Sub _1st_Floor_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim myConnection As New OleDbConnection(myConnString)
Dim myCommand As New OleDbCommand("SELECT ID FROM A WHERE Busy=True", myConnection)
myConnection.Open()
Dim reader As OleDbDataReader
Dim dt As New DataTable
dt.Load(myCommand.ExecuteReader)
For index As Integer = 1 To 90
If dt.Rows(index - 1).Item(0).ToString = index.ToString Then
Dim button As Button = CType(Me.Controls("Button" + index.ToString), Button)
button.BackColor = Color.Red
button.FlatAppearance.BorderColor = Color.Red
End If
Next
End Sub
I used this post to get controls by name String

Trying to get SUM of ListBox selected items from local DataTable into a Label

I have been searching for days, for any possible reference or suggestions and everything I've come across hasn't worked.
The goal:
User will select options in ComboBox1 that will then determine the available options in ComboBox2, then will populate a list of operations in ListBox1.
When the user selects available operations in ListBox1, I need the output to be the sum of values (total time in minutes in this case) into a label for display.
The data used in stored in a local db. So far everything works with my comboboxes and the listbox.
Im attempting to get the Text value, of all selected items, in ListBox1 to output the numeric value in my table (column 4 "OperationsTime"), into a label that will display the sum of all the selections (Total Time In Minutes).
Some Things I have Tried From Other Posts:
Label9.Text = ListBox1.ValueMember
Label9.Text = ListBox1.ValueMember.ToString
Label9.Text = CType(ListBox1.SelectedItem, DataRowView).Row.Item("OperationsTime").ToString
Attempted using Double:
Dim Total As Double = 0
For Each Time As Integer In ListBox1.SelectedItems
Total += CDbl(Time.ToString.Substring(Time.ToString.LastIndexOf(",") + 1))
Next
Label9.Text = Total.ToString
Screen Shot of the Table:
Operations Data Table
Below is my code:
Imports System.Data
Imports System.Configuration
Imports System.Data.SqlClient
Public Class MainHome
Private Function GetData(ByVal sql As String) As DataTable
Dim constr As String = "Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\hartj\Documents\visual studio 2015\Projects\TIMEMATRIX2.0\TIMEMATRIX2.0\TMX.mdf;Integrated Security=True"
Using con As SqlConnection = New SqlConnection(constr)
Using sda As SqlDataAdapter = New SqlDataAdapter(sql, con)
Dim dt As DataTable = New DataTable()
sda.Fill(dt)
Dim row As DataRow = dt.NewRow()
row(0) = 1
row(1) = "Please Select"
dt.Rows.InsertAt(row, 0)
Return dt
End Using
End Using
End Function
Private Sub MainHome_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
ComboBox1.DataSource = Me.GetData("SELECT SizeId, SizeName FROM Size")
ComboBox1.DisplayMember = "SizeName"
ComboBox1.ValueMember = "SizeId"
ComboBox2.Enabled = False
ComboBox3.Enabled = False
End Sub
Private Sub ComboBox1_SelectionChangeCommitted(sender As Object, e As EventArgs) Handles ComboBox1.SelectionChangeCommitted
ComboBox2.DataSource = Nothing
ComboBox3.DataSource = Nothing
ComboBox2.Enabled = False
ComboBox3.Enabled = False
If ComboBox1.SelectedValue.ToString() <> "0" Then
Dim sql As String = String.Format("SELECT DetailLevelId, DetailLevelName FROM DetailLevel WHERE SizeId = {0}", ComboBox1.SelectedValue)
ComboBox2.DataSource = Me.GetData(sql)
ComboBox2.DisplayMember = "DetailLevelName"
ComboBox2.ValueMember = "DetailLevelId"
ComboBox2.Enabled = True
End If
End Sub
Private Sub ComboBox2_SelectionChangeCommitted(sender As Object, e As EventArgs) Handles ComboBox2.SelectionChangeCommitted
ListBox1.DataSource = Nothing
ListBox1.Enabled = False
If ComboBox2.SelectedValue.ToString() <> "0" Then
Dim sql As String = String.Format("SELECT OperationsId, OperationsName, OperationsTime FROM Operations WHERE DetailLevelId = {0}", ComboBox2.SelectedValue)
ListBox1.DataSource = Me.GetData(sql)
ListBox1.ValueMember = "OperationsName"
ListBox1.ValueMember = "OperationsTime"
ListBox1.Enabled = True
Label9.Text = CType(ListBox1.SelectedValue, Integer).ToString
'Label.Text = CType(cbbank.SelectedItem, DataRowView).Row.Item("Account").ToString
End IF
End Sub
Dim totalOperationsTime As Double
For Each view As DataRowView In ListBox1.SelectedItems
totalOperationsTime += CDbl(view("OperationsTime"))
Next
There's no need to get the DataRow from the DataRowView because you can access the field values directly from the DataRowView. It can and does do many of the same things that the DataRow does.
That's the most conventional way but there are other options too. You could throw some LINQ at it:
Dim totalOperationsTime = ListBox1.SelectedItems.Cast(Of DataRowView)().
Sum(Function(view) CDbl(view("OperationsTime")))
It is somewhat annoying that the ValueMember property only helps you get a value for the SelectedItem. Here's a class I wrote some time ago that adds a GetItemValue method that makes use of the ValueMember much as the GetItemText method does for the DisplayMember:
Public Class ListBoxEx
Inherits ListBox
Public Function GetItemValue(item As Object) As Object
Dim index = Me.Items.IndexOf(item)
If (index <> -1 AndAlso Me.DataManager IsNot Nothing) Then
Return Me.FilterItemOnProperty(Me.DataManager.List(index), Me.ValueMember)
End If
Return Nothing
End Function
End Class
If you use that control instead of a regular ListBox then you can do this:
Dim totalOperationsTime As Double
For Each item In ListBoxEx1.SelectedItems
totalOperationsTime += CDbl(ListBoxEx1.GetItemValue(item))
Next
or this:
Dim totalOperationsTime = ListBox1.SelectedItems.Cast(Of Object)().
Sum(Function(item) CDbl(ListBoxEx1.GetItemValue(item)))
One advantage of using that custom control is that you don't have to know what type the data source or its items are. You only have to know that the ValueMember has been set.
I made a few changes to your code. It works with a ListBox. See comments for details.
' "Please Select" doesn't work well in the ListBox, I added it as an option
Private Shared Function GetData(ByVal sql As String, insertPleaseSelect As Boolean) As DataTable
Dim constr As String = "Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\hartj\Documents\visual studio 2015\Projects\TIMEMATRIX2.0\TIMEMATRIX2.0\TMX.mdf;Integrated Security=True"
Using con As SqlConnection = New SqlConnection(constr)
Using sda As SqlDataAdapter = New SqlDataAdapter(sql, con)
Dim dt As DataTable = New DataTable()
sda.Fill(dt)
If insertPleaseSelect Then
Dim row As DataRow = dt.NewRow()
row(0) = 1
row(1) = "Please Select"
dt.Rows.InsertAt(row, 0)
End If
Return dt
End Using
End Using
End Function
Private Sub MainHome_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
ComboBox1.DataSource = GetData("SELECT [SizeId], [SizeName] FROM [Size]", True)
ComboBox1.DisplayMember = "SizeName"
ComboBox1.ValueMember = "SizeId"
ComboBox2.Enabled = False
ListBox1.SelectionMode = SelectionMode.MultiSimple ' allow multi-select
End Sub
Private Sub ComboBox1_SelectionChangeCommitted(sender As Object, e As EventArgs) Handles ComboBox1.SelectionChangeCommitted
ComboBox2.DataSource = Nothing
ComboBox2.Enabled = False
If ComboBox1.SelectedValue.ToString() <> "0" Then
Dim sql As String = String.Format("SELECT [DetailLevelId], [DetailLevelName] FROM [DetailLevel] WHERE [SizeId] = {0}", ComboBox1.SelectedValue)
ComboBox2.DataSource = GetData(sql, True)
ComboBox2.DisplayMember = "DetailLevelName"
ComboBox2.ValueMember = "DetailLevelId"
ComboBox2.Enabled = True
End If
End Sub
Private Sub ComboBox2_SelectionChangeCommitted(sender As Object, e As EventArgs) Handles ComboBox2.SelectionChangeCommitted
ListBox1.DataSource = Nothing
ListBox1.Enabled = False
If ComboBox2.SelectedValue.ToString() <> "0" Then
Dim sql As String = String.Format("SELECT [OperationsId], [OperationsName], [OperationsTime] FROM [Operations] WHERE [DetailLevelId] = {0}", ComboBox2.SelectedValue)
ListBox1.DataSource = GetData(sql, False)
ListBox1.DisplayMember = "OperationsName" ' changed this from ValueMember to DisplayMember
ListBox1.ValueMember = "OperationsTime"
ListBox1.Enabled = True
ListBox1.ClearSelected() ' Every time the ListBox is populated, clear it
End If
End Sub
' Added this handler to respond to user input, not programmatic selection changes
Private Sub ListBox1_Click(sender As Object, e As EventArgs) Handles ListBox1.Click
' Here is the sum
Label9.Text = ListBox1.SelectedItems.OfType(Of DataRowView).Sum(Function(o) CType(o("OperationsTime"), Double))
End Sub

Runtime datatable update error

I have a datagridview with a checkbox column. When I click(check/Uncheck) on checkbox field as random, two other fields in corrensponding row should be added OR removed in a datatable (declared runtime).
So that I can do some procedures with data in the datatable.
For that I have declared a datatable as global.
Now the problem is, each time when I click on a checkbox, a simple mouse scrolling is required to update datatable, OR a click needed in the new datagridview which is showing values in the datatable.
My code given below,
global declaration: Public PaymentTable As DataTable
Private Sub ShowOrdersFrm_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
DataBind()
Me.DGVOrders.RowsDefaultCellStyle.BackColor = Color.GhostWhite
Me.DGVOrders.AlternatingRowsDefaultCellStyle.BackColor = Color.PaleGoldenrod
PaymentTable = New DataTable()
PaymentTable.Columns.Add("RowId", GetType(Integer))
PaymentTable.Columns.Add("Amount", GetType(Decimal))
End Sub
Private Sub DataBind()
DGVOrders.DataSource = Nothing
DGVOrders.Columns.Clear()
Dim cmd As New SqlCommand
Dim da As New SqlDataAdapter
Dim dt As New DataTable
con.Open()
With cmd
.Connection = con
.CommandText = "select * from VIEW_PAYMENTS_DUES_BYORDER where CustCode='" & CustCode & "' order by OrderNo DESC"
End With
da.SelectCommand = cmd
da.Fill(dt)
BindingSource1.DataSource = dt
DGVOrders.DataSource = BindingSource1
DGVOrders.ClearSelection()
con.Close()
DGVOrders.Columns(0).Visible = False
DGVOrders.Columns(1).HeaderText = "Order No"
DGVOrders.Columns(2).HeaderText = "Cust Code"
DGVOrders.Columns(3).HeaderText = "Name"
DGVOrders.Columns(4).HeaderText = "Order Date"
DGVOrders.Columns(5).HeaderText = "Order Price"
DGVOrders.Columns(6).HeaderText = "Total Payment"
DGVOrders.Columns(7).HeaderText = "Dues"
For i = 0 To DGVOrders.RowCount - 1
If DGVOrders.Rows(i).Cells(7).Value > 0 Then
DGVOrders.Rows(i).Cells(7).Style.ForeColor = System.Drawing.Color.Red
Else
DGVOrders.Rows(i).Cells(7).Style.ForeColor = System.Drawing.Color.Green
End If
Next
' CHECK BOX
Dim colmnchk As New DataGridViewCheckBoxColumn
colmnchk.DataPropertyName = "chkSelect"
colmnchk.HeaderText = "SELECT"
colmnchk.Name = "chkSelect"
DGVOrders.Columns.Add(colmnchk)
For i = 0 To DGVOrders.RowCount - 1
Next
'CHECK BOX END
End Sub
Private Sub DGVOrders_CellValueChanged(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DGVOrders.CellValueChanged
If DGVOrders.Columns(e.ColumnIndex).Name = "chkSelect" Then
Dim checkCell As DataGridViewCheckBoxCell = _
CType(DGVOrders.Rows(e.RowIndex).Cells("chkSelect"), _
DataGridViewCheckBoxCell)
If checkCell.Value = True Then
PaymentTable.Rows.Add(DGVOrders.Rows(e.RowIndex).Cells(0).Value, DGVOrders.Rows(e.RowIndex).Cells(7).Value)
Else
Dim toRemoveID As Integer = DGVOrders.Rows(e.RowIndex).Cells(0).Value
For i = 0 To PaymentTable.Rows.Count - 1
If PaymentTable.Rows(i).Item(0) = toRemoveID Then
PaymentTable.Rows(i).Delete()
Exit Sub
End If
Next
End If
DataGridView1.DataSource = PaymentTable
End If
End Sub
Can sombody to solve the issue, or is there any other good method if my code is wrong ?
Try using a different event like CellContentClick and testing for the ColumnIndex. The drawback with this is the event will fire whenever you click on any cell.
Private Sub DGVOrders_CellContentClick(sender As Object, e As DataGridViewCellEventArgs) Handles DGVOrders.CellContentClick
'Only interested in the CheckBox column
If e.ColumnIndex = colmnchk.Index Then
Debug.WriteLine("In DGVOrders_CellContentClick for the checkbox")
End If
End Sub

How to get datetimepicker to work

I Have a excel sheet with dates that I want to use datetimepicker with (only date needed). I just want to click on datetimepicker, choose a date and it must show me the info in my data grid view. this is my button code.
I have a txt box that I have tried, but cannot get the date, I have now put a datetimepicker box, but cannot get ii to work.
any help on this.
Here are my main code
Imports System.Data.OleDb
Public Class Tapes_info
Private dtGlobal As New DataTable
Private Sub Tapes_info_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
dtGlobal.Clear()
Using cn As New OleDb.OleDbConnection
Dim Builder As New OleDbConnectionStringBuilder With {.DataSource = IO.Path.Combine(Application.StartupPath, "Backuptapes.xls"), .Provider = "Microsoft.ACE.OLEDB.12.0"}
Builder.Add("Extended Properties", "Excel 12.0; IMEX=1;HDR=No;")
cn.ConnectionString = Builder.ConnectionString
cn.Open()
Using cmd As OleDbCommand = New OleDbCommand With {.Connection = cn}
cmd.CommandText = "SELECT TOP 5130 F1 As Tapes, F2 As Containere, F3 as ContainerRef, F4 as DateOut FROM [Tapese$]"
Dim dr As System.Data.IDataReader = cmd.ExecuteReader
dtGlobal.Load(dr)
LstTape.DisplayMember = "Tapes"
LstTape.DataSource = dtGlobal
txtContainer.DataBindings.Add("Text", dtGlobal, "Containere")
txtContainerRef.DataBindings.Add("Text", dtGlobal, "ContainerRef")
txtDateOut.DataBindings.Add("Text", dtGlobal, "Dateout")
End Using
End Using
End Sub
Here is my button code, I want to display any date that I want.
Private Sub BtnSearchDateOut_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnSearchDateOut.Click
For i As Integer = 0 To dtGlobal.Rows.Count - 1
If IsDBNull(dtGlobal.Rows(i)("Dateout")) Then
dtGlobal.Rows(i)("Dateout") = ""
End If
Next
Dim query = From item In dtGlobal.AsEnumerable() Where item.Field(Of String)("Dateout").StartsWith(txtSearchDateOut.Text) Select item
If query.Count > 0 Then
Dim newDT As DataTable = query.CopyToDataTable()
MsgBox(newDT.Rows.Count.ToString() & " Date out found.")
Dim frm As New Form()
Dim dgv As New DataGridView()
dgv.DataSource = newDT
dgv.Refresh()
frm.Controls.Add(dgv)
dgv.Dock = DockStyle.Fill
frm.Size = New Size(1400, 700)
frm.Show()
Else
MsgBox("There is no Date for this found.") 'message
End If
I'm not sure how you're using the date to filter the results but you'll want to start by getting the date from the dateTimePicker; like this: Dim dt As Date = Me.DateTimePicker1.Value Then you can use dt.date as the input for filtering.