Option strict On Vs. Checklistbox.items Vs. Late Binding - vb.net

I have a databinded checklistbox:
With Me.chkChaineSelected
.DataSource = dtChainesTvRadio
.DisplayMember = "Chaînes TV/RADIO"
End With
To get the items checked, i use a loop:
Dim strSelectedLinkeChaine Aa String
For i As Integer = 0 To (chkChaineSelected.Items.Count - 1)
If chkChaineSelected.GetItemChecked(i) Then
strSelectedLinkeChaine = DirectCast(Me.chkChaineSelected.Items(i)("Chaînes TV/RADIO"), String)
End If
Next
But this doesn't work with Option Strict On, the issue is late binding (BC30574) located on Me.chkChaineSelected.Items(i)

Related

What is the best way to loop this program?

This is one of the form, all the usercontrol value in this form will store in My.Settings
I have another form with a FlowLayoutPanel, everytime when the application start,
if Active checked then it will add a Button with discount value to the FlowLayoutPanel.
Should I add those usercontrol to a list and then loop through the list? Or what is the best way to solve this kind of problem?
UPDATED
How can I add multiple item to list in 1 code? I getting this error when system run to line 5
An exception of type 'System.NullReferenceException' occurred in XXX.exe but was not handled in user code
Additional information: Object reference not set to an instance of an object.
Public Sub RefreshDiscount(ByRef ref As scr_mainDiscount)
Dim li_disName As New List(Of TextBox)
Dim li_disValue As New List(Of TextBox)
Dim li_disType As New List(Of ComboBox)
Dim li_active As New List(Of CheckBox)
Dim tb_disName As TextBox() = {ref.tb_name1, ref.tb_name2, ref.tb_name3, ref.tb_name4, ref.tb_name5, ref.tb_name6, ref.tb_name7, ref.tb_name8, ref.tb_name9, ref.tb_name10}
Dim tb_disValue As TextBox() = {ref.tb_value1, ref.tb_value2, ref.tb_value3, ref.tb_value4, ref.tb_value5, ref.tb_value6, ref.tb_value7, ref.tb_value8, ref.tb_value9, ref.tb_value10}
Dim cb_disType As ComboBox() = {ref.cb_type1, ref.cb_type2, ref.cb_type3, ref.cb_type4, ref.cb_type5, ref.cb_type6, ref.cb_type7, ref.cb_type8, ref.cb_type9, ref.cb_type10}
Dim chkb_active As CheckBox() = {ref.CheckBox1, ref.CheckBox2, ref.CheckBox3, ref.CheckBox4, ref.CheckBox5, ref.CheckBox6, ref.CheckBox7, ref.CheckBox8, ref.CheckBox9, ref.CheckBox10}
li_disName.AddRange(tb_disName)
li_disValue.AddRange(tb_disValue)
li_disType.AddRange(cb_disType)
li_active.AddRange(chkb_active)
For index As Integer = 0 To li_active.Count - 1
If li_active(index).Checked = False Then
li_disName.RemoveAt(index)
li_disValue.RemoveAt(index)
li_disType.RemoveAt(index)
li_active.RemoveAt(index)
Else
Dim btn As New ctrl_DiscountButton
With btn
.Text = li_disName(index).Text
.Price = li_disValue(index).Text
.Type = li_disType(index).Text
End With
scr_sales.flp_discount.Controls.Add(btn)
End If
Next
li_disName.Clear()
li_disValue.Clear()
li_disType.Clear()
li_active.Clear()
End Sub
Here's a simple example showing how to find CheckBox1 thru CheckBox10, "by name", using the "searchAllChildren" option of Controls.Find():
For i As Integer = 1 To 10
Dim ctlName As String = "CheckBox" & i
Dim matches() As Control = Me.Controls.Find(ctlName, True)
If matches.Length > 0 AndAlso TypeOf matches(0) Is CheckBox Then
Dim cb As CheckBox = DirectCast(matches(0), CheckBox)
' do something with "cb"
If cb.Checked Then
' ... code ...
' possibly use code just like this to find the matching discount value control?
End If
End If
Next

Reusable function to adjust the width of combobox items to longest item in the list

