Click here to Skip to main content
15,889,281 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
My code behind for GetCasesButton_Click have an error which I am unable to fix. I need help.
The error is on await CandidateCaseController.GetNextBAtchNumber() line.

It says The 'await' operator can only be used within an async method. Consider marking this method with the 'async' modifier and changing its return type to 'Task'.

Please help fix this.

What I have tried:

Here is the code behind for GetCasesButton_Click
C#
protected void GetCasesButton_Click(object sender, EventArgs e)
 {
 #region Required Field Validation
    if (CaseNumbersTextBox.Text.Length < 1)
    {
       string myStringVariable = "Case number textbox cannot be empty.";
       ClientScript.RegisterStartupScript(this.GetType(), "myalert", "alert('" + myStringVariable + "');", true);
     }
        if (RequestorDropDownList.SelectedItem.Value !=null)
        {
            ListItem requestorItem = new ListItem();
            requestorItem = (ListItem)RequestorDropDownList.SelectedItem;
        }
            
        if (ReasonDropDownList.SelectedItem.Value !=null)
        {
           ListItem reasonItem = new ListItem();
           reasonItem = (ListItem)ReasonDropDownList.SelectedItem;
        }
        #region Parse case number entries
        string userEnteredCaseNumbers = CaseNumbersTextBox.Text;
        userEnteredCaseNumbers = userEnteredCaseNumbers.Replace("\r", ",");
        userEnteredCaseNumbers = userEnteredCaseNumbers.Replace("\n", ",");
        
        while (userEnteredCaseNumbers.Contains(",,"))
            userEnteredCaseNumbers = userEnteredCaseNumbers.Replace(",,", ",");
            List<string> userEnteredCaseNumberList = new List<string>();
            userEnteredCaseNumberList = userEnteredCaseNumbers.Split(',').Where(x => x.Length > 0).ToList();
            userEnteredCaseNumberList = userEnteredCaseNumberList.Select(s => s.Trim()).ToList();
            #endregion
        try
        {
          #region Get Batch Number
          int newBatchNumber = await CandidateCaseController.GetNextBatchNumber();
          #endregion
          #region Insert entered case numbers in database
          foreach(string caseNumber in userEnteredCaseNumberList)
          {
             EditCandidateCaseModel newCandidate = new EditCandidateCaseModel();
             newCandidate.CaseNbr = caseNumber;
             //newCandidate.RequestorInfoID = requestorItem.Value;
             //newCandidate.RequestorInfoID = (ListItem)RequestorDropDownList.SelectedItem.Value;
             //newCandidate.ReasonID = requestorItem.Value;
             newCandidate.BatchNumber = newBatchNumber;
             newCandidate.EntryStaffUserName = this._loggedInUserName;
             await CandidateCaseController.PostCandidate(newCandidate);
          }

          #endregion
          }
            catch (Exception ex)
            {
               string errorMsg = string.Format("An error has occured in {0}. \nException:\n{1}", "GetCasesButton_Click()", ex.Message);
                MessageBox.Show(errorMsg, "Application Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                ClientScript.RegisterStartupScript(this.GetType(), "myalert", "alert('" + errorMsg + "');", true);
                return;
            }
}


Here is the aspx code for the button
C#
<asp:Button ID="GetCasesButton" runat="server" Text="Get Cases" Font-Size="8.25"
    BackColor="RoyalBlue" ForeColor="White" Height="24px" Width="74px"
    OnClick="GetCasesButton_Click" />
Posted
Updated 9-Jan-20 9:38am

1 solution

Since you're not returning anything, I believe it's as simple as turning:
protected void GetCasesButton_Click(object sender, EventArgs e)

to
protected async void GetCasesButton_Click(object sender, EventArgs e)


If the return was to be something other than void, an additional requirement of "
C#
async Task<return type>
" would be included in the method header.
 
Share this answer
 
v3
Comments
Richard Deeming 9-Jan-20 15:48pm    
Before you do that, read:
Avoid async void methods | You’ve Been Haacked[^]

The recommendation from David Fowler is to create a separate async Task method, call that from your void method, and use a "discard" to avoid the compiler warning.
protected void GetCasesButton_Click(object sender, EventArgs e)
{
    _ = GetCasesButtonClickAsync();
}

private async Task GetCasesButtonClickAsync()
{
    ...
}

AspNetCoreDiagnosticScenarios/AsyncGuidance.md at master · davidfowl/AspNetCoreDiagnosticScenarios · GitHub[^]

That way, unhandled exceptions in the async method will raise the TaskScheduler.UnobservedTaskException event[^] instead of crashing the process.
Kris Lantz 9-Jan-20 15:51pm    
I hadn't considered that. I appreciate your addition, good sir.
Member 11403304 9-Jan-20 15:51pm    
Thank you so very much Kris. Your solution did fix the problem and data was inserted into database table. Step one is now done. I have other questions that I will post as I continue to develop my web app. Thank you again. It turned out the solution was very simple!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900