Check if a Range in Datagridview contains an "," if yes change it to ":" - vb.net

My application contains a Datagridview, the user has the possibility to enter values like: Day, Time, how many hours did he work etc. The problem is that my second application calculates with this data. It has to be in a certain format.
Like time should be "09:15", but i noticed that some users are using "09,15" instead. Can you help me guys, I need a code that can check if a Range in Datagridview contains some " blacklisted char" and if yes, replaces it with the right one.
Thanks for all.

Do not save values as a string.
Validate input string straight in the needed type.
Then validated values pass to the second application.
In this case you don't need "blacklisted chars"
Private Sub DataGridView_CellValidating(sender As Object,
e As DataGridViewCellValidatingEventArgs)
If e.RowIndex < 0 Then Exit sub
Dim dgv As DataGridView = DirectCast(sender, DataGridView)
Dim columnIndexWithInteger As Integer = 2
Dim columnIndexWithDate As Integer = 3
Select Case e.ColumnIndex
Case columnIndexWithInteger
Dim temp As Integer
If Integer.TryParse(e.FormattedValue, temp) = False Then
e.Cancel = True
End If
Case columnIndexWithDate
Dim temp As Date
If Date.TryParse(e.FormattedValue, temp) = False Then
e.Cancel = True
End If
End Select
End Sub

In DataGridView, you have one handle that allows you to check the validity of an edited cell : CellValueValidating. It is called before the user change is taken into account (CellValueChanged event).
You can find example and explanation here :
- https://msdn.microsoft.com/en-us/library/ykdxa0bc(v=vs.110).aspx
- https://msdn.microsoft.com/en-us/library/7ehy30d4(v=vs.110).aspx
You can also have a look at CellValueChanged, CellValueValidated and CellEndEdit events.

Related

Select a specific row from ComboBox and add amount in other Column from same row in DataGridView VB.NET

