2017-02-20 70 views
-1

嗨,你把这个标记为重复之前我已经看过,并尝试过别人,没有运气。我不断收到字符串getBrand的错误说:不是所有的代码路径都返回一个值c# - 私有字符串和for循环

不是所有的代码路径都返回一个值。

private string getBrand(string id) 
{ 
    con.Open(); 
    SqlCommand cmd = con.CreateCommand(); 
    cmd.CommandType = CommandType.Text; 
    cmd.CommandText = "Select brand from tbl_products where productId = '" + id + "'"; 
    cmd.ExecuteNonQuery(); 
    con.Close(); 
    DataTable dt = new DataTable(); 
    SqlDataAdapter sda = new SqlDataAdapter(cmd); 
    sda.Fill(dt); 
    getBrand = dt.Rows[0][0].ToString(); 
}  

下面是我得到的字符串“ID”是传递给getBrand字符串希望运行的查询。

for (int i = 0; i < salesGridView.Rows.Count; i++) 
{ 
    table2.AddCell(new Phrase(salesGridView[1, i].Value.ToString(), normFont)); 
    string id = salesGridView[0, i].Value.ToString(); 
    table2.AddCell(new Phrase(getBrand(id), normFont)); 
} 
+2

C#是不是VBA。您通过使用'return'关键字返回,而不是通过为该函数的名称设置一个值。 – InBetween

+0

您从不使用实际返回值到调用方法的返回语句 – 97hilfel

+0

[可能首先阅读此文章。](https://msdn.microsoft.com/en-us/library/ms173114.aspx)返回值 – DomeTune

回答

3

您已将dt.Rows[0][0].ToString();存储到方法的名称中。您需要从您的方法中返回以下行:

return dt.Rows[0][0].ToString(); 

或者将其存储在其他变量的名称中,然后返回该变量。就像这样:

var temp = dt.Rows[0][0].ToString(); 
return temp; 
+0

辉煌!谢谢:) – ZeeSoft

+0

需要等待10分钟才能将其标为正确! – ZeeSoft

0

你应该做的是这样的:

private string getBrand(string id) 
    { 
     con.Open(); 
     SqlCommand cmd = con.CreateCommand(); 
     cmd.CommandType = CommandType.Text; 
     cmd.CommandText = "Select brand from tbl_products where productId = '" + id + "'"; 
     cmd.ExecuteNonQuery(); 
     con.Close(); 
     DataTable dt = new DataTable(); 
     SqlDataAdapter sda = new SqlDataAdapter(cmd); 
     sda.Fill(dt); 

     return dt.Rows[0][0].ToString(); 
    }  
相关问题