eugene
eugene

Reputation: 658

Not all code return value in this method

This is the method i was using to check if there is a match of title in the data table:

public static bool checkBook(DataTable dt, String title)
{
    try
    {
        foreach (DataRow dr in dt.Rows)
        {
            String checktitle = dr["Title"].ToString();
            if (title == checktitle)
                return true;
            else
                return false;
    }
    catch (Exception ex)
    {
        //do something
        return false;
     }
}

but there is a problem, i try to use try and catch but why there is no value return?

Upvotes: 1

Views: 107

Answers (3)

saluce
saluce

Reputation: 13340

What happens if there are no rows in the data?
What gets returned then?

Upvotes: 2

Pranay Rana
Pranay Rana

Reputation: 176886

there is error because if there is no row in datatable nothing get returned form code so that you need to return false like as below in code ,

Refine code for you :

    public static bool checkBook(DataTable dt, String title)
    {
      bool returnval= false;
      try 
      {

         foreach (DataRow dr in dt.Rows)
            {
                String checktitle = dr["Title"].ToString();
                if (title == checktitle)
                {
                    returnval= true;
                }

        }
    catch (Exception ex)
    {
     //do something
    }
    return returnval;
   }

Upvotes: 2

Tejs
Tejs

Reputation: 41236

You aren't returning anything from the try block in the situation where nothing is enumerated from dt.Rows.

Outside the foreach in the try block, you simply need to add return false;

Upvotes: 6

Related Questions