So I have this code that is designed to delete a row in mySQL server database judging by what is selected in my list box. Here is the code I have to remove the rows:
private void remove_btn_Click(object sender, EventArgs e)
{
try
{
if (Calls_lsb.SelectedItem == null)
MessageBox.Show("Please select an item for deletion.");
}
else
{
int i = Calls_lsb.SelectedIndex;
if (i > 0)
{
SqlConnection connection = new SqlConnection(//My Connection String);
string sqlStatement1 = "DELETE FROM Records WHERE CallID = #Id";
string sqlStatement2 = "DELETE FROM Calls WHERE CallID = #Id";
connection.Open();
SqlCommand cmd1 = new SqlCommand(sqlStatement1, connection);
cmd1.Parameters.AddWithValue("#Id", Calls_lsb.Items[i]);
cmd1.ExecuteNonQuery();
SqlCommand cmd2 = new SqlCommand(sqlStatement2, connection);
cmd2.Parameters.AddWithValue("#Id", Calls_lsb.Items[i]);
cmd2.ExecuteNonQuery();
connection.Close();
Calls_lsb.Items.Remove(Calls_lsb.Items[i]);
}
else
{
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
I get no exceptions and I have similar code that adds records that works fine. I tried stepping into the code but it all seemed fine. It simply just does not delete the row from the database. It removes the correct item from the list, just not the database.
If anyone could shine some light on this situation that would be great, thanks!
Edit : Ok, I seem to have fixed the problem. I just removed the whole i = selected index stuff and replace the 'Calls_lsb.Items[i]' with '(Calls_lsb.SelectedIndex + 1)'. I don't really understand why I was getting an exception when I tried to add 1 to i as this is basically doing the same thing.
Replace your below line code.
cmd1.Parameters.AddWithValue("#Id", Calls_lsb.Items[i]);
//with
cmd1.Parameters.AddWithValue("#Id", Calls_lsb.Items[i].Value);
and
cmd2.Parameters.AddWithValue("#Id", Calls_lsb.Items[i]);
// with
cmd2.Parameters.AddWithValue("#Id", Calls_lsb.Items[i].Value);
Related
I have issue when showing the status when data was delete or not. Here's the code
public bool isDelete (String nim, String pass)
{
String query = "delete from dbmahasiswa where NIM=#NIM AND Password=#Password";
class_Mahasiswa cm = new class_Mahasiswa();
try
{
connect.Open();
MySqlCommand cmd = new MySqlCommand(query, connect);
cmd.Parameters.AddWithValue("#NIM", nim);
cmd.Parameters.AddWithValue("#Password", pass);
cmd.ExecuteNonQuery();
MySqlDataReader reader;
reader = cmd.ExecuteReader();
int count = 0;
while (reader.Read())
{
count += 1;
}
if (count == 1)
{
System.Windows.Forms.MessageBox.Show("sukses!", "Status");
return true;
}
else
System.Windows.Forms.MessageBox.Show("akun tidak ditemukan", "Status");
return false;
connect.Close();
}
catch (Exception e)
{
System.Windows.Forms.MessageBox.Show(e.Message, "Warning");
return false;
}
return true;
}
If I type the wrong username or password, it will show MessageBox "akun tidak ditemukan"(account not found). Also when I type the right username and password to delete it, it will show that MessageBox because the function will read the database after data has been deleted.
My question is, how to show the "Sukses" MessageBox when data has been deleted?
You are calling ExecuteReader. The ExecuteReader is used to read data returning from the query with a SELECT statement. You can't use it to know if a row or more has been deleted. For this task you use just ExecuteNonQuery and get the return value to know the number of rows 'affected' by the query command
String query = "delete from dbmahasiswa where NIM=#NIM AND Password=#Password";
class_Mahasiswa cm = new class_Mahasiswa();
try
{
connect.Open();
MySqlCommand cmd = new MySqlCommand(query, connect);
cmd.Parameters.AddWithValue("#NIM", nim);
cmd.Parameters.AddWithValue("#Password", pass);
int rows = cmd.ExecuteNonQuery();
if (rows > 0)
{
System.Windows.Forms.MessageBox.Show("sukses!", "Status");
return true;
}
else
{
System.Windows.Forms.MessageBox.Show("akun tidak ditemukan", "Status");
return false;
}
}
catch (Exception e)
{
System.Windows.Forms.MessageBox.Show(e.Message, "Warning");
return false;
}
finally
{
connect.Close();
}
}
Also, it seems that you are using a global connect object for your connection. This is usually the source of many bugs like the one you have in your catch clause. If your code results in an exception you forgot to close the connection and, in the next call to connect.Open, you will get an error. I have added a finally to ensure proper closure of your connection object. However it is a better practice to keep the connection local to the code where you need it, open inside a using statement block to have it closed and disposed at the end of the block
Sorry guys to my english..
when i insert a record the same description with the existing record in datagridview but different quantity.. it creates a new row for the last record i inserted...
what i want is to ADD the quantity i inserted to the old record with the same description..
1. HERE'S THE IMAGE FOR YOU TO UNDERSTAND THE PROBLEM
2. THIS IS WHAT HAPPEN
The result should be QUANTITY = 25.. and also the totalcbm.. totalcbm = quantity * cbm
private void btnSave_Click(object sender, EventArgs e)
{
MySqlConnection connection = new MySqlConnection(MyConnectionString);
MySqlCommand cmd;
connection.Open();
try
{
cmd = connection.CreateCommand();
cmd.CommandText = "INSERT INTO Inventory(Quantity,Unit,ItemCode,ItemName,Cbm,TotalCbm)VALUES(#Quantity,#Unit,#ItemCode,#ItemName,#Cbm,#TotalCbm)";
cmd.Parameters.AddWithValue("#Quantity", tbQuantity.Text.ToString());
cmd.Parameters.AddWithValue("#Unit", tbUnit.Text.ToString());
cmd.Parameters.AddWithValue("#ItemCode", tbItemCode.Text.ToString());
cmd.Parameters.AddWithValue("#ItemName", tbItemName.Text.ToString());
cmd.Parameters.AddWithValue("#Cbm", tbCbm.Text.ToString());
cmd.Parameters.AddWithValue("#TotalCbm", tbTotalCbm.Text.ToString());
cmd.ExecuteNonQuery();
}
catch (Exception)
{
throw;
}
finally
{
if (connection.State == ConnectionState.Open)
{
connection.Close();
frmUserAE form1 = new frmUserAE();
AccountForm.LoadGrid();
this.Hide();
}
}
}
You are doing an INSERT statement, which will create a new row.
You should do an UPDATE statement, depending on what you think is your primary key (the description?).
With the code below, I can insert the selected values of the checkboxes into a single line in the database.In the same line, it is added the date, a note, and an Id number from another table (not unique). In my .aspx page there is a simple treenode-checkboxes structure.
Now, I want to insert each selected value from the checkbox in his own line in the database table.
For example: 3 checkboxes are selected: 3 lines with each own value inserted (plus the same date, note, Id for all of them) in the database.
Please any ideas how to do it?
protected void btn_vac_Click(object sender, EventArgs e)
{
int id = Convert.ToInt32(Session["pa_id"]);
string vn = string.Empty;
if (TreeView1.CheckedNodes.Count > 0)
{
foreach (TreeNode node in TreeView1.CheckedNodes)
{
vn += string.Format("{0}", node.Text);
}
}
try
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["RegistrationConnectionString"].ConnectionString);
conn.Open();
if (note_vac.Text.Length != 0)
{
string insert_emer = "insert into P_vaccines (V_name,P_Id,Note,Date) values (#vn,#p_id,#note,#Date) ";
SqlCommand com = new SqlCommand(insert_emer, conn);
com.Parameters.AddWithValue("#vn", string.Format("{0}", vn));
com.Parameters.AddWithValue("#p_id", id);
com.Parameters.AddWithValue("#note", note_vac.Text);
com.Parameters.AddWithValue("#Date", DateTime.Now.ToShortDateString());
com.ExecuteNonQuery();
}
else
{
string insert_emer = "insert into P_vaccines (V_name,P_Id,Date) values (#vn,#p_id,#Date) ";
SqlCommand com = new SqlCommand(insert_emer, conn);
com.Parameters.AddWithValue("#vn", string.Format("{0}", vn));
com.Parameters.AddWithValue("#p_id", id);
com.Parameters.AddWithValue("#Date", DateTime.Now.ToShortDateString());
com.ExecuteNonQuery();
}
Response.Write("<script>alert('Success!')</script>");
conn.Close();
}
catch (Exception ex)
{
Response.Write("Error :" + ex.ToString());
}
}
You code could be simplified a lot. First, you should prepare the command before entering the foreach loop over the checked indices. This means, creating the connection and the command then inside the loop just update the values of the parameters that need to change. Something like this.
protected void btn_vac_Click(object sender, EventArgs e)
{
if (TreeView1.CheckedNodes.Count > 0)
{
try
{
string insert_text = "insert into P_vaccines (V_name,P_Id,Note,[Date]) values (#vn,#p_id,#note,#Date) ";
using(SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["RegistrationConnectionString"].ConnectionString))
using(SqlCommand com = new SqlCommand(insert_text, conn))
{
com.Parameters.Add("#vn", SqlDbType.NVarChar);
com.Parameters.Add("#p_id", SqlDbType.Int).Value = Convert.ToInt32(Session["pa_id"]);
com.Parameters.Add("#note", SqlDbType.NVarChar);
com.Parameters.Add("#Date", SqlDbType.NVarChar).Value = DateTime.Now.ToShortDateString();
conn.Open();
foreach (TreeNode node in TreeView1.CheckedNodes)
{
com.Parameters["#vn"].Value = node.Text;
com.Parameters["#note"].Value = note_vac.Text.Length > 0 ? note_vac.Text : DbNull.Value;
com.ExecuteNonQuery();
}
}
Response.Write("<script>alert('Success!')</script>");
}
catch (Exception ex)
{
Response.Write("Error :" + ex.ToString());
}
}
}
Your original problem was caused by the vn +=... statement that concatenates together all the checked nodes. In this code instead I change that value directly on the Parameter with the value of the current check.
Note also that I have removed the AddWithValue calls that is known to be pretty a bad practice. But this means that you should be precise on the datatype of the values that you pass to your database engine. For example that datetime passed as string is a lot suspicious.
I should also add that having a column named Date is very confusing because there is a DataType with that name and if you want to use that column name it is better to encapsulate it with square brackets to avoid Syntax errors (or rename the column)
I've created a website that is connected to the database, I can get data and display it on the page with no prob at all. But when I try to insert (or update) it does nothing.
I have tested the SQL query and it works just fine.
I've looked here for similar situations and questions here for the past 24 hours with no luck.
I want the website to tell if the user want a one way or two way tickets and make a request. The table has the request id which is automatically incremented
then I add the id of the student who is requesting, the the id of the departure ticket then the id of return ticket (if it is 2 ways, this value can be null) there is also status which will be pending until a supervisor either accept or decline the request, once accepted, issue date will be added and status will change to approved. If declined reason will be added and status change to declined.
Main issue, when I make the request, the row is not created and added to the database for the supervisor to view later.
Here is my code:
protected void Button1_Click(object sender, EventArgs e)
{
int parsedValue;
int.TryParse(DropDownList1.SelectedValue, out parsedValue);
SqlConnection myConnection = new SqlConnection(""); // I removed the connection string.
string sqlcommand = "";
string idString = TextBox1.Text;
string idTwoString ="";
bool canContune = false;
if (parsedValue == 1)
{
System.Diagnostics.Debug.WriteLine("p");
Panel3.Visible = true;
idTwoString = TextBox2.Text;
if (AllNumber(idString, TextBox1) && AllNumber(idTwoString, TextBox2))
{
canContune = true;
}
}
else if (AllNumber(idString, TextBox1))
{
canContune = true;
}
if (canContune)
{
int dId;
int dId2;
int.TryParse(idString, out dId);
int.TryParse(idTwoString, out dId2);
sqlcommand = "INSERT INTO TicketRequest.dbo.TicketRequest (student_id, departure_id, return_id, statues, issue_date, notes) "
+ "VALUES (#student_id, #departure_id , #return_id , #statues, #issue_date, #notes)";
try
{
SqlCommand cmd = new SqlCommand(sqlcommand);
cmd.CommandType = CommandType.Text;
cmd.Connection = myConnection;
myConnection.Open();
cmd.Parameters.Add("#student_id", SqlDbType.Int).Value = id;
cmd.Parameters.Add("departure_id", SqlDbType.Int).Value = dId; //I used AddWithValue(#para, value) it didn't work.
if (parsedValue == 0)
{
cmd.Parameters.AddWithValue("#return_id", DBNull.Value);
}
else
{
cmd.Parameters.Add("#return_id", SqlDbType.Int).Value = dId2;
}
cmd.Parameters.Add("#statues", SqlDbType.Text).Value = "Pending";
cmd.Parameters.AddWithValue("#issue_date", DBNull.Value);
cmd.Parameters.AddWithValue("#notes", DBNull.Value);
cmd.ExecuteNonQuery();
myConnection.Close();
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine(ex.ToString());
}
}
}`
It doesn't throw any exception, I really don't know what is wrong.
I would be very thankful to anyone who will point me out my mistake in Insert query. Thanks in advance.
==================================================
I apologized all, it worked just fine. it seemed that the code wasn't excuted to being with. Thanks Falanor, you helped me discover the problem. =)
Try to check the return value.
int modified =(int)cmd.ExecuteScalar();
This is also missing the # symbol for the parameter
cmd.Parameters.Add("departure_id", SqlDbType.Int).Value = dId; //I used AddWithValue(#para, value) it didn't work.
So, basically what I'm doing is, after adding a diagnosis on the TextBox I'm checking if there is a Diagnosis with the same name already. The connection works fine, however, I'm having difficulties with executing the command in this line here:
var count = (int)cmd.ExecuteNonQuery();
Here's the full method
protected void MesmoDiagnostico_ServerValidate(object source, ServerValidateEventArgs args)
{
string connectionString = ConfigurationManager.ConnectionStrings["BDClinica"].ConnectionString;
SqlConnection connection = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand("Select COUNT(*) from Diagnosticos Where Diagnostico_Nome=#Diagnostico_Nome", connection);
connection.Open();
cmd.Parameters.AddWithValue("#Diagnostico_Nome", source);
var count = (int)cmd.ExecuteNonQuery();
if (count > 0)
{
args.IsValid = false;
}
else
{
args.IsValid = true;
}
connection.Close();
}
Am I missing something? Thanks!
According to MSDN, ExecuteNonQuery is for executing catalog or UPDATE/INSERT/DELETE operations and returns the number of rows affected. By using a COUNT, you're still looking for "number of rows" but it's being executed as query, not an update.
Since you only want one piece of data, technically the first column of the first row, you can use ExecutScalar instead.
This is almost the exact code that you need :
SqlConnection con = new SqlConnection(Settings.Default.FrakoConnectionString);
SqlCommand maxcommand = new SqlCommand("SELECT MAX(Counter) AS max FROM ppartikulieren", con);
try
{
con.Open();
max = (int)maxcommand.ExecuteScalar() + 1;
}
catch (Exception ex)
{
MessageBox.Show("Fout bij het plakken:\n" + ex.Message, "Frako planner", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
finally
{
con.Close();
}
you can also use a using statement of course. But the point is that you really need to cast the output of ExecuteScalar.