Jump to content
Xtreme .Net Talk

Recommended Posts

Posted

Hi,

I want to change the text of current selected item of a combo box to another string at run time.

I have played with a lot of properties but had no luck, how should I do this task?

Thanks everyone.

Posted

Changing string items or custom objects

 

Do you want to change the text of the item itself, or just the text displayed in the ComboBox? If you only wish to change the text displayed, you should be able to use the Text property.

 

However, if you wish to change the text of an actual item, it depends on what the item is. For example, if you have added each item as just a string, then you will have to remove the item and add a new item at the same index. If, however, you are using a custom class for your ComboBox items, the text of the item is set by the ToString method so by changing this, you can change the text in the combobox.

 

For example, if your ComboBox contains strings:

 

Dim oldIndex As Integer

oldIndex = myCombo.SelectedIndex
myCombo.Items.RemoveAt(oldIndex)
myCombo.Items.Insert(oldIndex, newText)
myCombo.SelectedIndex = oldIndex

 

If your ComboBox contains a custom class then changing the result of the ToString method will change the text in the ComboBox:

 

Class CustomClass
   Private _text As String

   Public Property Text As String
       Get
           Return _text
       End Get
       Set(ByVal value As String)
           _text = value
       End Set
   End Property

   Public Overrides Function ToString() As String
       Return _text
   End
End Class


'Changing text of an item:
Dim myItem As CustomClass
myItem = DirectCast(myCombo.SelectedItem, CustomClass)
myItem.Text = newText
myCombo.Refresh()

 

The fact that the ComboBox can hold all types of objects in this way can be very useful.

 

Good luck :)

Never trouble another for what you can do for yourself.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...