C# Update command with oledb - c#

I'm trying to update the selected row in access database. How do I Update selected row in my access database?
I've tried using the update command
private void btnCancel_Click(object sender, EventArgs e)
{
try
{
for (int i = 0; i < dataRes.Rows.Count; i++)
{
string a = "Cancelled";
DataGridViewRow dr = dataRes.Rows[i];
if (dr.Selected == true)
{
connection.Open();
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = connection;
cmd.CommandText = "UPDATE Reservation SET Status ='" + a + "' WHERE ID = " + i +" ";
cmd.ExecuteNonQuery();
connection.Close();
MessageBox.Show("Reservation Cancelled");
}
}
}

Related

Deleting mysql table entry with C#

Basically, what I want to delete an entry form a dataviewtable which pulls data through from MySql. I thought this would be done fairly by effectively copying the modify code and substituting it for 'DELETE'. However, from the code below, you can clearly see that hasn't worked. I will copy most of my code for you:
private void button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection("Data Source=DESKTOP-HNR3NJB\\mysql;Initial Catalog=stock;Integrated Security=True");
var sqlQuery = "";
if (IfProductsExists(con, textboxProductID.Text))
{
con.Open();
sqlQuery = #"DELETE FROM [Products] WHERE [ProductID] = '" + textboxProductID.Text + "'";
SqlCommand cmd = new SqlCommand(sqlQuery, con);
cmd.ExecuteNonQuery();
con.Close();
}
else
{
MessageBox.Show("Record doesn't exist!", "ERROR:", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
//Reading Data
LoadData();
}
So that's the delete button's code now for the add button and load data function
Add button:
private void button2_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(#"Data Source=DESKTOP-HNR3NJB\mysql;Initial Catalog=stock;Integrated Security=True");
//insert logic
con.Open();
if(textboxProductID.Text == "" || textboxProductName.Text == "")
{
MessageBox.Show("You have to enter either a product ID or product name", "Error:", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
else
{
bool status = false;
if (comboboxStatus.SelectedIndex == 0)
{
status = true;
}
else
{
status = false;
}
var sqlQuery = "";
if (IfProductsExists(con, textboxProductID.Text))
{
sqlQuery = #"UPDATE [Products] SET [ProductName] = '" + textboxProductName.Text + "' ,[ProductStatus] = '" + status + "' WHERE [ProductID] = '" + textboxProductID.Text + "'";
}
else
{
sqlQuery = #"INSERT INTO [Stock].[dbo].[Products] ([ProductID],[ProductName],[ProductStatus]) VALUES
('" + textboxProductID.Text + "','" + textboxProductName.Text + "','" + status + "')";
}
SqlCommand cmd = new SqlCommand(sqlQuery, con);
cmd.ExecuteNonQuery();
con.Close();
textboxProductID.Clear();
textboxProductName.Clear();
LoadData();
}
}
LoadData function:
public void LoadData()
{
SqlConnection con = new SqlConnection(#"Data Source=DESKTOP-HNR3NJB\mysql;Initial Catalog=stock;Integrated Security=True");
//reading data from sql
SqlDataAdapter sda = new SqlDataAdapter("Select * From [stock].[dbo].[Products]", con);
DataTable dt = new DataTable();
sda.Fill(dt);
dataGridView1.Rows.Clear();
foreach (DataRow item in dt.Rows)
{
int n = dataGridView1.Rows.Add();
dataGridView1.Rows[n].Cells[0].Value = item["ProductID"].ToString();
dataGridView1.Rows[n].Cells[1].Value = item["ProductName"].ToString();
if ((bool)item["ProductStatus"])
{
dataGridView1.Rows[n].Cells[2].Value = "Active";
}
else
{
dataGridView1.Rows[n].Cells[2].Value = "Deactive";
}
}
}
You're going to need the IfProductsExists method too:
private bool IfProductsExists(SqlConnection con, string productCode)
{
SqlDataAdapter sda = new SqlDataAdapter("Select 1 From [Products] WHERE [ProductID]='" + productCode + "'", con);
DataTable dt = new DataTable();
if (dt.Rows.Count > 0)
return true;
else
return false;
}
It's going to be an inventory system that's going to be used at work for the sale and inventory management of IT equipment.

update selected data in mysql in c#

how to update selected data in mysql in c#?
this is my code when i press button2 . all data "jumlah_product" minus two.
i want to make just minus two "jumlah_product" in selected data.
private void button2_Click_1(object sender, EventArgs e)
{
string MyConnectionString = "Server=localhost;Database=maindata;Uid=root;pwd=firmandoang;";
string Query = "select * from maindata.product_database where idproduct = '" + this.textBox1.Text + "' OR namaproduct LIKE '" + this.textBox1.Text + "'";
MySqlConnection conn = new MySqlConnection(MyConnectionString);
MySqlCommand command = new MySqlCommand(Query, conn);
MySqlDataReader myReader;
conn.Open();
myReader = command.ExecuteReader();
try
{
if (myReader.Read())
{
DataGridViewRow row = (DataGridViewRow)dataGridView1.Rows[0].Clone();
row.Cells[1].Value = myReader.GetString("namaproduct");
row.Cells[2].Value = myReader.GetString("hargaproduct");
int count = Convert.ToInt32(textBox2.Text);
int price = Convert.ToInt32(row.Cells[2].Value);
row.Cells[3].Value = count;
row.Cells[4].Value = price *= count;
dataGridView1.Rows.Add(row);
string update = "UPDATE maindata.product_database SET jumlah_product=(jumlah_product - '" + count + "')";
MySqlCommand cmd = new MySqlCommand(update, conn);
MySqlDataReader reader;
myReader.Close();
reader = cmd.ExecuteReader();
reader.Close();
conn.Close();
}
else
{
MessageBox.Show("No Data ");
}
sorry for bad english . I hope you understand :)

Deleting row from table c#

I'm brand new to c# and am trying to figure out the delete and update portion of my table. I get the insert portion because I am not trying to select anything in my table prior to clicking a button. With the delete and update however, I am confused as to how a query pairs up to the selected row in my table. If anyone could point me in the right direction that would be great. I am using a dataset and GridControl in devexpress. I also have to make use of buttons to perform the events and will not be using the command fields within the grid. And I'm working on making my insert with parameters.
My list:
public partial class PatientList : XtraForm
{
public PatientList()
{
InitializeComponent();
}
private void PatientList_Load(object sender, EventArgs e)
{
SAConnection conn = new SAConnection("dsn={SQL Anywhere 10};uid=dba;pwd=sql;databasefile=C:\\Users\\Kbaker1\\Desktop\\Training1.db;");
SADataReader rdr = null;
string Query = "SELECT * FROM patient";
SADataAdapter da = new SADataAdapter(Query, conn);
DataSet ds = new DataSet();
da.Fill(ds);
grdList.DataSource = ds.Tables[0];
try
{
conn.Open();
SACommand cmd = new SACommand(Query, conn);
rdr = cmd.ExecuteReader();
}
finally
{
if (rdr != null)
{
rdr.Close();
}
if (conn != null)
{
conn.Close();
}
}
}
private void btnNewPatient_Click(object sender, EventArgs e)
{
Edit editPat = new Edit();
editPat.Show();
}
private void btnEditPatient_Click(object sender, EventArgs e)
{
Edit editPat = new Edit();
editPat.Show();
}
private void btnDeletePatient_Click(object sender, EventArgs e)
{
PatientService ps = new PatientService();
ps.DeletePatient();
}
private void btnClose_Click(object sender, EventArgs e)
{
this.Close();
}
}
The service class performing the operations:
public class PatientService
{
public void DataAccess()
{
}
public void CreatePatient(Patient patient)
{
SAConnection conn = new SAConnection();
SACommand cmd = new SACommand();
conn.ConnectionString = ("dsn={SQL Anywhere 10};uid=dba;pwd=sql;DBF=C:\\Users\\Kbaker1\\Desktop\\Training1.db;");
conn.Open();
cmd.Connection = conn;
cmd.CommandText = (#"INSERT INTO patient (patient_id, first_name, last_name, address, city, state, zipcode, phone, classification_id)
VALUES ('"
+ patient.PatientID + "','"
+ patient.FirstName + "','"
+ patient.LastName + "','"
+ patient.Address + "','"
+ patient.City + "','"
+ patient.State + "','"
+ patient.ZipCode + "','"
+ patient.Phone + "','"
+ patient.ClassificationID + "'); ");
cmd.ExecuteNonQuery();
conn.Close();
}
public void UpdatePatient()
{
}
public void DeletePatient()
{
SAConnection conn = new SAConnection();
conn.ConnectionString = ("dsn={SQL Anywhere 10};uid=dba;pwd=sql;DBF=C:\\Users\\Kbaker1\\Desktop\\Training1.db;");
conn.Open();
SACommand cmd = new SACommand("DELETE FROM patient WHERE patient_id = #patient_id");
cmd.Connection = conn;
cmd.ExecuteNonQuery();
conn.Close();
}
}
Just replace the INSERT sql statement with UPDATE
UPDATE table_name
SET column1=value1,column2=value2,...
WHERE some_column=some_value;
Delete:
DELETE FROM table_name
WHERE some_column=some_value;

How to display Image When Value will be True or False in Database

I wonder how to set The Picture box, and it will display 2 Images. On Value True image number 1, on value False, image number 2. I'm a noob in programming... My Record name is "oddal" dataType is "bit"
Here is my Code
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
SqlConnection cn = new SqlConnection(#"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\MSI\Documents\Visual Studio 2010\Projects\Baza z własnymi batonami\Baza z własnymi batonami\Database1.mdf;Integrated Security=True;User Instance=True");
SqlCommand cmd = new SqlCommand();
SqlDataReader dr;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
cmd.Connection = cn;
pokazliste();
}
private void button1_Click(object sender, EventArgs e)
{
if (textid.Text != "" & textimie.Text != "")
{
cn.Open();
cmd.CommandText = "Insert into Table1 (id,imie) values('" + textid.Text + "','" + textimie.Text + "')";
cmd.ExecuteNonQuery();
cmd.Clone();
MessageBox.Show("Wpis Wprowadzony","Vindykacja by Brzoska");
cn.Close();
textid.Text = "";
textimie.Text = "";
pokazliste();
}
}
private void pokazliste()
{
listBox1.Items.Clear();
listBox2.Items.Clear();
cn.Open();
cmd.CommandText = "Select * From Table1";
dr = cmd.ExecuteReader();
if (dr.HasRows)
{
while(dr.Read())
{
listBox1.Items.Add(dr[0].ToString());
listBox2.Items.Add(dr[1].ToString());
}
}
cn.Close();
}
private void listBox2_SelectedIndexChanged(object sender, EventArgs e)
{
ListBox l = sender as ListBox;
if (l.SelectedIndex != -1)
{
listBox1.SelectedIndex = l.SelectedIndex;
listBox2.SelectedIndex = l.SelectedIndex;
textid.Text = listBox1.SelectedItem.ToString();
textimie.Text = listBox2.SelectedItem.ToString();
}
}
private void button2_Click(object sender, EventArgs e)
{
if (textid.Text != "" & textimie.Text != "" & listBox1.SelectedIndex!=-1 )
{
cn.Open();
cmd.CommandText = "delete from Table1 where id='" + listBox1.SelectedItem.ToString() + "' and imie= '" + listBox2.SelectedItem.ToString() + "'";
cmd.ExecuteNonQuery();
cn.Close();
MessageBox.Show("Wpis Uaktualniony", "Vindykacja by Brzoska");
pokazliste();
textid.Text = "";
textimie.Text = "";
}
}
private void button3_Click(object sender, EventArgs e)
{
if (textid.Text != "" & textimie.Text != "")
{
cn.Open();
cmd.CommandText = "Update Table1 set id='" + textid.Text + "', imie= '" + textimie.Text + "'Where id'" + textid.Text + "'and imie= '" + textimie.Text + "'";
cmd.ExecuteNonQuery();
cn.Close();
MessageBox.Show("Wpis Usuniety", "Vindykacja by Brzoska");
pokazliste();
textid.Text = "";
textimie.Text = "";
}
}
private void pictureBox1_Click(object sender, EventArgs e)
{
}
}
}
SqlConnection cn = new SqlConnection(#"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\MSI\Documents\Visual Studio 2010\Projects\Baza z własnymi batonami\Baza z własnymi batonami\Database1.mdf;Integrated Security=True;User Instance=True");
SqlCommand cmd = new SqlCommand();
SqlDataReader dr;
cn.Open();
cmd.CommandText = "SELECT oddal FROM TableName WHERE (Your = Condition)";
dr = cmd.ExecuteReader();
if dr.Read()
{
if dr("oddal")
{
//Set picture box to image 1
}
else
{ //Set picture box to image 1
}
}
cn.Close();
Make sure to specify your condition in the SELECT. Also, for the future, assign meaningful names to the controls. Instead of button1, say btnInsert...

checkBox in gridView doesn't update my table

I am using the following the code to populate table on clicking upon the checkbox but there is no change in table
protected void Button1_Click(object sender, EventArgs e)
{
con.Open();
for (int i = 0; i < GridView1.Rows.Count; i++)
{
CheckBox chkUpdate = (CheckBox)
GridView1.Rows[i].Cells[0].FindControl("chkSelect");
if (chkUpdate != null)
{
if (chkUpdate.Checked)
{
string strID = GridView1.Rows[i].Cells[1].Text;
SqlCommand cmd;
string str1 = "update app1 set p_id=0 where p_id='" + strID + "'";
cmd = new SqlCommand(str1, con);
cmd .ExecuteNonQuery ();
}
}
}
}
Try this code it works
foreach (GridViewRows gdrv in GridView1.Rows)
{
CheckBox chkUpdate = (CheckBox)
gdrv.FindControl("chkSelect");
if (chkUpdate != null)
{
if (chkUpdate.Checked)
{
string strID = gdrv.Cells[1].Text;
SqlCommand cmd;
string str1 = "update app1 set p_id=0 where p_id='" + strID + "'";
cmd = new SqlCommand(str1, con);
con.open();
cmd .ExecuteNonQuery ();
con.close();
}
}
}
I'm guessing you really don't have a space in cmd .ExecuteNonQuery ();
When debugging, can you step into the if(chkUpdate.Checked) block?
I think the only problem in the query is the "Where" condition... if the p_id is Int type then you don't have to use ''...
So the statement must be :
string str1 = "update app1 set p_id=0 where p_id=" + strID;

Categories

Resources