Insert more than one item from checkedlistbox to AccessDB - c#

I have a listcheckedbox that lists the employee numbers and I want to be able to add each employee that attended a training class to show up under a training session. However, when I try to submit the information to insert into the DB, it will only add one of the employees selected. How can I have it submit more than 1 employee to a class session?
try
{
string cmdstring = "INSERT INTO [SESSION] (PrincipleName, Comments, SessionDate, SessionName, TellerNum) VALUES (#principle, #comments, #date, #session, #teller)";
using (OleDbCommand cmd = new OleDbCommand(cmdstring, con))
{
cmd.Parameters.AddWithValue("#principle", comboBox12.Text);
cmd.Parameters.AddWithValue("#comments", textBox3.Text);
cmd.Parameters.AddWithValue("#date", dateTimePicker1.Value);
cmd.Parameters.AddWithValue("#session", comboBox1.Text);
cmd.Parameters.AddWithValue("#teller", checkedListBox1.Text);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("Submitted Successfully");
}
}
catch (Exception ex)
{
MessageBox.Show("Failed due to " + ex.Message);
}
Here is my updated code after the answer from LarsTech answer
con.Open();
string cmdstring = "INSERT INTO [SESSION] (PrincipleName, Comments, SessionDate, SessionName, TellerNum) VALUES (#principle, #comments, #date, #session, #teller)";
foreach (int s in checkedListBox1.CheckedItems)
{
using (OleDbCommand cmd = new OleDbCommand(cmdstring, con))
{
cmd.Parameters.AddWithValue("#principle", comboBox12.Text);
cmd.Parameters.AddWithValue("#comments", textBox3.Text);
cmd.Parameters.AddWithValue("#date", dateTimePicker1.Value.ToShortDateString());
cmd.Parameters.AddWithValue("#session", comboBox1.Text);
cmd.Parameters.AddWithValue("#teller", s);
cmd.ExecuteNonQuery();
}
}
con.Close();
MessageBox.Show("Submitted Successfully");
textBox3.Clear();
checkedListBox1.ClearSelected();
comboBox1.Refresh();
comboBox12.Refresh();
dateTimePicker1.Refresh();

You have to iterate over the CheckedItems collection:
foreach (string s in checkedListBox1.CheckedItems)
{
using (OleDbCommand cmd = new OleDbCommand(cmdstring, con))
{
cmd.Parameters.AddWithValue("#principle", comboBox12.Text);
cmd.Parameters.AddWithValue("#comments", textBox3.Text);
cmd.Parameters.AddWithValue("#date", dateTimePicker1.Value);
cmd.Parameters.AddWithValue("#session", comboBox1.Text);
cmd.Parameters.AddWithValue("#teller", s);
cmd.ExecuteNonQuery();
}
}

Related

how to update weight in database

private void btn_Update_Click(object sender, EventArgs e)
{
con.Open();
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "update MyWeight set Weight='" + txt_Weight.Text + "'where Name='" + txt_Name.Text + "'";
string a = (string)cmd.ExecuteScalar();
con.Close();
if (a != null)
{
cmd.ExecuteNonQuery();
con.Close();
display_data();
MessageBox.Show("Weight updated successfuly!!!");
}
else
{
con.Close();
display_data();
MessageBox.Show("Not updated!!!");
}
}
I tried to update the weight into the database, but the database keeps saying that it is not updated.
Try like this:
bool updated;
con.Open();
using (SqlCommand cmd = con.CreateCommand())
{
cmd.CommandType = CommandType.Text;
cmd.CommandText = "update MyWeight set Weight=#Weight where Name=#Name";
cmd.Parameters.Add(new SqlParameter("Weight", txt_Weight.Text));
cmd.Parameters.Add(new SqlParameter("Name", txt_Name.Text));
updated = (cmd.ExecuteNonQuery() > 1);
con.Close();
}
if (updated)
{
display_data();
MessageBox.Show("Weight updated successfuly!!!");
}
else
{
display_data();
MessageBox.Show("Not updated!!!");
}
It makes more sense to use ExecuteNonQuery for update operations in general because you don't expect any results.
Have you checked the table to see if it did update the row?
Why are you executing the same command with ExecuteNonQuery inside the if statement?

