-1
while (reader.Read())
{
    var g = reader.FieldCount;
    if (g > 0)
    {
        string a = reader.GetString(1);
        string b = reader.GetString(3);
        string c = reader.GetString(4);
        string d = reader.GetString(5);

        await context.PostAsync($" ### Please find below the fleet policy information \n #### Policy number - " +
        $"`{a}` \n #### Policy type - `{b}` \n #### Property - `{c}` \n #### Number - `{d}` ");
    }
    else
    {
         await context.PostAsync("Record not found");
    }
}

If record does not exist in database I want the bot to display record not found but it seem not to work, instead it displays nothing.

Cœur
  • 37,241
  • 25
  • 195
  • 267

2 Answers2

0

You check the property HasRows instead

if(reader.HasRows)
{
     while (reader.Read())
     {
         string a = reader.GetString(1);
         string b = reader.GetString(3);
         string c = reader.GetString(4);
         string d = reader.GetString(5);

         await context.PostAsync(...........);
     }
}
else
{
    await context.PostAsync("Record not found");
}

Actually Read return false when there are no more record to read. In the case where you don't have any record to read the method returns false immediately and you never enter the read loop where you have the code to output your message. Of course the FieldCount has no meaning here because it counts the fields not the rows of the returned IDataRecord from the Read method.

Thus your solution is to check the HasRows property before starting the loop and printing your message if it returns false.

Steve
  • 213,761
  • 22
  • 232
  • 286
0

reader.Read() indicates that there are actual records in the dataset. You should put your code outside of the while.

Martin
  • 475
  • 4
  • 14