B4J Question How to Avoid Triggering SelectedIndexChanged of a ComboBox when its Selected Index is Changed via Code

xulihang

Active Member
Licensed User
Longtime User
Hi there.

I want the SelectedIndexChanged event of a combobox only be triggered with human action. What is the correct way to do this?


B4X:
#Region Project Attributes
    #MainFormWidth: 600
    #MainFormHeight: 600
#End Region

Sub Process_Globals
    Private fx As JFX
    Private MainForm As Form
    Private xui As XUI
    Private Button1 As B4XView
    Private ComboBox1 As ComboBox
End Sub

Sub AppStart (Form1 As Form, Args() As String)
    MainForm = Form1
    MainForm.RootPane.LoadLayout("Layout1")
    MainForm.Show
    ComboBox1.Items.Add("Item 1")
    ComboBox1.Items.Add("Item 2")
    ComboBox1.Items.Add("Item 3")
End Sub

Sub Button1_Click
    ComboBox1.SelectedIndex = 2  'will trigger the selected index changed event
End Sub

Private Sub ComboBox1_SelectedIndexChanged(Index As Int, Value As Object)
    Log(Index)
End Sub
 

LucaMs

Expert
Licensed User
Longtime User
B4X:
#Region Project Attributes
    #MainFormWidth: 600
    #MainFormHeight: 600
#End Region

Sub Process_Globals
    Private fx As JFX
    Private MainForm As Form
    Private xui As XUI
    Private Button1 As B4XView
    Private ComboBox1 As ComboBox
    Private ProgrSelected As Boolean
End Sub

Sub AppStart (Form1 As Form, Args() As String)
    MainForm = Form1
    MainForm.RootPane.LoadLayout("Layout1")
    MainForm.Show
    ComboBox1.Items.Add("Item 1")
    ComboBox1.Items.Add("Item 2")
    ComboBox1.Items.Add("Item 3")
End Sub

Sub Button1_Click
    ProgrSelected = True
    ComboBox1.SelectedIndex = 2  'will trigger the selected index changed event
End Sub

Private Sub ComboBox1_SelectedIndexChanged(Index As Int, Value As Object)
    If ProgrSelected Then Return
    ProgrSelected = False
    Log(Index)
End Sub
 
Upvote 0

xulihang

Active Member
Licensed User
Longtime User
B4X:
Private Sub ComboBox1_SelectedIndexChanged(Index As Int, Value As Object)
    If ProgrSelected Then Return
    ProgrSelected = False
    Log(Index)
End Sub
This is a way. But your code should be like this:

B4X:
Private Sub ComboBox1_SelectedIndexChanged(Index As Int, Value As Object)
    If ProgrSelected Then
        ProgrSelected = False
        Return
    End If
    Log(Index)
End Sub
 
Upvote 0
Top