I made a project using c# and data base using access accdb and connected between them both. I made 2 buttons, first one to add new costumer, which works perfectly, and second one to update the data of the costumer (first name and last name), for some reason, the update button does not work, there is no error when I run the project, but after I click nothing happens...
private void button2_Click(object sender, EventArgs e)
{
connect.Open();
string cid = textBox1.Text;
string cfname = textBox2.Text;
string clname = textBox3.Text;
OleDbCommand command = new OleDbCommand();
command.Connection = connect;
command.CommandText = "UPDATE Tcostumers SET cfname= " + cfname + "clname= " + clname + " WHERE cid = " + cid;
if (connect.State == ConnectionState.Open)
{
try
{
command.ExecuteNonQuery();
MessageBox.Show("DATA UPDATED");
connect.Close();
}
catch (Exception expe)
{
MessageBox.Show(expe.Source);
connect.Close();
}
}
else
{
MessageBox.Show("ERROR");
}
}
I believe your commandtext is where the trouble lies;
command.CommandText = "UPDATE Tcostumers SET cfname= " + cfname + "clname= " + clname + " WHERE cid = " + cid;
You require a comma between the set statements, and also as Gino pointed out the speechmarks.
Edit:
It's better than you use parameters for your variables, your current method is open to SQL injection, eg.
private void button2_Click(object sender, EventArgs e)
{
OleDbCommand command = new OleDbCommand(#"UPDATE Tcostumers
SET cfname = #CFName,
clname = #CLName
WHERE cid = #CID", connect);
command.Parameters.AddWithValue("#CFName", textBox2.Text);
command.Parameters.AddWithValue("#CLName", textBox3.Text);
command.Parameters.AddWithValue("#CID", textBox1.Text);
try
{
connect.Open();
}
catch (Exception expe)
{
MessageBox.Show(expe.Source);
}
try
{
command.ExecuteNonQuery();
MessageBox.Show("DATA UPDATED");
}
catch (Exception expe)
{
MessageBox.Show(expe.Source);
}
finally
{
connect.Close();
}
}
Its how I tend to format my code, so do as you will with it. Hope it helps.
It might be a stupid thing but...
you're updating strings not ints so try adding '' to your strings something like:
command.CommandText = "UPDATE Tcostumers SET cfname= '" + cfname + "' clname='" + clname + "' WHERE cid = " + cid;
//my sample code for edit/update
Table Name = StudentFIle
Fields = id,fname,lname
bool found = false;
OleDbConnection BOMHConnection = new OleDbConnection(connect);
string sql = "SELECT * FROM StudentFIle";
BOMHConnection.Open();
OleDbCommand mrNoCommand = new OleDbCommand(sql, BOMHConnection);
OleDbDataReader mrNoReader = mrNoCommand.ExecuteReader();
while (mrNoReader.Read())
{
if (mrNoReader["id"].ToString().ToUpper().Trim() == idtextbox.Text.Trim())
{
mrNoReader.Close();
string query = "UPDATE StudentFIle set fname='" +firstnametextbox.Text+ "',lname='"+lastnametextbox.Text+"' where id="+idtextbox.Text+" ";
mrNoCommand.CommandText = query;
mrNoCommand.ExecuteNonQuery();
MessageBox.Show("Successfully Updated");
found = true;
break;
}
continue;
}
if (found == false)
{
MessageBox.Show("Id Doesn't Exist !.. ");
mrNoReader.Close();
BOMHConnection.Close();
idtextbox.Focus();
}
Related
I am trying to delete data from a Database AND the DataGridViewer using Winforms on Visual Studio. The way I am doing this is selecting a cell, and based on where that cell is, that row will be deleted. The selected row will read two strings and one date. I've tested the two strings and they work perfectly when deleting data. When it comes to the date, it doesn't seem to work for me, I keep getting an error. The error message will be attached as an image and the code will be below. I am fairly new to C# and SQL, just to put that out there.
private void delete_Click(object sender, EventArgs e)
{
foreach (DataGridViewCell theCell in daily_log.SelectedCells)
{
if (theCell.Selected)
{
string eid = daily_log[0, theCell.RowIndex].Value.ToString();
string aid = daily_log[4, theCell.RowIndex].Value.ToString();
DateTime dt = Convert.ToDateTime(daily_log[5, theCell.RowIndex].Value);
try
{
connection.Open();
using (OleDbCommand cmd = new OleDbCommand("DELETE FROM DailyLog WHERE EmployeeID='" + eid + "' AND ActivityID = '" + aid + "' AND Date = '" + dt.Date + "'", connection))
{
cmd.ExecuteNonQuery();
}
connection.Close();
daily_log.Rows.RemoveAt(theCell.RowIndex);
}
catch (Exception ex)
{
MessageBox.Show("Err: " + ex);
}
}
}
}
Is this a conversion error? And if so, how would I fix this?
You could try to use OledbParameter to delete data from access database.
Here is a code example you can refer to.
OleDbConnection conn = new OleDbConnection("connstr");
private void button1_Click(object sender, EventArgs e)
{
foreach (DataGridViewCell theCell in dataGridView1.SelectedCells)
{
if (theCell.Selected)
{
string id = dataGridView1[0, theCell.RowIndex].Value.ToString();
string aid = dataGridView1[1, theCell.RowIndex].Value.ToString();
DateTime dt = Convert.ToDateTime(dataGridView1[2, theCell.RowIndex].Value);
try
{
conn.Open();
string sql = "delete from DailyLog where ID=#ID AND AID=#AID AND Date=#Date";
using (OleDbCommand cmd = new OleDbCommand(sql, conn))
{
cmd.Parameters.AddWithValue("#ID", id);
cmd.Parameters.AddWithValue("#AID", aid);
cmd.Parameters.AddWithValue("#Date", dt);
cmd.ExecuteNonQuery();
}
dataGridView1.Rows.RemoveAt(theCell.RowIndex);
}
catch (Exception ex)
{
MessageBox.Show("Err: " + ex);
}
}
}
conn.Close();
}
private void Form1_Load(object sender, EventArgs e)
{
conn.Open();
string query = "select * from DailyLog";
OleDbDataAdapter da = new OleDbDataAdapter(query, conn);
OleDbCommandBuilder builder = new OleDbCommandBuilder(da);
var ds = new DataSet();
da.Fill(ds);
dataGridView1.DataSource = ds.Tables[0];
conn.Close();
}
Result:
Your Ids are probably numeric, and Date is a reserved word, so try with:
"DELETE FROM DailyLog WHERE EmployeeID = " + eid + " AND ActivityID = " + aid + " AND [Date] = #" + dt.Date.ToString("yyyy'/'MM'/dd") + "#"
That said, go for using parameters.
{
It is showing me 2 errors.. please help .....required for my project work
The error showing in both cases is as follows:-
Error 1 'System.Data.SqlClient.SqlDataAdapter' does not contain a
definition for 'loginregistration' and no extension method
'loginregistration' accepting a first argument of type
'System.Data.SqlClient.SqlDataAdapter' could be found (are you missing
a using directive or an assembly reference?)
private void btnSave_Click(object sender, EventArgs e)
{
{
if (txtUsername.Text == "" || txtEmail.Text == "")
{
MessageBox.Show("Please enter all Details");
}
else
{
SqlCommand cmd = new SqlCommand("select * from loginregistration WHERE username='" + txtUsername.Text + "'", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(ds);
int i = da.loginregistration[0].Rows.Count;//.........(ERROR HERE)
if (i > 0)
{
MessageBox.Show("Username Already Exists");
da.Clear();//............(ERROR HERE)
}
else
{
try
{
SqlCommand cmd1 = con.CreateCommand();
cmd1.CommandType = CommandType.Text;
cmd1.CommandText = "insert into loginregistration(username,FirstName,LastName,Email,Address,Contact_No) VALUES('" + txtUsername.Text + "','" + txtFirstName.Text + "','" + txtLastName.Text + "','" + txtEmail.Text + "','" + txtAddress.Text + "','" + txtContact.Text + "')";
cmd1.ExecuteNonQuery();
con.Close();
disp_data();
MessageBox.Show("Inserted Successfully");
txtUsername.Text = txtFirstName.Text = txtLastName.Text = txtEmail.Text = txtContact.Text = txtAddress.Text = "";
}
catch (Exception ex)
{
MessageBox.Show("ex.Message");
}
}
}
}
}
Let's extract a method for checking user's existence. We don't need to load all the data into a DataTable with a help of SqlDataAdapter; one query will be enough:
private bool UserExists(string userName) {
if (null == userName)
return false;
using (SqlConnection conn = new SqlConnection("Connection_String_Here")) {
conn.Open();
// Keep query readable
// Make query parametrized
string sql =
#"select 1
from LoginRegistration
where UserName = #prmUserName";
// Do not share the single connection, but create a new one
using (SqlCommand q = new SqlCommand(sql, conn)) {
q.Parameters.Add("#prmUserName", SqlDbType.VarChar).Value = userName;
// If we can read at least one record
using (var reader = q.ExecuteReader()) {
// we can be sure the user exists
return reader.Read();
}
}
}
}
Now, let's use our method:
if (string.IsNullOrEmpty(txtUsername.Text) || string.IsNullOrEmpty(txtEmail.Text))
MessageBox.Show("Please enter all Details");
else {
if (UserExists(txtUsername.Text))
MessageBox.Show("Username Already Exists");
else {
...
}
}
try to use dataset
DataSet loginregistration = new DataSet();
da.Fill(loginregistration ,"loginregistration ");
To fix your existing code:
int i = da.loginregistration[0].Rows.Count;
should be
int i = ds.Tables[0].Rows.Count;
That said you should pay attention to the answer Dmitry gave and parameterise your SQL. Your current method is wide open to SQL Injection.
I need to get the id of the last record of the table and do a new search with it, I'm hours trying but could not get a result.
I basically need to put these queries together.
1st take the id and then update the information.
Thank you all.
private void btnClose_Click(object sender, EventArgs e)
{
btnClose.Enabled = false;
btnOpen.Enabled = true;
connection = new OleDbConnection(db);
try
{
connection.Open();
string query = "UPDATE Caixa SET Data_Fechamento = '" + DateTime.Now + "' WHERE Id_Caixa = " + idDay;
OleDbCommand cmd = new OleDbCommand(query, connection);
cmd.ExecuteNonQuery();
MessageBox.Show("Caixa fechado com sucesso!");
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
finally
{
connection.Close();
}
}
enter image description hereI have two tables where in table tbl_mngr_shift_handover there mgr_handover_id is primary key and i want to insert it into another table tbl_mngr_shift_handover_details at insert time. So following is asp.net c# code
string remarkString = remarkTextArea.Content;
string query = string.Empty;
query="INSERT INTO tbl_mngr_shift_handover(msp_id,cat_id,task_id,priority_id,shift_id,status_id,activity)VALUES('"
+MSPDropDownList.SelectedValue+"','"
+CategoryDropDownList.SelectedValue+"','"
+TaskDropDownList.SelectedValue+"','"
+PriorityDropDownList.SelectedValue+"','"
+ShiftDropDownList.SelectedValue+"','"
+StatusDropDownList.SelectedValue+"','"
+ActivityTextBox.Text+"')";
string query1 ="INSERT INTO tbl_mngr_shift_handover_details(status_id,remark,inserted_by,inserted_date)"
+"VALUES('" + StatusDropDownList.SelectedValue + "','"
+ remarkTextArea.Content + "','"
+ Session["user_id"] + "','"
+ DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "')";
if(query != null)
{
string query2 = "update tbl_mngr_shift_handover_details set tbl_mngr_shift_handover_details.mgr_handover_id=tbl_mngr_shift_handover.mgr_handover_id from tbl_mngr_shift_handover where tbl_mngr_shift_handover_details.mgr_handover_id=tbl_mngr_shift_handover.mgr_handover_id ";
con.ConnectionString = constr;
con.Open();
if (con != null)
{
cmd1 = new SqlCommand(query2, con);
cmd1.ExecuteNonQuery();
con.Close();
}
}
try
{
con.ConnectionString = constr;
con.Open();
if (con != null)
{
cmd = new SqlCommand(query, con);
cmd.ExecuteNonQuery();
cmd2 = new SqlCommand(query1, con);
cmd2.ExecuteNonQuery();
PopUpLabel.Text = "Inserted Successfully";
ModalPopupExtender2.Show();
}
}
catch (Exception er)
{
// Label3.Text += "error in handover : " + er.Message;
PopUpLabel.Text = "Error While Inserting Handover.Please Concern Your Manager: Error Details: " + er.Message;
pnlPopup.Visible = true;
ModalPopupExtender2.Show();
}
finally
{
con.Close();
}
Here is database fields Images
enter image description here
Here In tbl_mngr_shift_handover_details field mgr_handover_id show null vallue so what can i do..
update data in access database using name two column
because one column have same data because SerialNumber and Start can be Repeat
that's make update in all row have same data
i use this code but i have syntax Error
private void button3_Click(object sender, EventArgs e)
{
try
{
connection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
string query = "update Timer set Stop='" + label1.Text + "'where (SerialNumber,Start)='" + comboBox1.Text + "','" + textBox1.Text + "' ";
command.CommandText = query;
command.ExecuteNonQuery();
MessageBox.Show("Data saved");
connection.Close();
send_data f2 = new send_data(comboBox1.Text,label2.Text);
f2.ShowDialog();
}
catch (Exception ex)
{
MessageBox.Show("ERORR" + ex);
}
}
The correct syntax for the WHERE clause is
WHERE fieldname operator value AND/OR fieldname operator value ....
So the correct way to update that record is
string query = #"update Timer set Stop=? where SerialNumber = ? AND Start = ?";
command.CommandText = query;
command.Parameters.AddWithValue("#p1", label1.Text);
command.Parameters.AddWithValue("#p2", comboBox1.Text );
command.Parameters.AddWithValue("#p3", textBox1.Text);
command.ExecuteNonQuery();
Notice that before the WHERE keyword you need a space and I have changed your code to use a more secure parameterized approach instead of string concatenation