c# CheckedListbox values

1.4k views Asked by At

When I want to put the values in an array that are selected from a checkedlistbox. And then say:

messagebox.show(values[0]);

It's saying : System.Data.DataRowView

This is my current code:

        string[] itemArr = new string[clbTables.CheckedItems.Count];
        int counter = 0;
        foreach (object item in this.clbTables.CheckedItems)
        {
            string temp = Convert.ToString(item);
            itemArr[counter] = temp;
            counter++;
        }
        MetroMessageBox.Show(this, itemArr[0].ToString());

What am I doing wrong here>?

EDIT ::

clbTables.DataSource = sqlDisplayContent.connectDataTable("SELECT ('Tafelnr: '+ CONVERT(varchar,tafelnr)+' Zitplaatsen: '+ CONVERT(varchar,zitPlaatsen)) AS dispValue,tafelnr  FROM tabel");
clbTables.DisplayMember = "dispValue";
clbTables.ValueMember = "tafelnr";



class sqlDisplayContent
        {
            public static DataTable connectDataTable(string query)
            {
                SqlCommand comm= sqlCrud.returnSqlCommand(query);
                SqlDataAdapter sda = new SqlDataAdapter(comm);
                DataTable dt = new DataTable();
                sda.Fill(dt);
                return dt;
            }
        }

Thankss
3

There are 3 answers

3
Nathan M. On BEST ANSWER

The issue is that:

Convert.ToString(item);

will simply call the ToString() method of the object and store that, which in this case, is giving you the object's type. In this case, the type is System.Data.DataRowView. I suggest that you access the specific field in the row that you want by using:

((DataRowView)item).Row["FieldName"].ToString();

instead. You will want to replace "FieldName" with whatever the name of your column that you are wanting is. Additionally, you can use an int index instead of a string reference. Of course, if you need to access multiple fields, you can do this by simple string concatenation. The issue is that you need to access the specific field that you want. Not the entire row as you are currently on.

I hope this helps!

A couple references: DataRow, DataRowView

5
Andrew Grinder On
string temp = ((CheckBox)item).Text;

You are passing in the object, not the object's text (which is what it seems you want the code to do).

0
Dmytro Bogatov On

I suppose that your values[] array is not right. Please, refer to this example on MSDN.

https://msdn.microsoft.com/en-us/library/system.windows.forms.checkedlistbox.checkeditems(v=vs.110).aspx