Click here to Skip to main content
15,882,113 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
i'm trying to add checked values from checkedlistbox using stored procedure and c#

C#
public static void CreateDrugsListBox(CheckedListBox DrugsList)
  {
      try
      {
          SqlConnection con = new SqlConnection(@"connection");
          SqlCommand cmd = new SqlCommand("InsertData_DrugsListBox", con);
          cmd.CommandType = CommandType.StoredProcedure;

          con.Open();
          foreach (string  itemchecked in DrugsList.CheckedItems)
          {
              cmd.Parameters.Clear();
              cmd.Parameters.AddWithValue("@DrugsValue", itemchecked);
              cmd.ExecuteNonQuery();

          }
          con.Close();
     }

      catch (Exception ex)
      {

          MessageBox.Show("Error"+ex, "Error", MessageBoxButtons.OKCancel, MessageBoxIcon.Error);

      }

  }

it display an error like :
Quote:
errorSystem.invalidcastException: imposible to make a cast of an object type System.Data.DataRowView in type System.String
Posted
Updated 6-May-15 0:56am
v2

1 solution

The problem is
foreach (string  itemchecked in DrugsList.CheckedItems)
What you need is
foreach (object  itemchecked in DrugsList.CheckedItems)
               {
                   DataRowView drv = itemChecked as DataRowView;
                   cmd.Parameters.Clear();
                   cmd.Parameters.AddWithValue("@DrugsValue", drv["DisplayMember or ValueMember"]);
                   cmd.ExecuteNonQuery();
 
Share this answer
 
v4
Comments
Leila Toumi 6-May-15 7:33am    
thanks for your reply. u tried but i got an error: DisplayMember /valueMember is not a DataColumn or a DataRelation for the table !!
John C Rayan 6-May-15 7:36am    
Replace DisplayMember /valueMember with either your displaymember property column name or valueMember Column. Hope you understand.
Leila Toumi 6-May-15 9:28am    
when i add my ValueMember which is "ID_Drugs" it works successfully but it insert only the list of the id, and when i add my displaymember which is "DrugsValue" i got the same error: DrugsValue is not a DataColumn or a DataRelation for the table. in my situation i need to insert the value of the checkedlistbox not the id
John C Rayan 6-May-15 10:01am    
Can you post the code here where I can see your DisplayMember and ValueMember.
Leila Toumi 6-May-15 10:32am    
Thanks @John C Rayan it works succesully now i just replace "DrugsValue" by "DrugsValues"

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900