[英]How to add value from checkedlistbox into database using stored procedure c# windows forms?
我正在尝试使用存储过程和C#从checkedlistbox添加检查值
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);
}
}
它显示如下错误:
errorSystem.invalidcastException: imposible to make a cast of an object type System.Data.DataRowView in type System.String
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;
表格画面
数据插入后的表格
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.