-1

Hi before you mark this as a duplicate I have looked and tried others and had no luck. I keep getting the error for the string getBrand saying that:

not all code paths return a value.

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

Below is where I get the string 'id' that pass to the getBrand String wish the run the query from.

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));
}
Salah Akbari
  • 39,330
  • 10
  • 79
  • 109
zayn94
  • 65
  • 1
  • 11
  • 2
    c# is not VBA. You return by using the `return` keyword, not by setting a value to the function's name. – InBetween Feb 20 '17 at 11:41
  • You never use a return statement that actually returns a value to the calling method – 97hilfel Feb 20 '17 at 11:42
  • [Maybe read this article first.](https://msdn.microsoft.com/en-us/library/ms173114.aspx) Return Values – DomeTune Feb 20 '17 at 11:45
  • Possible duplicate of [c# returning error "not all code paths return a value"](http://stackoverflow.com/questions/21197410/c-sharp-returning-error-not-all-code-paths-return-a-value) – Manfred Radlwimmer Feb 20 '17 at 11:47

2 Answers2

4

You've stored the dt.Rows[0][0].ToString(); into the method's name. You need to return the following line from your method:

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

Or store it in a different variable's name and then return that variable. Like this:

var temp = dt.Rows[0][0].ToString();
return temp;
Salah Akbari
  • 39,330
  • 10
  • 79
  • 109
0

You should do it this way:

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