المساعد الشخصي الرقمي

مشاهدة النسخة كاملة : Return String from a CheckListBox Control



C# Programming
03-21-2013, 02:23 AM
Seems simple enough, and I have looked hard and found many code sources (because some here might say this has been asked and answered), but none of them seem to work (I am showing some below...there are more).
Teh primary error seems to be the following error (unable to cast object of type 'system.data.datarowview' to type 'system.string ) or something similar to this. It seems like I solved this problem a while ago by giving up on the check list box and using a list view box with the show checkbox property added, but I cannot find my original code. So, in a nutshell....I want to simply return the string values for the checked items in the control and add them to an array or arraylist (either will do). BTW...the checklistbox control was filled using an SQL query (shown also), in case that makes a difference. You guys have almost always come up with a solution of sorts, and I thank you again in advance for your great assistance and talent...Regards, Pat

//Query Code
//Create an Arraylist to hold the values ArrayList al = new ArrayList(); //Open a database connection for the reader Conn.Open(); //Create the reader and execute the command adding the values to the arraylist SqlDataReader dr = Comm.ExecuteReader(); if (dr != null) while (dr.Read()) { //fill arraylist al.Add(dr[0]); } //Close the connection Conn.Close(); //Use the list to fill the checkbox foreach(string s in al) { checkedListBoxServices.Items.Add(s); } //ListCheckbox code I have tried//This one returns just the first (or last) line. I tried incrementing the row but it will not work//foreach (DataRowView drv in checkedListBoxServices.SelectedItems) //{ // al.Add(drv.Row[0].ToString()); //} /////////////////////////////////These do not work at all//int i = 0; //int count = checkedListBoxServices.CheckedItems.Count; //object item = string.Empty; ///////////////////////////////// //while (i < count) //{ // item = checkedListBoxServices.SelectedItems.ToString(); // listServices.Add(item); // i++; //} /////////////////////////////// //foreach (var item in checkedListBoxServices.CheckedItems) //{ // checkedListBoxServices.GetItemText(item); //} ////////////////////////////// //string[] items = checkedListBoxServices.CheckedItems.OfType().ToArray(); ////////////////////////////// //String[] itemArr = new String[checkedListBoxServices.CheckedItems.Count]; //Int32 counter = 0; //foreach (ListViewItem item in this.checkedListBoxServices.CheckedItems) //{ // String temp = Convert.ToString(item); // itemArr[counter] = temp; // counter++; //} /////////////////////////////