Search code examples
c#winformscheckedlistboxdatarowview

How can I get the string value of a checked item from a CheckedListBox?


I've got this code to try to extract the display value from a CheckedListBox:

CheckedListBox.CheckedItemCollection selectedUnits = checkedListBoxUnits.CheckedItems;
_selectedUnit = selectedUnits[0].ToString();

...but it doesn't work - the value of "_selectedUnit", instead of being "platypus" as it should be, is "System.Data.DataRowView".

How can I coax the string value out of this complex object?

UPDATE

I'm not sure just what user2946329 wants to see bzg. my CheckedListBox, but here is how it is populated:

private void PopulateUnits()
{
    using (SqlConnection con = new SqlConnection(ReportRunnerConstsAndUtils.CPSConnStr))
    {
        using (SqlCommand cmd = new SqlCommand(ReportRunnerConstsAndUtils.SelectUnitsQuery, con))
        {
            cmd.CommandType = CommandType.Text;
            using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
            {
                DataTable dt = new DataTable();
                sda.Fill(dt);
                ((ListBox)checkedListBoxUnits).DataSource = dt;
                ((ListBox)checkedListBoxUnits).DisplayMember = "Unit";
                ((ListBox)checkedListBoxUnits).ValueMember = "Unit";
            }
        }
    }
}

Let me know if there is anything missing that would help you.


Solution

  • It should be something like this:

    DataRowView dr = checkedListBoxUnits.CheckedItems[0] as DataRowView;
    string Name = dr["Unit"].ToString();