c#中的数据表错误

时间:2015-10-05 11:03:57

标签: c#

我使用数据表从mysql db中获取一些数据,我的错误是

  

并非所有代码路径都返回值

return DS.Tables[0]无法在循环或if语句中访问。如何解决此问题?

public DataTable GetAlltheatredet()//I got error here//
{
    DataTable myalltheat = GetAllmytheatdet();
    foreach (DataRow drow1 in myalltheat.Rows)
    {
        usermsterid = drow1["UserMasterId"].ToString();
        if (usrmid == usermsterid)
        {
            flag = 1;
            break;
        }
        if (flag == 1)
        {
            try
            {
                string connString = "Server=localhost;database=Mytable;uid=root;";
                string query = "SELECT * FROM `Mytable`.`Mydata`";
                MySqlDataAdapter ma = new MySqlDataAdapter(query, connString);
                DataSet DS = new DataSet();
                ma.Fill(DS);
                return DS.Tables[0];
            }
            catch (MySqlException e)
            {
                throw new Exception(e.Message);
            }
        }
    }
}

2 个答案:

答案 0 :(得分:5)

您有if(flag==1) { ... return ... }您需要添加else语句,其中包含returnthrow new ...

public DataTable GetAlltheatredet()//I got error here//
{
    DataTable myalltheat = GetAllmytheatdet();
    foreach (DataRow drow1 in myalltheat.Rows)
    {
        usermsterid = drow1["UserMasterId"].ToString();
        if (usrmid == usermsterid)
        {
            flag = 1;
            break;
        }
        if (flag == 1)
        {
            try
            {
                string connString = "Server=localhost;database=Mytable;uid=root;";
                string query = "SELECT * FROM `Mytable`.`Mydata`";
                MySqlDataAdapter ma = new MySqlDataAdapter(query, connString);
                DataSet DS = new DataSet();
                ma.Fill(DS);
                return DS.Tables[0];
            }
            catch (MySqlException e)
            {
                throw new Exception(e.Message);
            }
        }
        else {
            throw new Exception("Flag isn't 1 and I don't know what to do");
        }
    }
}

答案 1 :(得分:2)

这是一个众所周知的错误,如果返回DataType的方法有任何多路径块,如if {} else {}或switch case,则应该在它们的每个路径中返回一些内容。