Update table failure without any error - c#

I'm current facing a strange issue that everytime i want to update my table value field from reserved to cancelled.
every time i click the button it din't pop any error but when i went to my ms-access to check it never change...
My Method:
public static void CancelClasses(int rid, int mid)
{
OleDbConnection myconnection = GetConnection();
string mysql = "UPDATE ClassesReservation SET Status = 'cancelled' WHERE ReservationID= "+rid+" AND MID="+mid+";";
OleDbCommand mycmd = new OleDbCommand(mysql, myconnection);
try
{
myconnection.Open();
mycmd.ExecuteNonQuery();
}
catch
{
throw;
}
finally
{
myconnection.Close();
}
}
Button Function:
protected void CancelWS_Click(object sender, EventArgs e)
{
if (ListBox3.SelectedIndex < 0)
{
Label2.Text = "Invalid Submit! Please select an Class or Workshop";
}
else
{
int reid = int.Parse(ListBox3.SelectedValue);
int MID = Convert.ToInt32(Session["memberid"]);
DBconn.CancelClasses(reid, MID);
}
}

Related

How to update oracle database table in c# with variable from text.box

When I click on update button I dont get any errors but my table isnt updated.
private void Button3_Click(object sender, EventArgs e)
{
try
{
OracleConnection cnn = new OracleConnection(oradb);
cnn.Open();
oracleCommand = new OracleCommand("UPDATE KUPAC SET NAZIVKUPCA = :NAZIVKUPCA, PIB = :PIB, MATICNIBROJ = :MATICNIBROJ, ZIRORACUN = :ZIRORACUN, EMAIL = :EMAIL WHERE KUPACID = :KUPACID", cnn);
oracleCommand.Parameters.Add("#KUPACID", Convert.ToInt32(txtKupacId.Text));
oracleCommand.Parameters.Add("#NAZIVKUPCA", txtNazivKupca.Text);
oracleCommand.Parameters.Add("#PIB", txtPIB.Text);
oracleCommand.Parameters.Add("#MATICNIBROJ", txtJMBG.Text);
oracleCommand.Parameters.Add("#ZIRORACUN", txtZiroRacun.Text);
oracleCommand.Parameters.Add("#EMAIL", txtEmail.Text);
int result = oracleCommand.ExecuteNonQuery();
MessageBox.Show("Kupac uspesno izmenjen");
}
catch (Exception exc)
{
MessageBox.Show("Greska prilikom izmena u bazi." + exc.Message);
}
finally
{
}
OsveziKupce();
ObrisiPolja();
}
I get message "Kupac uspesno izmenjen", which means that table should be updated, but nothing happens

System.InvalidCastException - Specified cast is not valid exception

Working with a mysql dbase and c#,
Below is the method I created in database class to check if the row exists.
public int CheckRows(string query)
{
try
{
openConnection();
}
catch (MySqlException ex)
{
MessageBox.Show(ex.Message);
}
cmd = new MySqlCommand(query, con);
int read = (Int32)cmd.ExecuteScalar();
return read;
cmd.Dispose();
closeConnection();
}
And the button click event,
private void button2_Click(object sender, EventArgs e)
{
int invoice = Convert.ToInt32(textBox9.Text);
string qry = "Select 1 from purchase where purchId='" + invoice + "'";
int dub = db.CheckRows(qry);
}
Which gives the mentioned exception. What am I doing wrong here?

C# update statement not updating when update button clicked

i am creating c# project so far insert and delete buttons are working but when i hit update button it gives data has not been updated and i cant see what is wrong with my code please help
public bool Update(Classre c)
{
bool isSuccess = false;
SqlConnection conn = new SqlConnection(myconnstring);
try
{
string sql = "UPDATE Class SET ClassName=#ClassName,ClassLevel=#ClassLevel WHERE ClassID=#ClassID";
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.Parameters.AddWithValue("#ClassName", c.ClassName);
cmd.Parameters.AddWithValue("#ClassLevel", c.ClassLevel);
conn.Open();
int rows = cmd.ExecuteNonQuery();
if (rows > 0)
{
isSuccess = true;
}
else
{
isSuccess = false;
}
}
catch (Exception ex)
{
}
finally
{
conn.Close();
}
return isSuccess;
}
and this is my update button code where i call the class that holds my update code
private void button3_Click(object sender, EventArgs e)
{
c.ClassID = int.Parse(textBox1.Text);
c.ClassName = textBox2.Text;
c.ClassLevel = comboBox1.Text;
bool success = c.Update(c);
if (success == true)
{
// label4.Text = "Data Has been updated";
MessageBox.Show("Data Has been updated");
DataTable dt = c.Select();
dataGridView1.DataSource = dt;
}
else
{
//label4.Text = "Data Has not been updated";
MessageBox.Show("Data Has not been updated");
}
}
I would prefer to use a stored procedure instead of pass through sql but you could greatly simplify this. As stated above your try/catch is worse than not having one because it squelches the error.
public bool Update(Classre c)
{
USING(SqlConnection conn = new SqlConnection(myconnstring))
{
string sql = "UPDATE Class SET ClassName = #ClassName, ClassLevel = #ClassLevel WHERE ClassID = #ClassID";
USING(SqlCommand cmd = new SqlCommand(sql, conn))
{
cmd.Parameters.Add("#ClassName", SqlDbType.VarChar, 4000).Value = c.ClassName;
cmd.Parameters.Add("#ClassLevel", SqlDbType.Int).Value = c.ClassLevel;
cmd.Parameters.Add("#ClassID", SqlDbType.Int).Value = c.ClassID;
conn.Open();
int rows = cmd.ExecuteNonQuery();
return rows > 0;
}
}
}

