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

2019-08-15 05:47发布

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.

4条回答
走好不送
2楼-- · 2019-08-15 06:10

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.

查看更多
Deceive 欺骗
3楼-- · 2019-08-15 06:22
_selectedUnit = ((DataRowView)selectedUnits[0])["Name"].ToString();

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

查看更多
甜甜的少女心
4楼-- · 2019-08-15 06:23

It should be something like this:

DataRowView dr = checkedListBoxUnits.CheckedItems[0] as DataRowView;
string Name = dr["Unit"].ToString();
查看更多
Deceive 欺骗
5楼-- · 2019-08-15 06:27

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.

查看更多
登录 后发表回答