如何使用存储过程c#windows窗体将checkedlistbox中的值添加到数据库中?

时间:2015-05-06 10:09:26

标签: c# .net winforms

我尝试使用存储过程和C#

从checkedlistbox添加选中的值
Collection

它显示如下错误:

Map m = Collections.synchronizedMap(new HashMap());
    ...
Set s = m.keySet();  // Needn't be in synchronized block
    ...
synchronized (m) {  // Synchronizing on m, not s!
    Iterator i = s.iterator(); // Must be in synchronized block
    while (i.hasNext())
        foo(i.next());
}

1 个答案:

答案 0 :(得分:1)

private void insert_Click(object sender, EventArgs e)
        {
           insert(list1);

        }
    private void insert(CheckedListBox list1)
     {
    using (SqlConnection conn = new SqlConnection())
      {
      try
      {
     conn.ConnectionString = "data source=servername;User ID=user_name;Password=password;initial catalog=database_name;integrated security=False;MultipleActiveResultSets=True;App=EntityFramework";
    conn.Open();

    SqlCommand cmd = new SqlCommand("InsertData_CityListBox", conn);
     cmd.CommandType = CommandType.StoredProcedure;
      for (int i = 0; i < list1.Items.Count; i++)
      {
       if (list1.GetItemChecked(i))
       {
   string str = (string)list1.Items[i]; //Or try  list1.Items[i].ToString();
        cmd.Parameters.Clear();
        cmd.Parameters.AddWithValue("@city_code", str);
        cmd.ExecuteNonQuery();
      }
    }
            conn.Close();
         }
      catch(Exception e1)
        {

           }

      }
    }

存储过程

create PROCEDURE [dbo].[InsertData_CityListBox] 
(@city_code varchar(50) ) 
AS BEGIN 

insert into city(city_code) values (@city_code)
 END;

表单屏幕 enter image description here

数据插入后的表

enter image description here