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.
Combining user2946329's answer with Resharper's contribution, the code I ended up using is:
(Resharper complained about a possible null reference issue, and so added the "if (dr != null)" jazz to the last line.
the key is to typecast the item before accessing it...
It should be something like this:
Judging by the string you get (
"System.Data.DataRowView"
), you use theCheckListBox
with datasource attached. If that's the case, inCheckedItems
you really getDataRowViews
.. hence the string, since its ToString() returns class name. You will need to access the data from theDataRowView
, by column name or index.