Search code examples
c#asp.netcomboboxajaxcontroltoolkit

How to get id of the selected item in combobox and populate another combobox with it?


I have 2 comboboxes created with Ajax Toolkit. One of them has a list of systems. I wanted to fill the other combobox with a list of subsystems whenever a system is selected. I did not use DisplayMember or ValueMember and most examples are using them. .aspx side just in case:

<ajaxToolkit:ComboBox ID="cbox1" runat="server" OnSelectedIndexChanged="cbox1_SelectedIndexChanged" />

Is this doable with what I'm trying? Is the event I used correct for the situation?(I guess not,but other events seem to be unrelated) Let me show you the code:

protected void fillSystemCombo()
        {
            var sysOperations = new ModelOperations.ConstantSystem.ConstantSystemOperations();
            var sys = sysOperations.GetSystemList().TransactionResultList;

            foreach (var item in sys)
            {
                cbox1.Items.Add(item.description);
            }
        }

This works fine and I can see the systems in my first combobox.

This is what I tried for populating the second one:

protected void cbox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            var subSysOperations = new ModelOperations.ConstantSubSystem.ConstantSubSystemOperations();
            int index = Convert.ToInt32(cbox1.SelectedItem.Value);//i think this should get the id...

            var subsys = subSysOperations.GetSubSystemList().TransactionResultList;

            foreach (var item in subsys)
            {
                if (item.sysID == index)
                {
                    cbox2.Items.Add(item.description);
                }
            }
        }

sysID is the foreign key in SubSystem which is the ID of System. By the way, my SelectedIndexChanged event never fired when I was debugging the program even though I clicked on an item in combobox.


Solution

  • I've actually found the answer after carefully reading the parameters taken by Items.Add. It wants a ListItemso if I create a ListItem inside the loop I can finally add my items with both a Text and a Value like this:

       foreach (var item in sys)
                {
                    combo1.Items.Add(new ListItem { Text = item.description, Value = item.ID.ToString() });
                }
    

    After that I can get the index with

    int index = Convert.ToInt32(combo1.SelectedValue);