none
“system_program.system.getMAX(string, string, string, string)”: 并非所有的代码路径都返回值 无法返回值 RRS feed

  • 问题

  • 刚学C#不久,写了一段代码,运行时出现错误,提示并非所有的代码都有返回值,请大家帮我看看下面这段代码

            public static string getMAX(string Id,string DataTable,string Condition,string Conditionvalue) 
            {
                string Maxsql = "select max(" + Id + ")from" + DataTable + "where" + Condition + "=" + Conditionvalue + "";
                SqlConnection con = new SqlConnection(SQLconnection);
                con.Open();
                SqlCommand cmdText = new SqlCommand();
                cmdText.Connection = con;
                cmdText.CommandText = Maxsql;
                SqlDataReader views = cmdText.ExecuteReader();
                int Max = 0;
                while (views.Read())
                {
                    if (views[0].ToString() == "")
                    {
                         return "0001";
                    }
                    else
                    {
                        Max = Convert.ToInt32(views[0].ToString());
                        ++Max;
                        string MaxNum = string.Format("0:0000}", Max);
                        return MaxNum;
                    }
                }
            }

    2010年12月8日 7:30

答案

  • while (views.Read())这一句中views.Read()如果为false的话,就没有对应的返回语句了,你可以试一下:

            public static string getMAX(string Id, string DataTable, string Condition, string Conditionvalue)
            {
                string Maxsql = "select max(" + Id + ")from" + DataTable + "where" + Condition + "=" + Conditionvalue + "";
                SqlConnection con = new SqlConnection("SQLconnection");
                con.Open();
                SqlCommand cmdText = new SqlCommand();
                cmdText.Connection = con;
                cmdText.CommandText = Maxsql;
                SqlDataReader views = cmdText.ExecuteReader();
                int Max = 0;
                while (views.Read())
                {
                    if (views[0].ToString() == "")
                    {
                        return "0001";
                    }
                    else
                    {
                        Max = Convert.ToInt32(views[0].ToString());
                        ++Max;
                        string MaxNum = string.Format("0:0000}", Max);
                        return MaxNum;
                    }
                }
                return "some value";
            }


    Sincerely,
    Eric
    MSDN Subscriber Support in Forum
    If you have any feedback of our support, please contact msdnmg@microsoft.com.
    Please remember to mark the replies as answers if they help and unmark them if they provide no help.
    Welcome to the All-In-One Code Framework! If you have any feedback, please tell us.
    • 已标记为答案 Creek.L 2010年12月12日 9:09
    2010年12月9日 3:46