Does anyone know how to dynamically add an array to a bunch of comboboxes in VB.net? I could really use the help (I've been struggling with this all day). When I try to do it my way I get an error on form load.
My code:
Private Sub Form1_Load(ByVal sender as Object, ByVal e as EventArgs) Handles Me.Load
Dim MyArray() as String = {"a","b","c"}
For each ctl as ComboBox in Me.Controls
if ctl.tag = "yadda" then ctl.Items.AddRange(MyArray)
Next
End Sub
Error: "Unable to cast object of type '...Button' to type '...Combobox'."
I've tried so many variations to this code but I just can't get it to work. I will eventually have nearly a hundred similarly constructed comboboxes in my application, and I'd like to be able to programmatically initialize their items. Could someone please help?
Thanks,
Elias
This is the way to do it :
Public Class Form1
Function getControl(ByVal controlName As String) As Control
Dim numCtrls = Me.Controls.Count()
For I As Integer = 0 To numCtrls - 1
If Me.Controls.Item(I).Name = controlName Then
If TypeOf Me.Controls.Item(I) Is ComboBox Then
Return CType(Me.Controls(controlName), ComboBox)
End If
End If
Next
End Function
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim myArray As Array = {"a", "b", "c"}
Dim myComboBox As ComboBox
For Each ctl As Control In Me.Controls
If TypeOf ctl Is ComboBox Then
If ctl.Tag = "yadda" Then
myComboBox = getControl(ctl.Name)
myComboBox.Items.AddRange(myArray)
End If
End If
Next
End Sub
End Class
You loop through all controls (buttons, combo, etc ...) then you check if it is the type you want (ComboBox) and do whatever you need.
Good luck !
Related
I have a radgridview with a cell whose data may contain an apostrophe. When the row is selected, the row context is cast to a collection of public properties. This works well except for the cell with an apostrophe.
Private Sub dgSelectOrder_MouseLeftButtonDown(sender As Object, e As MouseButtonEventArgs)
Dim row = TryCast(sender, GridViewRow)
Dim selectedOrder = TryCast(row.DataContext, myProperties)
If the cell data has an apostrophe, for example LET'S GO, the property returns the value LET''S GO. The apostrophe is doubled. If that data gets saved back to the database, then retrieved again, the property returns LET''''S GO.
How do I cast the row data correctly?
Public Class myProperties
Public Property pProjectNbr As String = String.Empty
Thanks.
I shouldn't have to do this but it's the only way it would work. I have similar code to cast the row.datacontext elsewhere. And that code runs as expected with the apostrophe.
Private Sub dgArchivedOrders_MouseLeftButtonDown(sender As Object, e As MouseButtonEventArgs)
Dim row = TryCast(sender, GridViewRow)
Dim selectedOrder = TryCast(row.DataContext, myProperties)
If selectedOrder.pProjectNbr.Contains("''") Then
Dim convertThis As String = selectedOrder.pProjectNbr
selectedOrder.pProjectNbr = convertThis.Replace("''", "'")
End If
I have several arrays named : Array1, Array2, Array3, ... and also some comboboxes named: cboArray1, cboArray2, cboArray3, ....
How can i write a GENERAL code to add elements of each array to corresponding combox. I know following code works, but its not GENERAL and ABSTRACT.
For i = 0 To Array1.Length - 1
cboArray1.Items.Add(Array1(i))
Next
For i = 0 To Array2.Length - 1
cboArray2.Items.Add(Array2(i))
Next
...
Working procedure maybe as follows: 1. Find all comboboxes in form (easy) 2. extract name of a combox (easy) 3. find similar-named array from code (difficult) 4. ....
I can use other sets like List, ... if it makes sense.
Here's what you're asking for using Reflection...though I'm not sure how useful this really is:
Public Class Form1
Private Array1 As String() = {"cat", "dog", "fish"}
Private Array2 As String() = {"alpha", "beta", "gamma"}
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
WireComboBoxes(Me)
End Sub
Private Sub WireComboBoxes(ByVal container As Control)
For Each ctl As Control In container.Controls
If TypeOf ctl Is ComboBox AndAlso ctl.Name.ToUpper.StartsWith("CBO") Then
Dim cb As ComboBox = DirectCast(ctl, ComboBox)
Dim arrName As String = cb.Name.Substring(3)
Dim fi As System.Reflection.FieldInfo = Me.GetType.GetField(arrName, Reflection.BindingFlags.Instance Or Reflection.BindingFlags.Public Or Reflection.BindingFlags.NonPublic Or Reflection.BindingFlags.IgnoreCase)
If Not IsNothing(fi) Then
cb.DataSource = fi.GetValue(Me)
End If
ElseIf ctl.HasChildren Then
WireComboBoxes(ctl)
End If
Next
End Sub
End Class
I have a LinkLabel which is set up to receive some URLs that result from making a selection in a ComboBox. What I'm trying to accomplish is for the user to select a state from my combo, and then be able to click the individual links that appear in link label.
Having my links in array, what I'm getting is the array displays the links as "one whole" string, and I want them to separate links. Here's what I have:
Public arrAlabama(2) As String
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
' Create array for Alabama and add items.
arrAlabama(0) = "http://www.rolltide.com/"
arrAlabama(1) = "http://www.crimsontidehoops.com/"
arrAlabama(2) = "http://centralalabamapride.org/"
End Sub
Private Sub cboSelectState_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cboSelectState.SelectedIndexChanged
' Populate the link label.
If cboSelectState.SelectedIndex = 0 Then
lnklblLinkbox.Text = arrAlabama(0) _
& vbNewLine & arrAlabama(1) _
& vbNewLine & arrAlabama(2)
End If
End Sub
I'll have about 3 other arrStateName type arrays, so my SelectedIndex will span from [0] to [3], and each array will contain 3 URL links.
So where am I going wrong here? If anyone can give me a boost in the right direction I would appreciate it. Some suggested using Dictionary data type, but I'm new to and when I tried test it out, I got frustrated because it doesn't seem to produce the results I want. Using the TKey and TValue throws me off, and I can never get all of my links to display in the box. I used Integer for my keys, and String for my values (links), but couldn't make it work. Some much needed guidance would be appreciated. Is what I'm trying to do possible, or should I be using some other control types?
Make a class object:
Public Class StateLinks
Public Property State As String
Public Property Links As New List(Of String)
Public Overrides Function ToString() As String
'tells the combobox what to display
Return State
Public Sub New(state As String)
Me.State = state
End Sub
End Class
Load some statesLinks into a List(OF T):
Private stateLinksList As New List(Of StateLinks)
Private Sub LoadMe() Handles Me.Load
Dim coState As New StateLinks("Colorado")
coState.Links.Add("some link")
stateLinksList.Add(coState)
' continue adding then bind them
cboSelectState.DataSource = stateLinksList
End Sub
Get the links from the selection:
Private cb_selectionChanged() Handles cboSelectState.SelectedIndexChanged
Dim state = TryCast(cb.SelectedItem, StateLinks)
If Not state Is Nothing
For Each link As String In state.Links
'each link now available
Next
End If
Add a RichTextBox and set Detect Urls = true, BorderStyle = None, Backcolor = color of form, if it is on form. The size should be large enough to hold the url's. Then
Private Sub cboSelectState_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cboSelectState.SelectedIndexChanged
'Populate RichTextBox1.
If cboSelectState.SelectedIndex = 0 Then
RichTextBox1.Text = arrAlabama(0) _
& vbNewLine & arrAlabama(1) _
& vbNewLine & arrAlabama(2)
End If
End Sub
In
Private Sub RichTextBox1_LinkClicked(sender As System.Object, e As System.Windows.Forms.LinkClickedEventArgs) Handles RichTextBox1.LinkClicked
Dim txt As String = e.LinkText 'txt is the link you clicked
End Sub
valter
I have a CSV file that is formatted as (name,number) on each line.
I'm creating an app that loads all names, index(0), into a listbox at form-load and when a name is selected the number, index(1), is displayed in a .textbox.
I start by filling an array and displaying index(0) in the box. No Prob. But when the selected text changes I have problems. If you cant tell I'm new to VB. If I could assign a var to the selected text I could use a while loop but I'm not sure how to assign that. Is there a better way to go about this? Below is my source. Any help would be great.
Public Class Form1
Public Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
For Each line As String In IO.File.ReadAllLines("MembershipPhone.txt")
Dim myData = line.Split(","c)
Dim mName = myData(0)
Dim mPhone = myData(1)
ListBox1.Items.Add(mName)
Next
End Sub
Private Sub ListBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ListBox1.SelectedIndexChanged
For Each line As String In IO.File.ReadAllLines("MembershipPhone.txt")
Dim query = line.Split(","c)
Dim mName = query(0)
Dim mPhone = query(1)
TextBox2.Text = mPhone
Next
End Sub
I want to be able to accept a NULL date using the DateTimePicker control.
The "Checked" property appears to be intended to specify whether the control "holds a date" or now. However, when "unchecked", the date still appears, though it appears disabled. To me, this is distracting. If the intent of the unchecked checkbox is to indicate that there is no date value, why is there ANY date value disable or otherwise that appears in the textbox? It seems to me that if the control is unchecked, the textbox should be EMPTY and that seeing a dimmed date value when the user really wants "no value" is distracting.
If the user toggled the checkbox on, then I would like the ability to place a default value into the textbox.
I am considering creating a usercontrol that toggles between a dateTimePicker control and a textBox, but I hate to go through this trouble.
I tried looking a Telerik's DateTimePicker but trying to get decent null handling functionality out of that control seems worse. I'd love to see a working example of what one of you think is a user-friendly code example with either the std MS or Telerik DateTimePicker control that accepts null input.
I've looked at a few opensource controls, but every time they fix one issue, they introduce others.
EDIT:
See my answer below. It seems to work fine, now I just want to make it part of every DateTimePicker's behavior.
I had the same problem. Well, actually I'm smart enough to understand, but my users had a problem.
I solved by removing the checkbox, and adding 2 radio buttons. Looks something like this now:
(using pseudo UI)
O No value entered
O | 1/1/2010 |V|
The top radiobutton is checked when there is no value (null), the bottom one when there is a value. I do not hide, or disable the bottom control, and users seem to understand.
The downside is, that it takes a lot more space.
PS: Next thing users will complain about is using the scroll-wheel when a combo-box has focus.
Klugey, but it seems to get the job done. If the checkbox is not checked, assume a NULL value.
Private Sub DateTimePicker1_ValueChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles DateTimePicker1.ValueChanged
If DateTimePicker1.Checked Then
DateTimePicker1.Format = DateTimePickerFormat.Short 'Or whatever the original format was
Else
DateTimePicker1.Format = DateTimePickerFormat.Custom
DateTimePicker1.CustomFormat = " "
End If
End Sub
OK, the next question...How do I roll this behavior into a subclassed DateTimePicker? What I want to do is to capture the original values of the Format and CustomFormat properties as set in the Properties window. But, this clearly isn't the way to do it.
Here's my feeble attempt:
Public Class NullableDateTimePicker
Inherits DateTimePicker
Private _OriginalFormat As DateTimePickerFormat
Private _OriginalCustomerFormat As String
Private Sub NullableDateTimePicker_ValueChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.ValueChanged
If Me.Checked Then
Me.Format = _OriginalFormat
Me.CustomFormat = _OriginalCustomerFormat
Else
Me.Format = DateTimePickerFormat.Custom
Me.CustomFormat = " "
End If
End Sub
Private Sub _DP_FormatChanged(ByVal sender As Object, ByVal e As System.EventArgs)
Static Count As Integer
If Count = 0 Then
_OriginalFormat = Me.Format
_OriginalCustomerFormat = Me.CustomFormat
End If
Count += 1
End Sub
Public Sub New()
AddHandler MyBase.FormatChanged, AddressOf _DP_FormatChanged
End Sub
End Class
I realise this is many years after your initial question but here's a subclass of the Telerik RadDateTimePicker that does what you were asking for:
Imports Telerik.WinControls.UI
Public Class DateTimePickerWithNull
Inherits Telerik.WinControls.UI.RadDateTimePicker
Private ReadOnly _calendar As RadCalendar
Sub New()
Dim calendarBehavior As RadDateTimePickerCalendar = Me.DateTimePickerElement.GetCurrentBehavior()
calendarBehavior.DropDownMinSize = New Size(220, 150)
_calendar = calendarBehavior.Calendar
_calendar.ShowFooter = True
AddHandler _calendar.ClearButton.Click, AddressOf ClearButton_Click
AddHandler _calendar.TodayButton.Click, AddressOf TodayButton_Click
End Sub
Private Sub ClearButton_Click(sender As Object, e As EventArgs)
'Do this to put the calendar away
_calendar.SelectedDate = _calendar.FocusedDate
'Then clear
Me.SetToNullValue()
End Sub
Private Sub TodayButton_Click(sender As Object, e As EventArgs)
_calendar.SelectedDate = _calendar.FocusedDate
End Sub
End Class
To get the value of the picker:
If DateTimePicker1.Value.Date = DateTimePicker1.NullDate Then
Label1.Text = "Null"
Else
Label1.Text = DateTimePicker1.Value.ToLongDateString
End If
A bit tricky to get right. This looked good:
Imports System.ComponentModel
Public Class MyDateTimePicker
Inherits DateTimePicker
Implements ISupportInitialize
Public Sub New()
Me.ShowCheckBox = True
Me.NullDate = True
End Sub
Private CustomFormatBacking As String = ""
Private FormatBacking As DateTimePickerFormat = DateTimePickerFormat.Long
<DefaultValue(True)> _
<Bindable(True)> _
Public Property NullDate() As Boolean
Get
Return Not Me.Checked
End Get
Set(ByVal value As Boolean)
Me.Checked = Not value
End Set
End Property
<DefaultValue("")> _
<Localizable(True)> _
<RefreshProperties(RefreshProperties.Repaint)> _
Public Shadows Property CustomFormat() As String
Get
Return CustomFormatBacking
End Get
Set(ByVal value As String)
CustomFormatBacking = value
If DesignMode Or Not NullDate Then MyBase.CustomFormat = value
End Set
End Property
<RefreshProperties(RefreshProperties.Repaint)> _
Public Shadows Property Format() As DateTimePickerFormat
Get
Return FormatBacking
End Get
Set(ByVal value As DateTimePickerFormat)
FormatBacking = value
If DesignMode Or Not NullDate Then MyBase.Format = value
End Set
End Property
<DefaultValue(true)> _
<Bindable(True)> _
<DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)> _
Public Shadows Property Checked() As Boolean
Get
Return MyBase.Checked
End Get
Set(ByVal value As Boolean)
MyBase.Checked = value
End Set
End Property
Private Sub updateNullState()
If NullDate and Not DesignMode Then
MyBase.CustomFormat = " "
MyBase.Format = DateTimePickerFormat.Custom
Else
MyBase.CustomFormat = CustomFormatBacking
MyBase.Format = FormatBacking
End If
End Sub
Public Sub BeginInit() Implements System.ComponentModel.ISupportInitialize.BeginInit
End Sub
Public Sub EndInit() Implements System.ComponentModel.ISupportInitialize.EndInit
updateNullState()
End Sub
Protected Overrides Sub OnValueChanged(ByVal eventargs As System.EventArgs)
MyBase.OnValueChanged(eventargs)
updateNullState()
End Sub
End Class