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 displays an error like:
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)
{
}
}
}
Stored procedure
create PROCEDURE [dbo].[InsertData_CityListBox]
(@city_code varchar(50) )
AS BEGIN
insert into city(city_code) values (@city_code)
END;
Form Screen
Table after data insert
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.