Default values when adding a new record - vb.net

I am trying to add a new record with the Binding Navigator Add button. I have three fields that can be defaulted on the new record. UserId, Start time and End Time. Using the code below I am able to set the Start and End time but not the User Combobox. Is it not possible to set this value?
I have tried setting the value in the BindingNavigatorAddNewItem_Click
Private Sub BindingNavigatorAddNewItem_Click(sender As Object, e As EventArgs) Handles BindingNavigatorAddNewItem.Click
'MsgBox("Add new Log")
Dim User As String = currUser.Name
Dim Index As Integer = cmbOperator.FindString(User)
cmbOperator.SelectedIndex = Index
cmbOperator.SelectedItem = User
dtpLogIn_Date.Value = currUser.Start_Time
dtpLogOut_Date.Value = currUser.End_Time
End Sub
Form after add new redraw

One solution is to set the cmbOperator index in the BindingSource_PositionChanged event. My guess is this fires after the record position changed. Then I wrapped it in code to check if the was a add new. Probably could have put it in the BindingNavigator_PositionChanged as well.
Dim varShiftKey = Shift_LogBindingSource.Current("Shift_Key")
If varShiftKey = -1 Then
Dim User As String = currUser.Name
Dim Index As Integer = cmbOperator.FindString(User)
cmbOperator.SelectedIndex = Index
End If

Related

Making One Column of DataGridView AutoComplete for String Data

I am trying to set up a DataGridView in VB.Net where a single column, called "Supplier" acts as a TextBox with an AutoCompleteSource to help users with entering data. This is the code I put together to attempt to accomplish this:
Private Sub OrderData_EditingControlShowing(ByVal sender As Object, ByVal e As DataGridViewEditingControlShowingEventArgs) Handles orderData.EditingControlShowing
Dim colIndex = orderData.SelectedCells.Item(0).ColumnIndex
Dim headerText As String = orderData.Columns(colIndex).HeaderText
If headerText.Equals("Supplier") Then
Dim autoText As TextBox = TryCast(e.Control, TextBox)
If autoText IsNot Nothing Then
autoText.AutoCompleteMode = AutoCompleteMode.SuggestAppend
autoText.AutoCompleteSource = AutoCompleteSource.CustomSource
autoText.AutoCompleteCustomSource = FillTextBoxData("supplier_name", "suppliers")
End If
End If
End Sub
I kind of works. Unfortunately it adds AutoCompletes to every single editable column in the table, instead of just the "Supplier" column (column index 2).
What do I need to do to fix this?
EDIT: I modified the code a bit to try and fix the issue, and it kind of worked. If I don't selected the "Supplier" column first, then the other columns to not contain an AutoComplete. However if I go from the "Supplier" column to another column, then it contains an AutoComplete. How do I fix this?
When you do
Dim headerText As String = orderData.Columns(2).HeaderText
If headerText.Equals("Supplier") Then
That will be always true, since you are always getting the col 2 header no matter what cell is selected, you need to add that, something like
Dim colIndex = orderData.SelectedCells.Item(0).ColumnIndex
then you can use your code
Dim headerText As String = orderData.Columns(colIndex).HeaderText
Also add an Else clause to the If headerText.Equals("Supplier") Then statement. In the Else portion add the line autoText.AutoCompleteMode = AutoCompleteMode.None

Datatables Not Merging VB.NET

