如何使用存储过程c#windows窗体将checkedlistbox中的值添加到数据库中? [英] How to add value from checkedlistbox into database using stored procedure c# windows forms?

查看:177
本文介绍了如何使用存储过程c#windows窗体将checkedlistbox中的值添加到数据库中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用存储过程从checkedlistbox添加选中的值并且c#



i'm trying to add checked values from checkedlistbox using stored procedure and 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:在System.String类型中对类型System.Data.DataRowView进行强制转换

errorSystem.invalidcastException: imposible to make a cast of an object type System.Data.DataRowView in type System.String

推荐答案

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();


这篇关于如何使用存储过程c#windows窗体将checkedlistbox中的值添加到数据库中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