C# Deleting a Row from AccessDatabase / Converting String to Int

67 Views Asked by At

I'm a novice programmer trying to delete a row from an AccessDatabase using a "DELETE FROM " query. It requires converting a string to an Int which is where the problem occurs

Here's the Code I'm running :

private void BtnDelete_Click(object sender, EventArgs e)
{

    OleDbConnection Conn = new OleDbConnection();
    Conn.ConnectionString = @"Provider = Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\\HoliPlanData.accdb;Persist Security Info=False";

    try
    {
         Conn.Open();
            String Query = "DELETE * FROM [Employee] WHERE PayrollNo = @PayrollNo";
            OleDbCommand DoDelete = new OleDbCommand(Query, Conn);
            String PayrollNo = PassPayrollNo;
            int PayRowNum = 0;
            bool isValid = int.TryParse(PassPayrollNo, out PayRowNum);
            if (isValid)
            {
                DoDelete.Parameters.AddWithValue("@PayrollNo", PayRowNum);
                DoDelete.ExecuteNonQuery();
                MessageBox.Show("Success");
                Conn.Close();   
            }
            else
            {
                MessageBox.Show("Could not convert to string");
                Conn.Close();
            }         

}

When I run this I get into the Else clause, so the conversion to string isn't working

What's going wrong? Why? Any help would be greatly appreciated, thanks.

2

There are 2 best solutions below

11
On BEST ANSWER

Try with passing int type parameter:

int payrowNum = 0;
bool isValid = int.TryParse(PassPayrollNo, out payrowNum);
if(isValid)
{
     string sQuery = "DELETE * FROM [Employee] WHERE PayrollNo = @PayrollNo";
     OleDbCommand DoDelete = new OleDbCommand(sQuery, Conn);
     DoDelete.Parameters.AddWithValue("@PayrollNo", payrowNum);
     int rowsAffected = DoDelete.ExecuteNonQuery();
     if(rowsAffected>0)
     {
         MessageBox.Show("Success");
     }
     Conn.Close();   

}
0
On

The problem is with your parameter @PayrollNo, you have to make sure the variable PassPayrollNo is the same type as the PayrollNo in your table. If you show the types you are using we can try to help you more.