How to only check empty visible Maskedtextboxes in vb.net? - vb.net

I have about 50 Maskedtextboxes, only few of them are visible. What I need is to only check the visible ones if they are empty.
I used this code to check all Maskedtextboxes:
Dim empty = TabLABOR.Controls.OfType(Of MaskedTextBox)().Where(Function(txt) txt.Text.Length = 0)
If empty.Any Then
MessageBox.Show(String.Format("Please fill all fields",
String.Join(",", empty.Select(Function(txt) txt.Name))))
Else
TabControlBlockD.SelectTab(TabMATERIALS)
End If
End Sub

you should use a for each like the following
dim myfrm as MyCurrentForm()
then
for Each item As System.Windows.Forms.Control In myfrm.Controls
If item.GetType Is GetType(System.Windows.Forms.MaskedTexbox) Then
For Each mboxes As MaskedTexbox In item.Controls
If MaskedTexbox.text = "" AND maskedTextbox.visible = true Then
//Make deltu king of the world
End If
Next
End If
Next
That should work.
edit:

Related

How to use function to prevent duplicated record for datagridview

I use function to prevent the same record goes into my datagridview but it doesnt work , when i separate the code out then its worked
i tried to seperate the for loop part out then the code work , but i wan to use function to do it so the code look more neater
Private Sub PicFavNote10_Click(sender As Object, e As EventArgs) Handles picFavNote10.Click
If validationDataGrid(lblNameNote10.Text) <> True Then
'if item didn added to the favorite data table yet
'add to favorite table
addTofavorite(lblUserLogin.Text, lblNameNote10.Text, lblDecpNote10.Text, txtPicNote10.Text, "SmartPhone", lblPriceNote10.Text)
End If
lblPriceNote10.Text = FormatCurrency(lblPriceNote10.Text)
End Sub
Private Function validationDataGrid(ByRef data As String) As Boolean
'validation on data grid view
For Each itm As DataGridViewRow In DGTFavTable.Rows 'loop though every item in datagrid
If itm.Cells(0).Value = data Then 'check wherter the text already exist
MsgBox(data & " Already added to your favorite cart")
Return True
Else
Return False
End If
Next
End Function
I expected the MsgBox(data & " Already added to your favorite cart") will excecute but instead the validationDataGrid function return false value even the item is already added to favorite datagridview
Before you loop all rows you need to call this sub as is an efficient workaround to validate new data on DataGridView:
Private Sub ForceGridValidation()
'Get the current cell
Dim currentCell As DataGridViewCell = DGTFavTable.CurrentCell
If currentCell IsNot Nothing Then
Dim colIndex As Integer = currentCell.ColumnIndex
If colIndex < DGTFavTable.Columns.Count - 1 Then
DGTFavTable.CurrentCell = DGTFavTable.Item(colIndex + 1, currentCell.RowIndex)
ElseIf colIndex > 1 Then
DGTFavTable.CurrentCell = DGTFavTable.Item(colIndex - 1, currentCell.RowIndex)
End If
'Set the original cell
DGTFavTable.CurrentCell = currentCell
End If
End Sub

Search listview for multiple results

I have accomplished to search my list view item, but unfortunately it shows the first result only and nothing beyond that
This is my code
Private Sub ULButton1_Click(sender As Object, e As EventArgs) Handles ULButton1.Click
If ComboBox2.Text = "" Then
MessageBox.Show("Please select an office")
Else
Dim itm As ListViewItem
itm = Me.ListView2.FindItemWithText(TextBox1.Text)
If Not itm Is Nothing Then
ListView2.SelectedItems.Clear()
ListView3.Clear()
ListView3.View = View.Details
ListView3.FullRowSelect = True
ListView3.GridLines = True
ListView3.Sorting = SortOrder.Ascending
ListView3.Columns.Add("Username", CInt(ListView1.Width / 2))
ListView3.Columns.Add("Name", CInt(ListView1.Width / 2))
Me.ListView2.Items.Item(itm.Index).Selected = True
For Each itm2 As ListViewItem In Me.ListView2.SelectedItems
Me.ListView3.Items.Add(ListView2.Items(itm2.Index).Clone())
Next
Else
MessageBox.Show("Not Found", "")
End If
itm = Nothing
End If
End Sub
When I enter a string in the textbox, this code will show results of listview item in another listview, is there a way I can modify this to show multiple related items to the string I enter in the textbox?
Thank you
FindItemWithText finds only the first matching item.
You would need to use another form or that function that takes the starting index and keep finding next item in a loop.
Also, this fragment looks strange:
Me.ListView2.Items.Item(itm.Index).Selected = True
For Each itm2 As ListViewItem In Me.ListView2.SelectedItems
Me.ListView3.Items.Add(ListView2.Items(itm2.Index).Clone())
Next
You iterate over selected items, but you just selected one! An you already know it's index...

