Search code examples
c#winformscontrolscheckedlistbox

How to access data bound objects in listView using DataSource property?


So I have this radclv_peças which is a radCheckedListBox control populated with Peça custom objects and I'm trying to get the object currently selected using the SelectedItem property. The problem is I don´t know how to access these objects which I bound using the DataSource property like this:

radclv_peças.DataSource = Program.M_Wardrobe.ListaPeças;
radclv_peças.DisplayMember = "Name";
radclv_peças.ValueMember = "Id";

I need to change the image in a pictureBox according to the Peça currently selected in the listView. The idea is to get the currently selected item by ID and compare it with all Peça objects contained in Program.M_Wardrobe.ListaPeças(MVC pattern) which is of type List<Peça>, until I find the one with the same ID and send it to the pictureBox. So, how can I access the Id, or other properties, of the items bound in the radCheckedListBox (Telerik) with the DataSource property?


Solution

  • Telerik's RadCheckedListBox.SelectedItem has a DataBoundItem property. This represents a specific object that the SelectedItem is bound to out of the list of objects that the RadCheckedListBox is bound to. By casting this at runtime to your object type, you can access its properties in your event handler.

    private void RadCheckedListBox_SelectedIndexChanged(object sender, EventArgs e)
    {
        var selectedItem = radCheckedListBox.SelectedItem?.DataBoundItem as Peça;
    }
    

    Once you have the item, you are free to use it how you want from there.