简体   繁体   中英

C# Error - Not all code path return value

I'm getting an error "not all code paths return a value" in method getdatatoTextbox .

Please help me fix this problem.

private DataTable getdatatoTextbox(int RegistrationId)
{
    try
    {
        SqlConnection con = new SqlConnection("Data Source=.;Initial Catalog=DotNetFunda;User id=sa;Password=sqluser");
        con.Open();
        SqlCommand sqlcmd = new SqlCommand("Getdatatotextbox", con);
        sqlcmd.CommandType = CommandType.StoredProcedure;
        sqlcmd.Parameters.AddWithValue("@RegistrationId", SqlDbType.Int).Value = RegistrationId;
        DataTable dtdatanew = new DataTable();
        SqlDataAdapter da = new SqlDataAdapter(sqlcmd);
        da.Fill(dtdatanew);
        con.Close();
        return dtdatanew;
    }
    catch (Exception ex)
    {
    }
    finally
    {
        con.Dispose();
    }
}

If the event of an Exception nothing is being returned which is not valid if you have a non void return type in your method. Also never swallow exceptions, its bad practice and when something goes wrong you come back later asking questions on SO with why.

On another note, you should wrap all your Disposables in using blocks. If your query fails your Db connection will remain open the way your code is now, I know you have the dispose in the finally but that wont even compile because you defined it inside your try block.

This would fix the problem and give you an Exception (a good thing) when something unexpected happens. You can handle it outside the method or let it bubble up to the original caller and then do something.

private DataTable getdatatoTextbox(int RegistrationId)
{
    using(SqlConnection con = new SqlConnection("Data Source=.;Initial Catalog=DotNetFunda;User id=sa;Password=sqluser"))
    using(SqlCommand sqlcmd = new SqlCommand("Getdatatotextbox", con))
    using(SqlDataAdapter da = new SqlDataAdapter(sqlcmd))
    {
        con.Open();
        sqlcmd.CommandType = CommandType.StoredProcedure;
        sqlcmd.Parameters.AddWithValue("@RegistrationId", SqlDbType.Int).Value = RegistrationId;
        DataTable dtdatanew = new DataTable();
        da.Fill(dtdatanew);
        return dtdatanew;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM