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

浪尽此生 提交于 2019-12-24 11:46:12

问题


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.



来源:https://stackoverflow.com/questions/34422684/how-can-i-get-the-string-value-of-a-checked-item-from-a-checkedlistbox

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!