What is wrong with my subroutines?

So I've been working on this project for a couple of weeks, as I self teach. I've hit a wall, and the community here has been so helpful I come again with a problem.
Basically, I have an input box where a user inputs a name. The name is then displayed in a listbox. The name is also put into an XML table if it is not there already.
There is a button near the list box that allows the user to remove names from the list box. This amends the XML, not removing the name from the table, but adding an end time to that name's child EndTime.
If the user then adds the same name to the input box, the XML gets appended to add another StartTime rather than create a new element.
All of this functions well enough (My code is probably clunky, but it's been working so far.) The problem comes when I try to validate the text box before passing everything through to XML. What I am trying to accomplish is that if the name exists in the listbox on the form (i.e hasn't been deleted by the user) then nothing happens to the XML, the input box is cleared. This is to prevent false timestamps due to a user accidentally typing the same name twice.
Anyhow, I hope that makes sense, I'm tired as hell. The code I've got is as follows:
Private Sub Button1_Click_2(sender As System.Object, e As System.EventArgs) Handles addPlayerButton.Click
playerTypeCheck()
addPlayerXML()
clearAddBox()
End Sub
Private Sub playerTypeCheck()
If playerTypeCBox.SelectedIndex = 0 Then
addMiner()
ElseIf playerTypeCBox.SelectedIndex = 1 Then
addHauler()
ElseIf playerTypeCBox.SelectedIndex = 2 Then
addForeman()
End If
End Sub
Private Sub addMiner()
If minerAddBox.Text = String.Empty Then
Return
End If
If minerListBox.Items.Contains(UCase(minerAddBox.Text)) = True Then
Return
Else : minerListBox.Items.Add(UCase(minerAddBox.Text))
End If
If ComboBox1.Items.Contains(UCase(minerAddBox.Text)) = True Then
Return
Else : ComboBox1.Items.Add(UCase(minerAddBox.Text))
End If
End Sub
Private Sub addPlayerXML()
If System.IO.File.Exists("Miners.xml") Then
Dim xmlSearch As New XmlDocument()
xmlSearch.Load("Miners.xml")
Dim nod As XmlNode = xmlSearch.DocumentElement()
If minerAddBox.Text = "" Then
Return
Else
If playerTypeCBox.SelectedIndex = 0 Then
nod = xmlSearch.SelectSingleNode("/Mining_Op/Miners/Miner[#Name='" + UCase(minerAddBox.Text) + "']")
ElseIf playerTypeCBox.SelectedIndex = 1 Then
nod = xmlSearch.SelectSingleNode("/Mining_Op/Haulers/Hauler[#Name='" + UCase(minerAddBox.Text) + "']")
ElseIf playerTypeCBox.SelectedIndex = 2 Then
nod = xmlSearch.SelectSingleNode("/Mining_Op/Foremen/Foreman[#Name='" + UCase(minerAddBox.Text) + "']")
End If
If nod IsNot Nothing Then
nodeValidatedXML()
Else
Dim docFrag As XmlDocumentFragment = xmlSearch.CreateDocumentFragment()
Dim cr As String = Environment.NewLine
Dim newPlayer As String = ""
Dim nod2 As XmlNode = xmlSearch.SelectSingleNode("/Mining_Op/Miners")
If playerTypeCBox.SelectedIndex = 0 Then
newMinerXML()
ElseIf playerTypeCBox.SelectedIndex = 1 Then
newHaulerXML()
ElseIf playerTypeCBox.SelectedIndex = 2 Then
newForemanXML()
End If
End If
End If
Else
newXML()
End If
End Sub
Private Sub nodeValidatedXML()
If playerTypeCBox.SelectedIndex = 0 Then
minerValidatedXML()
ElseIf playerTypeCBox.SelectedIndex = 1 Then
haulerValidatedXML()
ElseIf playerTypeCBox.SelectedIndex = 2 Then
foremanValidatedXML()
End If
End Sub
Private Sub minerValidatedXML()
If minerListBox.Items.Contains(UCase(minerAddBox.Text)) = False Then
appendMinerTimeXML()
End If
End Sub
Private Sub appendMinerTimeXML()
Dim xmlSearch As New XmlDocument()
xmlSearch.Load("Miners.xml")
Dim docFrag As XmlDocumentFragment = xmlSearch.CreateDocumentFragment()
Dim cr As String = Environment.NewLine
Dim newStartTime As String = Now & ", "
Dim nod2 As XmlNode = xmlSearch.SelectSingleNode("/Mining_Op/Miners/Miner[#Name='" & UCase(minerAddBox.Text) & "']/StartTime")
docFrag.InnerXml = newStartTime
nod2.AppendChild(docFrag)
xmlSearch.Save("Miners.xml")
End Sub
And lastly, the clearAddBox() subroutine
Private Sub clearAddBox()
minerAddBox.Text = ""
End Sub
So, I should point out, that if I rewrite the nodeValidated() Subroutine to something like:
Private Sub nodeValidatedXML()
If playerTypeCBox.SelectedIndex = 0 Then
appendMinerTimeXML()
ElseIf playerTypeCBox.SelectedIndex = 1 Then
appendHaulerTimeXML()
ElseIf playerTypeCBox.SelectedIndex = 2 Then
appendForemanTimeXML()
End If
End Sub
then all of the XML works, except it adds timestamps on names that already exist in the list, which is what i'm trying to avoid. So if I haven't completely pissed you off yet, what is it about the minerValidated() subroutine that is failing to call appendMinerTimeXML()? I feel the problem is either in the minerValidated() sub, or perhaps clearAddBox() is somehow firing and I'm missing it? Thanks for taking the time to slog through this.
Edit: Clarification. The code as I have it right now is failing to append the XML at all. Everything writes fine the first time, but when I remove a name from the list and then re-add, no timestamp is added to the XML.
You need to prevent the user accidentally typing the name twice.(Not sure if you mean adding it twice)
For this I believe you need to clear the minerAddBox.Text in your addminer() if this line is true.
minerListBox.Items.Contains(UCase(minerAddBox.Text)) = True
minerAddBox.Text = ""
Return
Now it will return back to your addplayerXML which will Return to your clearbox(), since you have this in your addplayerXML()
If minerAddBox.Text = "" Then
Return
Now you get to your clearbox() (Which is not really needed now since you cleared the minerAddBox.Text already)
when I remove a name from the list and then re-add, no timestamp is added to the XML.
your minerValidatedXML() is true, because you are not clearing the textbox when you re-add a name to the list box. Or you may need to remove the existing listbox item if it is the same as the textbox
If minerListBox.Items.Contains(UCase(minerAddBox.Text)) = True Then
minerListBox.Items.remove(UCase(minerAddBox.Text))