My intent is to be able to use a function to adjust the width of the drop down so that all items included in the drop down are shown (length wise). I'm trying to create a function where I'll be able to use it for multiple comboboxes. Currently this is being called from a LOAD CBO function, after the data has been loaded however it is not adjusting the .dropDownWidth.
Private Sub AdjustCombobox(ByVal comboboxName As ComboBox)
Dim maxwidth = 0
Dim temp = 0
For Each Item As Object In comboboxName.Items
temp = TextRenderer.MeasureText(Item.ToString(), comboboxName.Font).Width
If temp > maxwidth Then
maxwidth = temp
End If
Next
comboboxName.DropDownWidth = maxwidth
End Sub
EDIT:
comboboxload function
Dim da As New SqlDataAdapter(sql, objconnection)
Dim ds As New DataSet
da.Fill(ds, "Prov")
If ds.Tables("Prov").Rows.Count > 0 Then
With c
.DataSource = ds.Tables("Prov")
.ValueMember = "No"
.DisplayMember = "Name"
.SelectedIndex = -1
End With
End If
First, I would use the actual DataSource, not the items. This allows a really short solution:
Private Function GetMaxDataSize(dt As DataTable, mem As String) As Int32
Dim longestItem = dt.AsEnumerable.Select(Function(q) q.Field(Of String)(mem)).
OrderBy(Function(z) z.Length).
Last()
' assumes as the CBO's use the same Font
Dim longestSize = TextRenderer.MeasureText(longestItem, cboE.Font)
Return longestSize.Width +
SystemInformation.VerticalScrollBarWidth + 5
End Function
Note that the method accounts for the VerticalScrollBarWidth and a slight fudge factor to account for internal gutters, padding, margins etc. If different combos use different fonts, pass each to the method as well. Usage:
' "Text" is the DisplayMember name / column name
cboE.DropDownWidth = GetMaxDataSize(dtLorem, "Text")
Using "Lorem ipsum dolor" fragments, with one especially long one, the result:

Type mismatch user form

I'm getting a error mesage when I run this code.
Dim usf as object
If usfOKNAR01.Visible = True Then
k = 1
Set usf = VBA.UserForms(usfOKNAR01) 'here I'm getting the error
ElseIf usfOKNAR02.Visible = True Then
k = 2
Set usf = VBA.UserForms(usfOKNAR02) 'here I'm getting the error mesage
End If
I want to create a dynamic object control which is reffering to 2 Userforms called usfOKNAR01 and usfOKNAR02.
Depending which is visible the proper will be set and then used like this usf.Controls("txt" & k & "oknar13").Value in other part of my code.
I don't know where the issue can be?
Thank you for your help!
I have removed a part of my code and it seems to work but I don't know if this is the proper way to solve my issue.
Here the new code:
Dim usf as object
If usfOKNAR01.Visible = True Then
k = 1 Set
usf = usfOKNAR01
ElseIf usfOKNAR02.Visible = True Then
k = 2 Set
usf = usfOKNAR02
End If
You can't use the name or the class name as an index to VBA.UserForms - it only accepts Integer index arguments. If you don't know the integer index of the collection, you'll have to iterate over it:
Dim usf As Object
Dim found As Boolean
If usfOKNAR01.Visible = True Then
k = 1
Dim candidate As Object
For Each candidate In VBA.UserForms
If TypeOf candidate Is usfOKNAR01 Then
found = True
Exit For
End If
Next usf
If found Then Set usf = candidate
'...
Since you need to do this at least twice, I'd recommend extracting it to a function.
Note that if either of the forms is not loaded when your code runs, VBA will instantiate them when you test whether they are Visible.