inserting from textbox and datagridview at sametime in database

how can I insert data from datagridview and textboxes at same time with one button click in one table. here is my code I use foreachloop to insert from DataGridview but it insert null
any help appreciate.
SqlCommand cmd, cmd1, cmd2, cmd3;
con.Open();
cmd = new SqlCommand("insert into sale_detail(sale_bill_number, discount,currency,date) values(#sale_bill_number, #discount ,#currency,#date)", con);
cmd.Parameters.AddWithValue("#sale_bill_number", billbox.SelectedItem);
cmd.Parameters.AddWithValue("#discount", txtdiscount.Text);
cmd.Parameters.AddWithValue("#currency", currencyid);
cmd.Parameters.AddWithValue("#date", dateTimePicker.Value.Date);
cmd1 = new SqlCommand("insert into payment(sdetail,totalprice) values(#sdetail,#totalprice)", con);
cmd1.Parameters.AddWithValue("#sdetail", sid);
cmd1.Parameters.AddWithValue("#totalprice", txtpayment.Text);
cmd2 = new SqlCommand("insert into sale(customer) values(#customer)", con);
cmd2.Parameters.AddWithValue("#customer", customerid);
foreach (DataGridViewRow dr in saleDataGridView.Rows)
{
string sqlquery = "insert into sale_detail(medicine_id,purchase_rate,quantity)values(#medicine_id,#purchase_rate, #quantity)";
cmd = new SqlCommand(sqlquery, con);
cmd.Parameters.AddWithValue("#medicine_id", dr.Cells["شماره مسلسل"].Value);
// cmd.Parameters.AddWithValue("#country", saleDataGridView.Rows[i].Cells["کشور"].Value);
cmd.Parameters.AddWithValue("#purchase_rate", dr.Cells["قیمت"].Value);
// cmd.Parameters.AddWithValue("#sale_rate", dr.Cells["قیمت فروش"].Value ??DBNull.Value);
cmd.Parameters.AddWithValue("#quantity", dr.Cells["تعداد"].Value);
}
if (cmd.ExecuteNonQuery() == 1)
{
if (cmd1.ExecuteNonQuery() == 1) {
if (cmd2.ExecuteNonQuery() == 1)
{
Perhaps:
using con = new SqlCommand(...);
con.Open();
var tran = con.BeginTransaction();
var cmd = new SqlCommand("insert into sale_detail(sale_bill_number, discount,currency,date) values(#sale_bill_number, #discount ,#currency,#date)", con);
cmd.Parameters.AddWithValue("#sale_bill_number", billbox.SelectedItem);
cmd.Parameters.AddWithValue("#discount", txtdiscount.Text);
cmd.Parameters.AddWithValue("#currency", currencyid);
cmd.Parameters.AddWithValue("#date", dateTimePicker.Value.Date);
cmd.ExecuteNonQuery();
cmd = new SqlCommand("insert into payment(sdetail,totalprice) values(#sdetail,#totalprice)", con);
cmd.Parameters.AddWithValue("#sdetail", sid);
cmd.Parameters.AddWithValue("#totalprice", txtpayment.Text);
cmd.ExecuteNonQuery();
cmd = new SqlCommand("insert into sale(customer) values(#customer)", con);
cmd.Parameters.AddWithValue("#customer", customerid);
cmd.ExecuteNonQuery();
foreach (DataGridViewRow dr in saleDataGridView.Rows)
{
string sqlquery = "insert into sale_detail(medicine_id,purchase_rate,quantity)values(#medicine_id,#purchase_rate, #quantity)";
cmd = new SqlCommand(sqlquery, con);
cmd.Parameters.AddWithValue("#medicine_id", dr.Cells["شماره مسلسل"].Value);
// cmd.Parameters.AddWithValue("#country", saleDataGridView.Rows[i].Cells["کشور"].Value);
cmd.Parameters.AddWithValue("#purchase_rate", dr.Cells["قیمت"].Value);
// cmd.Parameters.AddWithValue("#sale_rate", dr.Cells["قیمت فروش"].Value ??DBNull.Value);
cmd.Parameters.AddWithValue("#quantity", dr.Cells["تعداد"].Value);
cmd.ExecuteNonQuery();
}
tran.Commit();
And wrap the whole thing(apart from the using) in a try catch (I would have done it but I'm on a cellphone; there is no code indent button) and put tran.Rollback(); in the catch

Button click does not change anything in database c#

Button click when workorder exist to update the datatable does not change anything in the datatable but when the workorder does not exist it will insert data into the datatable. Does anyone know where i gone wrong? I have changed the update statement from my other post(Syntax error in update using C# inputting data into an existing row) when this problem(button click dont change anything) appears
private void save_care_Click(object sender, EventArgs e)
{
if (textBox2.Text=="")
MessageBox.Show("No data, Please scan workorder");
else
{
//Checking if workorder exist in database
connection.Open();
OleDbCommand checkrecord = new OleDbCommand("SELECT COUNT(*) FROM [c# barcode] WHERE ([Workorder] = #workorder)", connection);
checkrecord.Parameters.AddWithValue("#workorder", textBox2.Text);
int recordexist = (int)checkrecord.ExecuteScalar();
if (recordexist > 0)
{
//add data if it exist
string cmdText = "UPDATE [c# barcode] SET [Close from care] =#Close,[Name care] =#name WHERE[Workorder] = #workorder"; ;
using (OleDbCommand cmd = new OleDbCommand(cmdText, connection))
{
cmd.Parameters.AddWithValue("#workorder", textBox2.Text);
cmd.Parameters.AddWithValue("#Close", DateTime.Now.ToString("d/M/yyyy"));
cmd.Parameters.AddWithValue("#name", label4.Text);
cmd.ExecuteNonQuery();
textBox2.Clear();
connection.Close();
}
connection.Close();
}
else
{
//inserting workorder if it does not exist
string cmdText = "INSERT INTO [c# barcode] ([Workorder],[Close from care],[Name care]) VALUES (#workorder,#Close,#name)";
using (OleDbCommand cmd = new OleDbCommand(cmdText, connection))
{
cmd.Parameters.AddWithValue("#workorder", textBox2.Text);
cmd.Parameters.AddWithValue("#Close", DateTime.Now.ToString("d/M/yyyy"));
cmd.Parameters.AddWithValue("#name", label4.Text);
if (cmd.ExecuteNonQuery() > 0)
{
textBox2.Clear();
MessageBox.Show("Insert succesful, workorder has not been handedover, Please Check");
}
else
{
textBox2.Clear();
MessageBox.Show("Please rescan");
connection.Close();
}
connection.Close();
}
}
}
}
string cmdText = "UPDATE [c# barcode] SET [Close from care] =#Close,[Name care] =#name WHERE[Workorder] = #workorder"; ;
First check the double semicolon at this string doesn't the compiler complain?

Save values between 'Steps' in Wizard ASP.NET

I get this error in ASP.NET Wizard when I try to use values of TextBox control of previous step.
Error:
The INSERT statement conflicted with the FOREIGN KEY constraint "FK_Contact_Emp".
The conflict occurred in database "KKSTech", table "dbo.Emp", column 'EmpID'.
Is it a problem to access control's values of different steps?
This is the First class that inserts into dbo.Emp table
public void InsertInfo()
{
String KKStech = #"Data Source=USER-PC\SQLEXPRESS;Initial Catalog=KKSTech;Integrated Security=True";
SqlConnection conn = new SqlConnection(KKStech);
String insertstring = #"insert into Emp (EmpID, FirstName, LastName, MiddleName, Mob1, Mob2, Phone, Email1, Email2, EmpDesc)
values (#EmpID, #FirstName, #LastName, #MiddleName, #Mob1, #Mob2)";
SqlCommand cmd = new SqlCommand(insertstring, conn);
cmd.CommandText = insertstring;
cmd.CommandType = CommandType.Text;
try
{
conn.Open();
cmd.Parameters.AddWithValue("#EmpID", TextBox1.Text);
cmd.Parameters.AddWithValue("#FirstName", TextBox2.Text);
cmd.Parameters.AddWithValue("#LastName", TextBox3.Text);
cmd.Parameters.AddWithValue("#MiddleName", TextBox4.Text);
cmd.Parameters.AddWithValue("#Mob1", TextBox5.Text);
cmd.Parameters.AddWithValue("#Mob2", TextBox6.Text);
cmd.ExecuteNonQuery();
}
finally
{
conn.Close();
}
}
And this is the one where I 'm inserting into the table where EmpID is a FK
public void Insertaddress()
{
String KKStech = #"Data Source=USER-PC\SQLEXPRESS;Initial Catalog=KKSTech;Integrated Security=True";
SqlConnection conn = new SqlConnection(KKStech);
String str = #"insert into Contact (Addressline1, Addressline2, CityID, EmpID)
values(#Addressline1, #Addressline2, #CityID, #EmpID)";
SqlCommand cmd = new SqlCommand(str, conn);
cmd.CommandText = str;
cmd.CommandType = CommandType.Text;
try
{
conn.Open();
cmd.Parameters.AddWithValue("#Addressline1", TextBox15.Text);
cmd.Parameters.AddWithValue("#Addressline2", TextBox17.Text);
cmd.Parameters.AddWithValue("#CityID", DropDownList2.SelectedValue);
cmd.Parameters.AddWithValue("#EmpID", TextBox1.Text);
cmd.ExecuteNonQuery();
}
catch (System.Data.SqlClient.SqlException ex)
{
string msg = "Insert Error:";
msg += ex.Message;
throw new Exception(msg);
}
finally
{
conn.Close();
}
}
That was my problem.
A foreign key ensures that it cannot have a value in that column that is not also in the primary key column of the referenced table.
In your case , you are inserting EmpID into contact table which is not present in the referenced table of EmpID i.e Emp table.

inserting multiple values from C# into one row in a SQL table

I have a table which i want to store all the outputs into one row seperated by a space(eg "textbox1 textbox2 textbox3". How would i do this? At the moment its trying to put them into different columns. Giving me an error stating im using fewer columns.
}
using (SqlCommand cmd = new SqlCommand("INSERT INTO [user] (solution) VALUES (#textbox1, #textbox2, #textbox3)", cn))
{
cmd.Parameters.AddWithValue("#textbox1", textBox1.Text);
cmd.Parameters.AddWithValue("#textbox2", textBox2.Text);
cmd.Parameters.AddWithValue("#textbox3", textBox3.Text);
cmd.ExecuteNonQuery(); // or int affected = cmd.ExecuteNonQuery()
MessageBox.Show("Success!");
}
}
Try this:
using (SqlCommand cmd = new SqlCommand("INSERT INTO [user] (solution) VALUES (#text)", cn))
{
cmd.Parameters.AddWithValue("#text", textBox1.Text + " " + textBox2.Text + " " + textBox3.Text);
cmd.ExecuteNonQuery(); // or int affected = cmd.ExecuteNonQuery()
MessageBox.Show("Success!");
}
You are inserting data in more column than you have specified so I think you have got the error in that part. So, make some modification in code to remove the error:
}
using (SqlCommand cmd = new SqlCommand("INSERT INTO [user] (solution) VALUES (#textbox1+' '+ #textbox2+' '+ #textbox3)", cn))
{
cmd.Parameters.AddWithValue("#textbox1", textBox1.Text);
cmd.Parameters.AddWithValue("#textbox2", textBox2.Text);
cmd.Parameters.AddWithValue("#textbox3", textBox3.Text);
cmd.ExecuteNonQuery(); // or int affected = cmd.ExecuteNonQuery()
MessageBox.Show("Success!");
}
}

Categories