DataSet not updated with new row inserted in C#

i am trying to insert new row in Emp table in c# (disconnected mode), the new row successfully inserted but the dataset not updated, so when i search for the new row, i don't find it, but when i search for an old row, i find it.
the insertBTN button used to insert new row
the searchByID button used to search for row by its ID
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private SqlConnection conn;
private SqlDataAdapter adapter;
private DataSet ds;
private void Form1_Load(object sender, EventArgs e)
{
conn = new SqlConnection(#"data source=(local);initial catalog =Test;integrated security = true");
conn.Open();
adapter = new SqlDataAdapter("select * from Emp",conn);
ds = new DataSet();
adapter.Fill(ds,"Emp");
}
private void insertBTN_Click(object sender, EventArgs e)
{
try
{
int id = int.Parse(textBox1.Text);
string name = textBox2.Text;
string address = textBox3.Text;
int age = int.Parse(textBox4.Text);
int salary = int.Parse(textBox5.Text);
SqlCommand command = new SqlCommand("Insert into Emp values(" + id + ",'" + name + "','" + address + "'," + age + "," + salary + ")", conn);
command.ExecuteNonQuery();
adapter.Update(ds,"Emp");
MessageBox.Show("Employee added successfully");
}
catch (Exception exception)
{
MessageBox.Show(exception.Message);
}
}
private void searchByID_Click(object sender, EventArgs e)
{
try
{
int id = int.Parse(textBox1.Text);
foreach (DataRow row in ds.Tables["Emp"].Rows)
{
if (Convert.ToInt32(row["id"]) == id)
{
textBox2.Text = Convert.ToString(row["name"]);
textBox3.Text = Convert.ToString(row["address"]);
textBox4.Text = Convert.ToString(row["age"]);
textBox5.Text = Convert.ToString(row["salary"]);
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
The Update method of the DataAdapter doesn't read again but tries to execute the INSERT, DELETE and UPDATE commands derived from the original SELECT statement against the Rows in the DataTable that have their RowState changed
So, if you want to use the Update method of the adapter you could write
private void insertBTN_Click(object sender, EventArgs e)
{
try
{
DataRow row = ds.Tables["emp"].NewRow();
row.SetField<int>("id", int.Parse(textBox1.Text));
row.SetField<string>("name", textBox2.Text));
row.SetField<string>("address", textBox3.Text));
row.SetField<int>("age", int.Parse(textBox4.Text));
row.SetField<int>("salary", int.Parse(textBox5.Text));
ds.Tables["emp"].Rows.Add(row);
adapter.Update(ds,"Emp");
MessageBox.Show("Employee added successfully");
}
catch (Exception exception)
{
MessageBox.Show(exception.Message);
}
}
At this point your DataSet contains the added row because you have added it manually and then passed everything to the Update method to write it to the database.
However, keep in mind that the Update method to work requires certain conditions to be present. You could read them in the DbDataAdapter.Update page on MSDN.
Mainly you need to have retrieved the primary key of the table, do not have more than one table joined together and you have used the DbCommandBuilder object to create the required commands (Again the example in the MSDN page explain it)
Not related to your question, but you could change your search method and avoid writing a loop to search for the ID
private void searchByID_Click(object sender, EventArgs e)
{
try
{
int id = int.Parse(textBox1.Text);
DataRow[] foundList = ds.Tables["Emp"].Select("Id = " + id);
if(foundList.Length > 0)
{
textBox2.Text = foundList[0].Field<string>("name");
textBox3.Text = foundList[0].Field<string>("address");
textBox4.Text = foundList[0].Field<int>("age").ToString();
textBox5.Text = foundList[0].Field<int>("salary").ToString();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}

Delete record from MDF database

I want to create simple application in C#. It should be windowsForms app, with service-based database added to project. In this I want to make table (ID, name, second name) and in program show name into listBox. Current name selected in listBox will be deleted (row will be deleted)
Can anyone help me how to do it? I have try with dataset, this is working, but after I close app and run it again, table is full with data again.
For saving records into database and loading them in a listbox you can see..
save-data-to-database-then-load-data-to-listbox
Now,for deleting a record from a listbox you can code like this..
protected void removeButton_Click(object sender, EventArgs e)
{
if (ListBox1.SelectedItem.Text == null)
{
MessageBox.Show("Please select an item for deletion.");
}
else
{
for (int i = 0; i <= ListBox1.Items.Count - 1; i++)
{
if (ListBox1.Items[i].Selected)
{
DeleteRecord(ListBox1.Items[i].Value.ToString());
}
}
string remove = ListBox1.SelectedItem.Text;
ListBox1.Items.Remove(remove);
}
}
For deleting that record also from database use like this..
private void DeleteRecord(string ID)
{
SqlConnection connection = new SqlConnection("YOUR CONNECTION STRING");
string sqlStatement = "DELETE FROM Table1 WHERE Id = #Id";
try
{
connection.Open();
SqlCommand cmd = new SqlCommand(sqlStatement, connection);
cmd.Parameters.AddWithValue("#Id", ID);
cmd.CommandType = CommandType.Text;
cmd.ExecuteNonQuery();
}
catch (System.Data.SqlClient.SqlException ex)
{
string msg = "Deletion Error:";
msg += ex.Message;
throw new Exception(msg);
}
finally
{
connection.Close();
}
}

Categories