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();
}
}
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.
{
Trying to update the first name of the student there is a textbox "FirstNameTextbox" information was loaded to it from the DB, when I change the information in the textbox and try to write the changes it read only the original data.So if it loaded "Craig" as the first name from the DB, i would edit and put "Chris" in the textbox, what happens is that Craig is written to the DB and not "Chris"
int stuID = getSqlStuID(IDNUMLabel.Text);
SqlConnection conn = new SqlConnection(GetConnectionString());
string sqlUpdateStudent = "Update tblStudent set fname = #fname where stuID = #stuID";
SqlCommand cmd = new SqlCommand(sqlUpdateStudent, conn);
conn.Open();
cmd.Parameters.AddWithValue("#stuID", stuID);
cmd.Parameters.AddWithValue("#fname", FirstNameTextbox.Text);
cmd.ExecuteNonQuery();
ErrorMessage.Text = "Success";
protected void Page_Load(object sender, EventArgs e)
{
if (Session["User"] != null)
{
IDNUMLabel.Text = Session["User"].ToString();
getStuData(Session["User"].ToString());
}
else
{
Response.Redirect("../Login/Login.aspx");
}
}
private void getStuData(string id)
{
SqlConnection conn = new SqlConnection(GetConnectionString());
string sql = "Select fname, sname From tblStudent Where idnumber = '" + id + "' ";
SqlCommand cmd = new SqlCommand(sql, conn);
try
{
conn.Open();
SqlDataReader selectedRecord = cmd.ExecuteReader();
cmd.CommandType = CommandType.Text;
while (selectedRecord.Read())
{
FirstNameTextbox.Text = selectedRecord["fname"].ToString();
LastNameTextbox.Text = selectedRecord["sname"].ToString();
}
selectedRecord.Close();
}
catch (System.Data.SqlClient.SqlException ex)
{
//id = 0;
//string msg = "Error reading Student ID";
//msg += ex.Message;
//throw new Exception(msg);
}
catch (Exception ex)
{
}
finally
{
conn.Close();
}
}
At what point do you make the actual update? After a button was pressed, after the value was entered on the textbox...? You're missing the method in which the code that handles the update is placed...
Maybe this could help: How to display data from database into textbox, and update it
I have got a problem.
I need to get id_subcategoria in 2 combobox "1". I have this code:
void fill_cbsubcategoria(int masterId)
{
cbsubcategoria.Items.Clear();
cbproduto.Items.Clear();
cbproduto.Text = "Escolha o produto";
txtquantidade.Text = null;
txtpreco.Text = null;
txtiva.Text = null;
try
{
con.Open();
string Query = "select * from Subcategoria where id_categoria = #mid";
SqlCommand createCommand = new SqlCommand(Query, con);
createCommand.Parameters.AddWithValue("#mid", masterId);
SqlDataReader dr = createCommand.ExecuteReader();
while (dr.Read())
{
int id_subcategoria = (int)dr.GetInt32(0);
string subcategoria = (string)dr.GetString(1);
cbsubcategoria.Items.Add(id_subcategoria.ToString() + " - " + new SubCategoriaHolder(id_subcategoria, subcategoria));
}
con.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
And I need to have id_subcategoria, when clicking at "Guardar".
private void btnguardar_Click(object sender, EventArgs e)
{
try
{
con.Open();
string Query = "insert into dbPAP.Produtos (id_subcategoria, nome_produto, quantidade, preco_unitario, iva, imagem)" + "values('" + "I NEED THAT ID FROM COMBOBOX" + this.txt_nproduto.Text + this.txtquantidade.Text + this.txtpreco.Text + this.txtiva.Text + "') ;";
SqlCommand createCommand = new SqlCommand(Query, con);
SqlDataReader dr = createCommand.ExecuteReader();
MessageBox.Show("Adicionado com sucesso!");
while (dr.Read())
{
}
con.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Here's my button guardar code.
Note: I don't want SelectedValue from combobox, I want to get id_subcategoria from DataBase.
Just add the ID's to a array List, while loading the elements to the combo Box, the Selected index from the combo box should reference to the according id in the List
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();
}
I'm tring to search for a value in multiple Sqlite tables and return the row where the value is found.
But my code only works if the value is in the last table i search.
SetConnection();
sql_con.Open();
sql_cmd = sql_con.CreateCommand();
dataGridView1.DataSource = "";
try
{
string comando = "SELECT UFE_SG, lOG_NO FROM log_logradouro where cep ='" + maskedTextBoxCep.Text + "'";
DB = new SQLiteDataAdapter(comando, sql_con);
}
catch (SystemException e)
{
}
try
{
string comando = "SELECT UFE_SG, lOc_NO FROM log_localidade where cep ='" + maskedTextBoxCep.Text + "'";
DB = new SQLiteDataAdapter(comando, sql_con);
}
catch (SystemException e)
{
}
try
{
string comando = "SELECT UFE_SG, CPC_NO FROM log_cpc where cep ='" + maskedTextBoxCep.Text + "'";
DB = new SQLiteDataAdapter(comando, sql_con);
}
catch (SystemException e)
{
}
DS.Reset();
DB.Fill(DS);
DT = DS.Tables[0];
dataGridView1.DataSource = DT;
sql_con.Close();
It looks like you're overwriting the DB object in each try/catch block instead of executing the query and checking for results with each command.