0

C# data export to excel - error

Hi all, hope in your help.

I am creating a C# 2010 Web application.

I have researched and test this and this should work...but I get an error and I can't get past this problem...my code below.

I would greatly appreciate any help you can give me in working this problem

CS0161: '_Default.GetData(System.Data.Odbc.OdbcCommand)': not all code paths return a value

private DataTable GetData(OdbcCommand cmd)
{
    DataTable dt = new DataTable();
    OdbcDataAdapter sda = new OdbcDataAdapter();

    cmd.CommandType = CommandType.Text;
    cmd.Connection = con;

    try
    {
        con.Open();
        sda.SelectCommand = cmd;
        sda.Fill(dt);

        if (dt.Rows.Count > 0)
        {
            return dt;
        }
        else
        {
            string strScript = "<script>" + "alert('Not found!.');";
            strScript += "window.location='default.aspx';";
            strScript += "</script>";
            Page.ClientScript.RegisterStartupScript(this.GetType(), "Startup", strScript);
        }
    }
    catch (Exception ex)
    {
        throw ex;
    }
    finally
    {
        con.Close();
        sda.Dispose();
        con.Dispose();
    }
}

3 Answers 3

1

Well, the compiler already told you what your problem is. You only return the DataTable if certain requirements are met. However a non-void method most return something in all possible code paths.

Sign up to request clarification or add additional context in comments.

Comments

0

Just add this before the closing bracket

return dt;

Comments

0

The if clause checking for rows in the data table excludes the rest of the method from returning the signature the method dictates to be returned. You most likely want to get rid of the if/else clause and just return the data table regardless of the row count. Your code calling the method should be doing the checking for row count and rendering the alert. I would also highly recommend using StringBuilder when concatenating strings like that... Or since the string seems to be static text, use it as such with a constant.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.