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.
{
Related
I am trying to search my populated ListView for a specific date entry using a datetimepicker. I only want to search and result in the date part of the DateTime component.
I've tried converting my datetimepicker (dtpStartDate) to a short date string within my search button code (my current method below throws an error "the conversion of a varchar data type to a DateTime data type resulted in an out-of-range value").
I've also tried
dtpStartDate = Convert.ToDateTime(System.DateTime.Now.ToShortDateString("dd-MM-yyyy"));
but the ToShortDateString underlines in red.
I've also tried
string dt = dtpStartDate.Value.ToShortDateString();
then searching for the dt value but it's the same varchar error as above.
This is my code for displaying all the sales from the SQL Server database in my listview:
private void DisplaySales()
{
string selectQuery;
selectQuery = "SELECT Sales.SaleID, Customers.CustomerID, Products.ProductID, ";
selectQuery = selectQuery + "Sales.Payable, Sales.StartDate ";
selectQuery = selectQuery + "FROM Sales INNER JOIN ";
selectQuery = selectQuery + "Customers ON Sales.CustomerID = Customers.CustomerID ";
selectQuery = selectQuery + "INNER JOIN Products ON Sales.ProductID = Products.ProductID ";
selectQuery = selectQuery + " " + GlobalVariables.saleSearchCriteria;
SqlConnection conn = ConnectionManagerClass.ConnectionManager.DatabaseConnection();
SqlDataReader rdr = null;
try
{
SqlCommand cmd = new SqlCommand(selectQuery, conn);
conn.Open();
rdr = cmd.ExecuteReader();
while (rdr.Read())
{
// Define the list items
Business_Logic_Layer.SaleInfoClass sale = new Business_Logic_Layer.SaleInfoClass(int.Parse(rdr["SaleID"].ToString()),
(rdr["CustomerID"].ToString()),
(rdr["ProductID"].ToString()),
(rdr["Payable"].ToString()),
(DateTime.Parse(rdr["StartDate"].ToString())));
ListViewItem lvi = new ListViewItem(sale.SaleID.ToString());
lvi.SubItems.Add(sale.CustomerID.ToString());
lvi.SubItems.Add(sale.ProductID.ToString());
lvi.SubItems.Add(sale.Payable);
lvi.SubItems.Add(sale.StartDate.ToString());
lvSales.Items.Add(lvi);
}
if (rdr != null)
rdr.Close();
conn.Close();
}
catch (Exception ex)
{
MessageBox.Show("Unsuccessful" + ex);
}
}
This is my code to add a sale into the database:
private void btnSave_Click(object sender, EventArgs e)
{
Business_Logic_Layer.SaleInfoClass sale = new Business_Logic_Layer.SaleInfoClass(GlobalVariables.selectedSaleID, txtCustomerID.Text,
lbProductID.Items[cbProductID.SelectedIndex].ToString(),
cbPayable.Text, dtpStartDate.Value);
string addQuery;
if (GlobalVariables.selectedSaleID == 0)
{
addQuery = "sp_Sales_CreateSale";
}
else
{
addQuery = "sp_Sales_UpdateSale";
}
SqlConnection conn = ConnectionManagerClass.ConnectionManager.DatabaseConnection();
conn.Open();
SqlCommand cmd = new SqlCommand(addQuery, conn);
cmd.CommandType = CommandType.StoredProcedure;
if (GlobalVariables.selectedSaleID != 0)
{
cmd.Parameters.AddWithValue("#SaleID", sale.SaleID);
}
cmd.Parameters.AddWithValue("#CustomerID", sale.CustomerID);
cmd.Parameters.AddWithValue("#ProductID", sale.ProductID);
cmd.Parameters.AddWithValue("#Payable", sale.Payable);
cmd.Parameters.AddWithValue("#StartDate", Convert.ToDateTime(sale.StartDate));
if (GlobalVariables.selectedSaleID == 0)
{
cmd.Parameters.AddWithValue("#NewSaleID", SqlDbType.Int).Direction = ParameterDirection.Output;
}
//Confirm user input
//Cancel if user chooses 'No'
if (MessageBox.Show("Would you like to save this Sale?", "Confirm", MessageBoxButtons.YesNo) == DialogResult.Yes)
{
cmd.Transaction = conn.BeginTransaction();
cmd.ExecuteNonQuery();
cmd.Transaction.Commit();
this.Close();
}
conn.Close();
this.Close();
}
And this is my code to search for a sale:
private void btnSearch_Click(object sender, EventArgs e)
{
dtpStartDate.Text = DateTime.Now.ToShortDateString();
if (rbStartDate.Checked == true)
{
GlobalVariables.saleSearchCriteria = "WHERE StartDate = '" + dtpStartDate.Text + "'";
}
this.Close();
}
Try to this way
string date1 = dtpStartDate.Value.Date.ToString("yyyy-MM-dd HH:mm:ss");
string date2 = dtpStartDate.Value.AddDate(1).Date.ToString("yyyy-MM-dd HH:mm:ss");
"WHERE StartDate >= '" + date1 + "' AND StartDate < '"+ date2;
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.
I want to edit the dataGridView as well as dataBase.
I have an button when i click it after editing the dataGridview it will updated database.
My first row obly updated but others row doesn't.
here is my code
private void button2_Click(object sender, EventArgs e)
{
try
{
foreach (DataGridViewRow row in dataGridView1.Rows)
{
string id = row.Cells["Product ID"].Value.ToString();
string name = row.Cells["Product Name"].Value.ToString();
string description = row.Cells["Product Description"].Value.ToString();
string category = row.Cells["Category"].Value.ToString();
string quantity = row.Cells["QTY"].Value.ToString();
string buyPrice = row.Cells["Buy Price"].Value.ToString();
string sellPrice = row.Cells["Sell Price"].Value.ToString();
string date = row.Cells["Date"].Value.ToString();
String query = "UPDATE [Stock List Table3] SET [Product Name] = '" + name + "',[Product Description] = '" + description + "',[Category] = '" + category + "',[QTY] = '" + quantity + "',[Buy Price] = '" + buyPrice + "',[Sell Price] = '" + sellPrice + "',Date = '" + date + "' WHERE [Product ID] = '" + id + "'";
m.Update_By_DataGridView_Information(query);
m.Load_Table1(dataGridView1);
m.Load_Table1(dataGridView4);
}
}
catch (Exception ex)
{
//MessageBox.Show(ex.Message);
}
}
public void Load_Table1(DataGridView dv)
{
string query = "SELECT * FROM [Stock List Table3]";
SqlConnection Conn = create_connection();
SqlCommand cmd = new SqlCommand(query, Conn);
try
{
SqlDataAdapter sda = new SqlDataAdapter();
sda.SelectCommand = cmd;
DataTable dataset = new DataTable();
sda.Fill(dataset);
BindingSource bSource = new BindingSource();
bSource.DataSource = dataset;
dv.DataSource = bSource;
sda.Update(dataset);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
public void Update_By_DataGridView_Information(string query)
{
try
{
SqlConnection Conn = create_connection();
SqlCommand cmd = new SqlCommand(query, Conn);
cmd.ExecuteNonQuery();
Conn.Close();
//MessageBox.Show("Updated Product Information Successfully", "Confirmation", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Here is my total code Error Line catch block in button2
After updating first row you update datagridview1 with original data
m.Load_Table1(dataGridView1)
Then next rows was updated with same values...
Try to put Load method outside of foreach loop:
foreach (DataGridViewRow row in dataGridView1.Rows)
{
//your update code for row...
}
m.Load_Table1(dataGridView1);
m.Load_Table1(dataGridView4);
I have a problem, when i m login the error is occured that No value given for one or more required parameters.
protected void imgbtn_login_Click(object sender, ImageClickEventArgs e)
{
int UserId = 0;
string str = ("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=pathto.mdb;Persist Security Info=False;");
OleDbConnection conn = new OleDbConnection(str);
conn.Open();
string query = "select * from Users where LoginName='" + txt_logname.Text + "' and Password='" + txt_pass.Text + "';";
OleDbDataAdapter da=new OleDbDataAdapter(query,conn);
DataSet ds = new DataSet();
da.Fill(ds);
DataTable dt = new DataTable();
dt = ds.Tables[0];
try
{
UserId = Int32.Parse(dt.Rows[0]["UserId"].ToString());
//btn_LogIn.Text = "Login Succeded";
Response.Redirect("Register.aspx");
}
catch (Exception ex)
{
}
txt_logname.Text = " ";
txt_pass.Text = "";
}
Password is a reserved word. Put it in square brackets [Password]
See Syntax error in INSERT INTO statement