I have some code that is intended to:
1. Loop through a datagrid that is user populated
2. Search an access database using the input criteria
3. Return the results as a datatable
4. Merge additional results to that datatable
5. Bind the merged table results to a DataGridView
The query works, results return as expected with a single value search. The query will also return one of the two test values if I use the user input DataGridView. However, it will not combine the two results before outputting to the results_DataGridView. I have also tried using .Fill from the adapter to add onto my temp table and use that as the datasource.
Option Strict On
Dim dt_TempTable As New DataTable
Dim dt_ContentsTable As New DataTable
Dim SerialNumbers As New List(Of String)
Dim PanelIDs As New List(Of String)
Dim MultiSearch As Boolean
Private Sub bgwk_data_DoWork(sender As Object, e As System.ComponentModel.DoWorkEventArgs) Handles bgwk_data.DoWork
If Not (MultiSearch) Then
Retrieveinfo(Me.txt_SerialNumber.Text, Me.txt_PanelID.Text) 'Local
Else
Dim arrSN As String() = SerialNumbers.ToArray()
Dim arrPID As String() = PanelIDs.ToArray()
For i = 0 To arrSN.Count - 1
If i > 0 Then
Retrieveinfo(arrSN(i), arrPID(i)) 'Local - Run query and create a new temp table of results
dt_ContentsTable.Merge(dt_TempTable) 'Merge new temp table to current contents table
Else
dt_ContentsTable = Retrieveinfo(arrSN(i), arrPID(i)) 'Return the original temp table to the contents table (datagridview datasource)
End If
Next
End If
End Sub
'Gets the Data by SerialNumber and saves it to dt_TempTable to be bound afterwards
Private Function Retrieveinfo(SerialNumber As String, PanelID As String) As DataTable
Dim ds As New datasource
Dim tblAdapt As New datasourceTableAdapters.toHTML_SPC_DataTableAdapter
tblAdapt.GetData(dt_TempTable, SerialNumber, PanelID)
Return dt_TempTable 'Return the table
End Function
'Updates dg_data with the datatable from Retrieveinfo and refreshes the form
Private Sub bgwk_dataRunWorkerCompleted(sender As Object, e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles bgwk_data.RunWorkerCompleted
'Unlocks ability to search new things
Me.txt_PanelID.ReadOnly = False
Me.txt_SerialNumber.ReadOnly = False
Me.dg_data.ReadOnly = False
'Binds the backgroundworker results to the datagridview
Me.dg_data.DataSource = Nothing
Me.dg_data.DataSource = dt_ContentsTable
Me.dg_data.Refresh()
Me.Refresh()
End Sub
I understand that merge can be used on DataTables, but perhaps this is incorrect usage?
I'd go with a condition in the multi-search loop:
If dt_ContentsTable.Rows.Count = 0 Then
dt_ContentsTable = dt_TempTable.Clone()
End If
dt_ContentsTable.Merge(dt_TempTable)
This way, the first time, its at least creating the columns of the dt_ContentsTable.
I also don't see any code in the single search where dt_ContentsTable is assigned. So, in the single search, I recommend you assign dt_ContentsTable to dt_TempTable.

Pass integer value from one form to another in VB.NET

I'm writing a program that has two forms. One form gets the user to enter multiple values, and then does some calculations. Then it passes that information to another form However I can't figure out how to do it. Here is a relevant part of my code. To head some confusion, I am trying to pass 11 values, also initially, form 2 is not shown, and then when the values are passed from form 1 to form 2, then form 1 goes away and form 2 is the only one that shown
NOTE: This is not all my code, I don't believe all my code is required (I have 1000 lines right now) However this is the code with the information I want to be passed to the other form.
A lot of people are apparently saying that this is a duplicate of another question, however that question, he seems to already know how to pass the variables, but is just having issues with it (and even with looking at his, i cant figure it out)
Private Sub btnSubmit_Click(sender As Object, e As EventArgs) Handles btnSubmit.Click
'declarations
Dim intNormal As Integer
Dim intChildren As Integer
Dim intBonanza As Integer
Dim intDiamond As Integer
Dim intPictureFrame As Integer
Dim intKite As Integer
Dim intCrazyT As Integer
Dim intLetterX As Integer
Dim int2PostageStamp As Integer
Dim intPick7 As Integer
Dim intJackpot As Integer
Validate()
If txtNormal1.Enabled = False Then
intNormal = intNormInput
Else
intNormal = CalcNormalBooks()
End If
If txtChildren1.Enabled = False Then
intChildren = intChildInput
Else
intChildren = calcChildrensBooks()
End If
If txtBonanza1.Enabled = False Then
intBonanza = intBonInput
Else
intBonanza = calcBonanza()
End If
If txtSpecial1.Enabled = False Then
intSpecial = intSpeInput
Else
intSpecial = calcSpecialBooks(intSpecial)
End If
If txtDiamond1.Enabled = False Then
intDiamond = intDiaInput
Else
intDiamond = calcDiamond(intSpecial)
End If
If txtPictureFrame1.Enabled = False Then
intPictureFrame = intPicInput
Else
intPictureFrame = calcPictureFrame(intSpecial)
End If
If txtKite1.Enabled = False Then
intKite = intKiteInput
Else
intKite = calcKite(intSpecial)
End If
If txtCrazyT1.Enabled = False Then
intCrazyT = intCrazyInput
Else
intCrazyT = calcCrazyT(intSpecial)
End If
If txtLetterX1.Enabled = False Then
intLetterX = intLettInput
Else
intLetterX = calcLetterX(intSpecial)
End If
If txt2PostageStamp1.Enabled = False Then
int2PostageStamp = intPostInput
Else
int2PostageStamp = CalcPostageStamp(intSpecial)
End If
If txtPick71.Enabled = False Then
intPick7 = intPickInput
Else
intPick7 = calcPick7(intSpecial)
End If
If txtJackpot1.Enabled = False Then
intJackpot = intJackInput
Else
intJackpot = calcJackpot()
End If
End Sub
Since I had almost the same requiremnt lately here is my solution:
Custom Event which fires when your 2nd Form is closing
Public Event HotKeyFormClosed As EventHandler(Of HotKeyFormClosedEventArgs)
Custom EventArgs class where you store your values you want to pass to Main Form
Public Class HotKeyFormClosedEventArgs
Inherits EventArgs
'Your properties here
Public Sub New(...) 'your params here
MyBase.New()
'set your properties here
End Sub
End Class
On 2nd Form handle FormClosed event and pass your values to EventArgs
Private Sub HotKey_FormClosed(sender As Object, e As System.Windows.Forms.FormClosedEventArgs)
RaiseEvent HotKeyFormClosed(Me, New HotKeyFormClosedEventArgs(...)) 'your params here
End Sub
On Main Form handle your custom event (here HotKeyFormClosed) and extract its values
AddHandler frmHotKey.HotKeyFormClosed, AddressOf HotKey_FormClosed;
...
Private Sub HotKey_FormClosed(sender As Object, e As HotKeyFormClosedEventArgs)
'Do stuff with values from e
End If
I have chosen the Event approach since it decouples the two forms from another.
One could easily duplicate the information on both forms, make them public and access it directly thru an object instance.
But I like the observable approach from the events more due to it gives mor flexibility (additonal forms using the same events etc.)
P.S.: I wrote my code in c# and blind entered the VB code here so be gracious.
The values/variables that a method expects to receive (specified in the method's signature) are called Parameters.
The values sent to a method when the method is called are called Arguments.
As long as the arguments used when calling a method match the parameters for that method, those values can be passed.
For example (and I'll try to apply this to your context), if you want to create an instance of a form that takes certain values, you can specify those parameters in the form's New event, like so:
Public Sub New(someInt As Integer)
'do something with someInt here
End Sub
Then when you call this method you'd pass it the arguments, like so:
Dim myInt As Integer = 10
Dim newForm As myForm = New myForm(myInt)
When I say the arguments need to match the parameters, that means the number of values, the order of those values, and the value types must be the same (or in the case of numbers the parameter's type must be the same or larger than the argument's type).
As long as that is true, then it shouldn't really matter how you pass these - you could pass 11 individual arguments, you just have to make sure you are matching the argument to the parameter.
Hope that helps!

Trying to move items from one to the other

]I am having strange problem when i try to move items from one grid view to another using a bindingsource it adding in an extra blank row some reason
Private Sub btnMove_Click(sender As System.Object, e As System.EventArgs) Handles btnMove.Click
Dim bs As New BindingSource
Dim a As Integer
Dim removeList As List(Of infoRemoteFiles) = fileList
For a = 0 To grdAvailFiles.SelectedRows.Count
grdProcessFiles.Rows.Add(grdAvailFiles.Rows(a).Cells("filename").Value)
removeList.RemoveAll(Function(p As infoRemoteFiles) p.filename = grdAvailFiles.Rows(a).Cells("filename").Value)
Next
bs.DataSource = removeList
grdAvailFiles.DataSource = bs
End Sub
please see what i mean its the row below what I have selected I dont no where its comming from thanks
The extra blank row is added automatically if you have the AllowUserToAddRows property set to True on the DataGridView control.
From the documentation:
If the DataGridView is bound to data, the user is allowed to add rows if both this property and the data source's IBindingList.AllowNew property are set to true.
On a separate note, you shouldn't have to create anew binding source (for the source data grid). Instead, modify the collection that is already bound to the DataSource property.
Try:
For A = 0 To grdAvailFiles.SelectedRows.Count - 1
Note the minus 1, because you're starting from zero.

Error trying to rebind DataSource to DataGridViewComboBoxCell?

I have a DataGridView with two DataGridViewComboBoxColumns. I want to use the selected item in the first column to trigger a re-population of the items in the second column, on a per-row basis.
Here's the code I have so far. "addlInfoParentCat" identifies the first column, and currentRow.Cells.Item(1) is the DataGridViewComboBoxCell that I want to re-populate. ExtEventAdditionalInfoType is a type I defined that contains the string/value pairs.
Private Sub dgvAdditionalInfo_CellValueChanged(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles dgvAdditionalInfo.CellValueChanged
Dim currentCell As DataGridViewCell
currentCell = Me.dgvAdditionalInfo.CurrentCell
If Not currentCell Is Nothing Then
If currentCell.OwningColumn.DataPropertyName = "addlInfoParentCat" Then
Dim parentTypeID As Integer = currentCell.Value
Dim currentRow As DataGridViewRow = Me.dgvAdditionalInfo.CurrentRow
Dim subtypeCell As DataGridViewComboBoxCell = currentRow.Cells.Item(1)
Dim theChildren As New List(Of ExtEventAdditionalInfoType)
theChildren = Custom_ExtEventAdditionalInfoType.GetChildrenOfThisParentOrderByTypeName(parentTypeID)
subtypeCell.DataSource = Nothing
subtypeCell.DataSource = theChildren
subtypeCell.DisplayMember = "ExtEventAdditionalInfoTypeDescr"
subtypeCell.ValueMember = "ID_ExtEventAdditionalInfoType"
End If
End If
End Sub
Basically what I see is that the binding works great the first time around. When I select a item in the first column, it populates the items correctly in the second. I can add rows to the DataGridView and repeat the process.
The problem comes when I try to change the first-column item after the second column has already been bound. I get an endless string of dialog boxes with the following:
System.ArgumentException: DataGridViewComboBoxCell value is not valid.
Any idea why this is happening? Thanks in advance!
UPDATE CodeByMoonlight's suggestion appears to work.
I clear the DataGridViewComboBoxCell's value before re-binding:
....
subtypeCell.DataSource = Nothing
subtypeCell.Value = Nothing 'here's the change
subtypeCell.DataSource = theChildren
....
Well, it looks like as soon as you remodify the first combo's value, you're invalidating the binding and datasource you used to populate the second combo, causing all the errors.