2016-07-07 112 views
1

我需要阻止用戶通過編寫某人不在應用程序上的批准。我已經將Where IS NULL設置爲阻止它覆蓋數據,但我需要顯示一個標籤,說明記錄未更新爲已批准。如何知道行是否已更新

我如何知道sql查詢是否更新或沒有,並獲取該信息,所以我可以做一個If語句。

If row updated then 
    label.text = "data approved" 
else 
    label.text = "You can not approve this as it's already approved" 


CheckBox ckb = (CheckBox)sender; 
     GridViewRow row = (GridViewRow)ckb.Parent.Parent;   //Get row selected 
     int idx = row.RowIndex; 

     //Get activity number ID for update query 
     Label lblDHActivityNoApp = (Label)row.Cells[0].FindControl("lblDHActivityNoApp"); 
     string Number = lblDHActivityNoApp.Text.ToString(); 

     string connectionString = ConfigurationManager.ConnectionStrings["PlusConnectionString"].ConnectionString; 
     string UpdateSql = "UPDATE Activities SET Status = @Status, [email protected], [email protected] WHERE ApprovedBy IS NULL and ([email protected])"; 
     //Create SQL connection 
     SqlConnection con = new SqlConnection(connectionString); 

     //Create SQL Command And Sql Parameters 
     SqlCommand cmd = new SqlCommand(); 
     cmd.Connection = con; 
     cmd.CommandType = CommandType.Text; 
     cmd.CommandText = UpdateSql; 

     SqlParameter Status = new SqlParameter("@Status", SqlDbType.VarChar, 40); 
     Status.Value = "Approved"; 
     cmd.Parameters.Add(Status); 

     SqlParameter ApprovedDate = new SqlParameter("@ApprovedDate", SqlDbType.VarChar, 50); 
     DateTime myDateTime = DateTime.Now; ; 
     ApprovedDate.Value = myDateTime.ToString("dd/MM/yy HH:mm:ss"); 
     cmd.Parameters.Add(ApprovedDate); 

     SqlParameter ApprovedBy = new SqlParameter("@ApprovedBy", SqlDbType.VarChar, 40); 
     ApprovedBy.Value = (string)Session["Username"]; 
     cmd.Parameters.Add(ApprovedBy); 

     SqlParameter No = new SqlParameter("@No", SqlDbType.VarChar, 50); 
     No.Value = Number; 
     cmd.Parameters.Add(No); 

     try 
     { 
      con.Open(); 
      cmd.ExecuteNonQuery(); 
      gbDHdetailsApp.DataBind(); //Reloads gridview with checked data  
     } 

     catch (SqlException ex) 
     { 
      string errorMessage = "Not approved, please contact support"; 
      errorMessage += ex.Message; 
      throw new Exception(errorMessage); 
     } 

     finally 
     { 
      con.Close(); 
     } 

回答

1

ExecuteNonQuery()返回受影響的行數和具有返回類型INT,因此你可以像

int rowsAffected = cmd.ExecuteNonQuery(); 

if(rowsAffected > 0) 
{ 
    // do something 
} 
4

ExecuteNonQuery返回受影響的行數。如果這是0,則可以拋出一個Exception

相關問題