How to search in listview

I am trying to create a Loop that will read through the information on my ListView through the SubItem to find the text that matches the text in my Textbox whenever I hit the search button and Focuses the listbox onto the matched text. Below is what I have but it keeps telling me that the value of string cannot be converted. I am also pretty sure that my numbers wont loop correctly but I am not really sure how to cause them to loop endlessly till end of statement.
Dim T As String
T = Lines.Text
For r As Integer = 0 to -1
For C As Integer = 0 to -1
If List.Items(r).SubItems(C).Text = Lines.Text Then
List.FocusedItem = T
End If
Next
Next
End Sub
I don't understand your code, but I do understand the question. Below is example code to search all rows and columns of a listview. Search is case insensitive and supports a "find next match" scenario. If a match or partial match is found in any column the row is selected. TextBox1 gets the text to find. FindBtn starts a new search.
Private SrchParameter As String = ""
Private NxtStrtRow As Integer = 0
Private Sub FindBtn_Click(sender As Object, e As EventArgs) Handles FindBtn.Click
If Not String.IsNullOrWhiteSpace(TextBox1.Text) Then
SrchParameter = TextBox1.Text
NxtStrtRow = 0
SearchListView()
End If
End Sub
Private Sub ListView1_KeyDown(sender As Object, e As KeyEventArgs) Handles ListView1.KeyDown
If e.KeyCode = Keys.F3 Then
SearchListView()
End If
End Sub
Private Sub SearchListView()
' selects the row containing data matching the text parameter
' sets NxtStrtRow (a form level variable) value for a "find next match" scenario (press F3 key)
If ListView1.Items.Count > 0 Then
If SrchParameter <> "" Then
Dim thisRow As Integer = -1
For x As Integer = NxtStrtRow To ListView1.Items.Count - 1 ' each row
For y As Integer = 0 To ListView1.Columns.Count - 1 ' each column
If InStr(1, ListView1.Items(x).SubItems(y).Text.ToLower, SrchParameter.ToLower) > 0 Then
thisRow = x
NxtStrtRow = x + 1
Exit For
End If
Next
If thisRow > -1 Then Exit For
Next
If thisRow = -1 Then
MsgBox("Not found.")
NxtStrtRow = 0
TextBox1.SelectAll()
TextBox1.Select()
Else
' select the row, ensure its visible and set focus into the listview
ListView1.Items(thisRow).Selected = True
ListView1.Items(thisRow).EnsureVisible()
ListView1.Select()
End If
End If
End If
End Sub
Instead of looping like that through the ListView, try using a For Each instead:
searchstring as String = "test1b"
ListView1.SelectedIndices.Clear()
For Each lvi As ListViewItem In ListView1.Items
For Each lvisub As ListViewItem.ListViewSubItem In lvi.SubItems
If lvisub.Text = searchstring Then
ListView1.SelectedIndices.Add(lvi.Index)
Exit For
End If
Next
Next
ListView1.Focus()
This will select every item which has a text match in a subitem.
Don't put this code in a form load handler, it won't give the focus to the listview and the selected items won't show. Use a Button click handler instead.
This is the easiest way to search in listview and combobox controls in vb net
dim i as integer = cb_name.findstring(tb_name.text) 'findstring will return index
if i = -1 then
msgbox("Not found")
else
msgbox("Item found")
end if

