C#从AccessDatabase删除行/将字符串转换为Int

时间:2016-02-24 09:45:12

标签: c# ms-access rowdeleting

我是一名新手程序员,试图使用“DELETE FROM”查询从AccessDatabase中删除一行。它需要将字符串转换为发生问题的Int

这是我正在运行的代码:

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

}

当我运行这个时,我进入了Else子句,因此转换为字符串不起作用

出了什么问题?为什么? 非常感谢任何帮助,谢谢。

2 个答案:

答案 0 :(得分:1)

问题在于您的参数@PayrollNo,您必须确保变量PassPayrollNo与表中的PayrollNo类型相同。如果您显示正在使用的类型,我们可以尝试为您提供更多帮助。

答案 1 :(得分:1)

尝试传递int类型参数:

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

}