简体   繁体   English

C# 错误 - 并非所有代码路径返回值

[英]C# Error - Not all code path return value

I'm getting an error "not all code paths return a value" in method getdatatoTextbox .我在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.如果发生 Exception 事件,则不会返回任何内容,如果您的方法中有非void返回类型,则这是无效的。 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.另一方面,您应该将所有 Disposable 包装在using块中。 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.如果您的查询失败,您的 Db 连接将像您现在的代码一样保持打开状态,我知道您在 finally 中有处置,但它甚至无法编译,因为您在try块中定义了它。

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;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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