cannot get selectedvalue of combobox, returns empty

I'm sure this is really something stupid in my code, but I cannot get the selected value from my combobox for the life of me. Here is my code.
Dim objScales As List(Of My.Scale) = Nothing
Dim ExistingDimScale As Double = 0
Dim ExistingDimScaleIndex As Double = 0
_ScaleForm = New ScaleForm
Try
Me.LoadProperties()
If Me.ConfigUnits <> 0 Then
'Get the right scales per units
If Me.ConfigUnits = 1 Then 'imperial
objScales = Me.GetImperialScales()
Else
objScales = Me.GetMetricScales()
End If
'Load up the combobox values
If objScales IsNot Nothing Then
_ScaleForm.cmbScale.DisplayMember = "Name"
_ScaleForm.cmbScale.ValueMember = "DimScale"
For Each objScale In objScales
_ScaleForm.cmbScale.Items.Add(objScale)
'MsgBox(objScale.Name.ToString)
Next
'Set the selected Index to the current dim scale
Double.TryParse(Autodesk.AutoCAD.ApplicationServices.Application.GetSystemVariable("Dimscale").ToString, ExistingDimScale)
ExistingDimScaleIndex = objScales.FindIndex(Function(Val) Val.DimScale = ExistingDimScale)
If ExistingDimScaleIndex = -1 Then
_ScaleForm.cmbScale.SelectedIndex = 0
Else
Integer.TryParse(ExistingDimScaleIndex.ToString, _ScaleForm.cmbScale.SelectedIndex)
End If
Else
MsgBox("There were no scales set")
End If
Else
Throw New System.Exception("Error Reading Configuration Units")
End If
Catch ex As System.Exception
MsgBox(ex.Message)
'handle it here internally
End Try
_ScaleForm.ShowDialog()
If DialogResult.OK = 1 Then
MsgBox(_ScaleForm.cmbScale.SelectedValue)
End If
The second from the last line MsgBox(_ScaleForm.cmbScale.SelectedValue), this is where I want to use the selected value to do stuff but it keeps popping up empty in the messagebox. I'm tired and unsure of why it's not working.
You are not setting the DataSource property of the ComboBox but inserting every item one by one in the items collection. Try to set the DataSource
_ScaleForm.cmbScale.DataSource = objScales
and you will get the SelectedValue set.
In alternative you could read the SelectedItem property that will return a Scale object if something has been selected and then get the DimScale field from this instance
if DialogResult.OK = _ScaleForm.ShowDialog() Then
if _ScaleForm.cmbScale.SelectedItem IsNot Nothing Then
My.Scale obj = CType(_ScaleForm.cmbScale.SelectedItem, My.Scale)
....
End If
End If