How can I get the string value of a checked item f

2019-08-15 06:23发布

问题:

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.

回答1:

It should be something like this:

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


回答2:

Judging by the string you get ("System.Data.DataRowView"), you use the CheckListBox with datasource attached. If that's the case, in CheckedItems you really get DataRowViews.. hence the string, since its ToString() returns class name. You will need to access the data from the DataRowView, by column name or index.



回答3:

_selectedUnit = ((DataRowView)selectedUnits[0])["Name"].ToString();

the key is to typecast the item before accessing it...



回答4:

Combining user2946329's answer with Resharper's contribution, the code I ended up using is:

String _selectedUnit;
. . .
DataRowView dr = checkedListBoxUnits.CheckedItems[0] as DataRowView;
if (dr != null) _selectedUnit = dr["Unit"].ToString();

(Resharper complained about a possible null reference issue, and so added the "if (dr != null)" jazz to the last line.