'AddRange' is not a member of... (while i attempt to save column order of a DataGridView

I'm trying to save and load the data grid view column order.
I'm using this code that i suppose is also right.
Private Sub SaveColumnOrder()
Dim upperBound As Integer = Me.DataTable1DataGridView.ColumnCount - 1
Dim columnIndexes(upperBound) As String
For index As Integer = 0 To upperBound
Dim column As DataGridViewColumn = Me.DataTable1DataGridView.Columns(index)
columnIndexes(column.DisplayIndex) = index.ToString()
Next
My.Settings.GridColumnIndexes = New StringCollection
My.Settings.GridColumnIndexes.AddRange(columnIndexes)
End Sub
Private Sub LoadColumnOrder()
Dim columnIndexes As StringCollection = My.Settings.GridColumnIndexes
For displayIndex As Integer = 0 To columnIndexes.Count - 1
Dim index As Integer = CInt(columnIndexes(displayIndex))
Me.DataTable1DataGridView.Columns(index).DisplayIndex = displayIndex
Next
End Sub
Problem is that i don't know how to set the GridColumnIndexes inside project property settings.
I set to string and other "data" options but i always get the error: 'AddRange' is not a member of... {option selected}
Which is the right option in settings to make it finally work? Thank you :)

To iterate through the values of combo box control using vb.net

I update my question here .. Am using a combo box with no of phone numbers .I want to get the phone no one by one in a variable. Now am using the below code to get the combobox values. But still now am getting the following error message System.Data.DataRowView. Please help me to fix this error. am new for vb.net.
My partial code is here ..
For i = 0 To ComboBox1.Items.Count
Dim s As String
s = Convert.ToString(ComboBox1.Items(i))
Next i
you are using an index which is zero based.
change this:
For i = 0 To ComboBox1.Items.Count
to this:
For i = 0 To ComboBox1.Items.Count - 1
This also works!
Dim stgTest = "Some Text"
Dim blnItemMatched As Boolean = False
'-- Loop through combobox list to see if the text matches
Dim i As Integer = 0
For i = 0 To Me.Items.Count - 1
If Me.GetItemText(Me.Items(i)) = stgTest Then
blnItemMatched = True
Exit For
End If
Next i
If blnItemMatched = False Then
Dim stgPrompt As String = "You entered '" & stgTypedValue & "', which is not in the list."
MessageBox.Show(stgPrompt, "Incorrect Entry", MessageBoxButtons.OK, MessageBoxIcon.Information)
Me.Text = ""
Me.Focus()
End If
Your problem probably happens here:
s = Convert.ToString(ComboBox1.Items(i))
This doesn't return the value. It returns a string representation of the object at the given index, which in your case apparently is of type System.Data.DataRowView.
You would have to cast ComboBox1.Items(i) to the approbriate type and access its Value. Or, since its a DataRowView, you can access the values throgh the appropriate column names:
Dim row = CType(ComboBox1.Items(i), System.Data.DataRowView)
s = row.Item("column_name")
Nevertheless, first of all you should definitely close and dispose the connection, no matter whether the transaction fails or succeeds. This can be done in a finally block (option 1) or with a using statement (option 2).
Option 1
// ...
con1 = New MySqlConnection(str)
con1.Open()
Try
// ...
Catch ex As Exception
Lblmsg.Text = " Error in data insertion process....." + ex.Message
Finally
con1.Close()
con1.Dispose()
End Try
Option 2
// ...
Using con1 as New MySqlConnection(str)
con1.Open()
Try
// ...
Catch ex As Exception
Lblmsg.Text = " Error in data insertion process....." + ex.Message
Finally
con1.Close()
End Try
End using
Even after long time back you will achieve this with simply by following
For Each item As Object In combx.Items
readercollection.Add(item.ToString)
Next
Please try this
For j As Integer = 0 To CboCompany.Items.Count - 1
Dim obj As DataRowView = CboCompany.Items(j)
Dim xx = obj.Row(0)
If xx = "COMP01" Then
CboCompany.SelectedIndex = j
Exit For
End If
Next
I could not find this answer online in its entirety but pieced it together. In the snippet below cbox is a ComboBox control that has the DisplayMember and ValueMember properties initialized.
Dim itemIE As IEnumerator = cbox.Items.GetEnumerator
itemIE.Reset()
Dim thisItem As DataRowView
While itemIE.MoveNext()
thisItem = CType(itemIE.Current(), DataRowView)
Dim valueMember As Object = thisItem.Row.ItemArray(0)
Dim displayMember As Object = thisItem.Row.ItemArray(1)
' Insert code to process this element of the collection.
End While