I'm using VB.NET for a small project. I have a DataGridView with some rows and columns.
I want to send amounts inside a specific row & column. For this purpose I'm using a ComboBox to select the receiver, but I cant manage to select the specific row & column for the amount.
Here is a photo of the form:
[
I managed to add the receivers inside the ComboBox and to add an amount, but in all rows.
This is code (it auto generates the rows for now).
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim rowId As Integer = Me.DataGridView1.Rows.Add()
Dim row As DataGridViewRow = Me.DataGridView1.Rows(rowId)
row.Cells("Column1").Value = "UNITED BANK"
row.Cells("Column2").Value = "1000"
row.Cells("Column3").Value = "ExampleInfo"
Dim rowId2 As Integer = Me.DataGridView1.Rows.Add()
Dim row2 As DataGridViewRow = Me.DataGridView1.Rows(rowId2)
row2.Cells("Column1").Value = "FREE BANK"
row2.Cells("Column2").Value = "2000"
row2.Cells("Column3").Value = "ExampleInfo"
Dim bolAdd As Boolean = False
Dim strValue As String
For Each myRow As DataGridViewRow In Me.DataGridView1.Rows
bolAdd = True
strValue = myRow.Cells("Column1").Value
For Each myItem As String In Me.ComboBox1.Items
If myItem = strValue Then bolAdd = False
Next
If bolAdd AndAlso Not (strValue Is Nothing) Then Me.ComboBox1.Items.Add(strValue)
Next
If Me.ComboBox1.SelectedIndex = -1 Then
Me.ComboBox1.SelectedIndex = 0
End If
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
For Each rowX As DataGridViewRow In Me.DataGridView1.Rows
rowX.Cells(1).Value = Val(rowX.Cells(1).Value) + Val(TextBox1.Text)
Next
End Sub
End Class
With this code, I'm able to add an amount, but to all rows.
I want to add an amount only to the row I selected in the ComboBox.
Your current code in the Button1_Click event is adding the amount from the text box to ALL the rows in the grid regardless of “what” value is selected in the combo box.
From what you describe, you want the amount from the text box to be added to rows that “match” the value in the combo box. The current code is never checking this, so the value from the text box is added to all the rows in the grid.
Therefore, the code needs to check to see if the value in Column1 "Receiver" “matches” the value in the combo box. If it DOES match, then add the value from the text box to the current value in Column2 "USD."
It is unclear if there may be more rows in the grid that have the same Column1 "Receiver" value and if you want to update those values also. I am assuming that there will only be ONE row in the grid that “matches” the value in the combo box. Therefore, once we find this value and add the amount, then we are done and the code will return without looping through the rest of the rows in the grid.
So is what you need to do is alter the code in the button click event to do this checking as described above.
There are a lot of checks we need to make. We need to check that the combo box has a value to compare to. Also, before we check ANY cell value, we need to make sure the cells value is not null BEFORE we try and call the cell's Value ToString method.
In addition, the cell MAY have a value, however, it may not be a number, so we have to check and make sure the value in the cell is an actual number and the same would apply to the text box.
So, walking through the code below would go something like…
If (Int32.TryParse(TextBox1.Text, addedValue)) … checks to see if
the text box amount is a valid number.
If (Not String.IsNullOrEmpty(targetComboValue)) … checks to make
sure the combo box value is not empty.
Then we start the loop through all the rows in the grid.
If (Not rowX.IsNewRow) … checks to see if the row is the “new” row
which we will ignore this “new” row.
If (rowX.Cells("Column1").Value IsNot Nothing) … checks to make
sure the “Receiver” cell is not null
If (rowX.Cells("Column1").Value.ToString() = targetComboValue) …
checks to see if the “Receiver” cells value matches the value in the
combo box.
If (rowX.Cells("Column2").Value IsNot Nothing) … check to make sure
the “USD” cell is not null.
And Finally,…
If (Int32.TryParse(rowX.Cells("Column2").Value.ToString(), currentValue)) … check to see if the value in the “USD” cell is a valid number.
If all these checks succeed then add the value from the text box to the current value in the “USD” cell.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim targetComboValue = ComboBox1.SelectedItem
Dim addedValue As Int32
Dim currentValue As Int32
If (Int32.TryParse(TextBox1.Text, addedValue)) Then
If (Not String.IsNullOrEmpty(targetComboValue)) Then
For Each rowX As DataGridViewRow In Me.DataGridView1.Rows
If (Not rowX.IsNewRow) Then
If (rowX.Cells("Column1").Value IsNot Nothing) Then
If (rowX.Cells("Column1").Value.ToString() = targetComboValue) Then
If (rowX.Cells("Column2").Value IsNot Nothing) Then
If (Int32.TryParse(rowX.Cells("Column2").Value.ToString(), currentValue)) Then
rowX.Cells("Column2").Value = currentValue + addedValue
Return
End If
End If
End If
End If
End If
Next
End If
End If
End Sub
I hope this makes sense.
You can edit the desired row just by using a syntax as follow:
Me.DataGridView1.Rows(1).Cells(2).Value = "your string"
So if you want to select corresponding to your combo index :
Dim myId As Integer = Me.ComboBox1.SelectedIndex
Me.DataGridView1.Rows(myId).Cells(2).Value = "your string"
But this assuming that the count of combo and DataGridView are same.
If not you should think about to add an id Column in your DataGridView ...
If you mean something else please explain, I will edit.

Take list box selection, add value to other list box without allowing duplicates

I have two list boxes on a form I am making. The first list box is linked to a table with various company names. The goal I am after is after double clicking a companies name, the value is inserted in the second list box.
It worked fine until I tried to add code to prevent duplicates from appearing in the second list box, so you couldn't accidentally insert the same company twice. I have tried several different iterations, but with no luck. Anyone able to help with this one? My end goal would be for a msgbox to pop up alerting the user that duplicates are not allowed.
Private Sub ContractorLstbx_DblClick(Cancel As Integer)
Dim found As Boolean
found = False
Dim ID As Long
Dim Contractor As String
For Each newItem In Me.ContractorLstbx.ItemsSelected
For j = 0 To Me.SelectedContractorLst.ListCount - 1
If (Me!ContractorLstbx.ItemData(newItem).Column(1) = Me.SelectedContractorLst.ItemData(j).Column(1)) Then
found = True
Exit For
End If
Next j
If found = False Then
ID = Me.ContractorLstbx.ItemData(newItem)
Me.SelectedContractorLst.AddItem ContractorLstbx!.ItemData(newItem).Column(0) & ";" & Me!ContractorLstbx.ItemData(newItem).Column(1)
End If
found = False
Next newItem
End Sub
This is the full code for your solution. I tried it on test sample and working fine. just copy and paste the code. If you need your comparison to be case sensitive (I mean A <> a) then use Option Compare Binary as in my code below. If it is required to be case insensitive (A = a) just leave the default Option Compare Database or better force it using Option Compare Text
Option Compare Binary
Private Sub ContractorLstbx_DblClick(Cancel As Integer)
Dim found As Boolean
found = False
Dim ID As Long
Dim Contractor As String
For i = 0 To Me.ContractorLstbx.ItemsSelected.Count - 1
For j = 0 To Me.SelectedContractorLst.ListCount - 1
If (Me.ContractorLstbx.Column(1, Me.ContractorLstbx.ItemsSelected(i)) = Me.SelectedContractorLst.Column(1, j)) Then
found = True
Exit For
End If
Next j
If found = False Then
ID = Me.ContractorLstbx.ItemData(Me.ContractorLstbx.ItemsSelected(i))
Me.SelectedContractorLst.AddItem (ContractorLstbx.Column(0, Me.ContractorLstbx.ItemsSelected(i)) & ";" & Me.ContractorLstbx.Column(1, Me.ContractorLstbx.ItemsSelected(i)))
End If
found = False
Next i
End Sub

Microsoft Form - If Checkbox Cell Value Greater Than

First post on this forum - I have a fillable form which I would like to do the following.
There are two check boxes, (Legacy form item), labelled H and N, depending on which one is selected the value of another input box (Legacy form item) should be equal to or greater than a value. E.G if N is selected, the input cell should be greater than 0.5 if H is selected the cell should be equal to or greater than 0.5.
Can anyone impart any wisdom on this one, I would then set it to run a check once the user has input the value, based on the checkbox option and value input into the cell.
Thanks in advance,
Daniel
You have 3 objects and you need to react on any change. So I'd put something like this into the code section of the form:
Private Sub cbN_Click() ' name of checkbox N is cbN
proc_chg
End Sub
Private Sub cbH_Click()
proc_chg
End Sub
Private Sub tbx_Change() ' name of textbox is tbx
proc_chg
End Sub
Private Sub proc_chg
Dim rVal as Single
rVal = Val(Me.tbx.value)
If cbN And rVal > 0.5 Then
tbx.BackColor = vbGreen ' OK
ElseIf cbH And rVal >= 0.5 Then
tbx.BackColor = vbGreen ' OK
Else
tbx.BackColor = vbRed ' wrong
End If
End Sub
This will capture every change on the form and set the background color of the inputbox accordingly. (Please complete the logic in proc_chg, this is just an example.)

Invalid Cast Expectation Was Unhanded (when checking the contents of a text box)

This code is from a subroutine that checks if a text box entry fits the criteria specified (an integer between 1 and 100).
The first IF statement should check if it is not a numerical entry. If it is not numerical then the contents of the text box should be set blank so that a number can be entered.
The second IF statement should check if the number is larger than 100. If it is then the contents of the text box should be set blank so that an appropriate number can be entered.
The Third IF statement should check if the number is smaller than 1. If it is then the contents of the text box should be set blank so that an appropriate number can be entered.
Finally the contents of the box should be set as the variable.
I initially programmed the first IF statement on its own and it worked. But upon adding the others my program would crash when I typed anything into the text box and the error was as stated in my title. I have looked at multiple solutions and have found nothing for almost 2 days that fixed the problem.
Any suggestions would be appreciated.
Public Sub TextBox1_TextChanged(sender As Object, e As EventArgs) Handles NumQTextBoxInput.TextChanged
'Check if input is numeric
If Not IsNumeric(NumQTextBoxInput.Text) Then NumQTextBoxInput.Text = ""
If (NumQTextBoxInput.Text > 100) Then
NumQTextBoxInput.Text = ""
End If
If (NumQTextBoxInput.Text < 1) Then
NumQTextBoxInput.Text = ""
End If
ArchwayComputingExamCreator.GlobalVariables.NumOfQuestions = NumQTextBoxInput.Text
'Setting the variable to the contense
End Sub
You should always use the appropriate parse function when accepting text for numbers.
Public Sub TextBox1_TextChanged(sender As Object, e As EventArgs) Handles NumQTextBoxInput.TextChanged
Dim Value as integer
If Not Integer.TryParse(NumQTextBoxInput.text, Value) OrElse Value < 1 OrElse Value > 100 Then NumQTextBoxInput.Text = ""
... no idea if the archway bit is really what you wanted so left that out ....
End Sub
In this operation:
If Not IsNumeric(NumQTextBoxInput.Text) Then NumQTextBoxInput.Text = ""
Any time the input is not numeric, you set it to a value which is still not numeric. So any numeric comparison will fail:
If (NumQTextBoxInput.Text > 100)
Maybe you meant to set the value to some numeric default?:
If Not IsNumeric(NumQTextBoxInput.Text) Then NumQTextBoxInput.Text = "0"
Or just exit the method entirely when it's not numeric?:
If Not IsNumeric(NumQTextBoxInput.Text) Then
NumQTextBoxInput.Text = ""
Return
End If
Or perhaps something else? However you modify your logic, the point is that you can't perform numeric comparisons on non-numeric strings.

Getting the column names of the selected row in SQL?

I have a program with 2 forms and both forms have their own grid. Grid1 is on form1, Grid2 is on form2. I want Grid2 to serve as a pop up window which is used for editing. When a user doubleclicks a row on Grid1, it should do a requery on just that row and display that single row on Grid2. I can't figure out how to get the column names of the selectedrow then do a query on it's unique identifers. What I have so far:
(This is on form1 by the way)
Public Sub dgvForm1_CellDoubleClick(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles dgvForm1.CellDoubleClick
Dim i As Integer = 0
Dim rowIndex As Integer
Dim cellName as string
While dgvForm1.SelectedRows.Item(0).Cells(i).ColumnIndex < dgvForm1.ColumnCount
rowIndex = dgvForm1.SelectedRows.Item(0).HeaderCell.RowIndex
cellName = dgvForm1.SelectedRows.Item(0).HeaderCell.toString
Select Case cellName
Case "control_no"
Dim sControlNum = cellName.ToString
Case "store_id"
Dim sStoreNum = cellName.ToString
End Select
i = i + 1
End While
end sub
I simply just want the user to doubleclick a row that is displayed on a datagridview with many other records, and that triggers a doubleclick event. This would then loop through the selectedrow's column names until it finds both control_id and store_id and gets their values. P.s. I tried google for a good hour or so but I had a hard time getting any techniques to work.
UPDATE:
I should probably add, this is a bound datagrid that uses sqlClient and its dataadapter/dataset method.
myTable.Columns.ColumnName.
Read more at http://msdn.microsoft.com/en-us/library/system.data.datacolumn.columnname.aspx