C# Listbox control - How to tell if program has selected an item in listbox or the interactive user


  • Hi,

    My form has 2 listbox:

    server_type which has items 'dev', 'uat' and 'prod'

    ad_domain which has items '', '' and ''

    The scenario is as follows:

    On startup the program sets server_type to 'dev' and ad_domain to '',

    I want it so that if the user changes server_type to 'prod' then the program changes 

    ad_domain to '' ONLY IF the user has NOT previously changed the ad_domain listbox to something else (eg. If the program just changes the ad_domain listbox unconditionally then the user experience is frustrating as the user's work is being constantly overwritten by the program.

    How can my C# program tell if the listbox control has been changed by the program or the user?

    Thanks for any help.

    Friday, March 15, 2019 5:59 AM

All replies

  • Hi,

    Do you want to select the corresponding item in "ad_domain" while selecting "server_type"? If so, maybe you can refer to the following code:

        private void Form1_Load(object sender, EventArgs e)
            server_type.SelectedItem = "dev";
            ad_domain.SelectedItem = "";
        int index;
        private void server_type_SelectedIndexChanged(object sender, EventArgs e)
            index = server_type.SelectedIndex;
            ad_domain.SelectedIndex = index;

    >> ONLY IF the user has NOT previously changed the ad_domain listbox to something else

    Do you want to set "ad_domain" to not be manually selectable? If so, you can set its "Enabled" to "false".

        public Form1()
            ad_domain.Enabled = false;

    If there is any misunderstanding, please feel free to contact me.



    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact

    Friday, March 15, 2019 6:48 AM
  • Try the next events and variables:

    bool ad_domain_changing_by_program;
    bool ad_domain_changed_by_user;
    private void Form1_Load( object sender, EventArgs e )
        server_type.SelectedIndex = 0;
        ad_domain.SelectedIndex = 0;
        ad_domain_changing_by_program = false;
        ad_domain_changed_by_user = false;
    private void server_type_SelectedIndexChanged( object sender, EventArgs e )
        if( !ad_domain_changed_by_user )
            ad_domain_changing_by_program = true;
            ad_domain.SelectedIndex = server_type.SelectedIndex;
            ad_domain_changing_by_program = false;
    private void ad_domain_SelectedIndexChanged( object sender, EventArgs e )
        ad_domain_changed_by_user = !ad_domain_changing_by_program;

    Saturday, March 16, 2019 5:58 PM