Search code examples
c#ms-accessrowdeleting

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


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.


Solution

  • 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();   
    
    }