无法使用C#

时间:2017-06-21 10:21:26

标签: c# sql-server-2008

我无法从sql server检索或下载PDF / JPG文件。当我单击浏览器中的按钮时,它没有响应,也没有任何反应。请帮助我。请检查一下,代码是否有任何问题。 我有一个表包含id作为整数和

enter image description here enter image description here

和代码背后:

protected void btnView_Click(object sender, EventArgs e)
    {
        string strQuery = "select Upload_Name, Content_Type, Uploads from Tab_CPD_Hours WHERE id =@id";
        SqlCommand cmd = new SqlCommand(strQuery);
        cmd.Parameters.Add("@id", SqlDbType.Int).Value = 1;
        DataTable dt = GetData(cmd);
        if (dt != null)
        {
            download(dt);
        }
    }

    private void download(DataTable dt)
    {
        Byte[] bytes = (Byte[])dt.Rows[0]["Uploads"];
        Response.Buffer = true;
        Response.Charset = "";
        Response.Cache.SetCacheability(HttpCacheability.NoCache);
        Response.ContentType = dt.Rows[0]["Content_Type"].ToString();
        Response.AddHeader("content-disposition", "attachment;filename="
        + dt.Rows[0]["Upload_Name"].ToString());
        Response.BinaryWrite(bytes);
        Response.Flush();
        Response.End();
    }

public static DataTable GetData(SqlCommand cmd)
    {
        DataTable dt = new DataTable();
        string strConnString = System.Configuration.ConfigurationManager.ConnectionStrings["CS"].ConnectionString;
        SqlConnection con = new SqlConnection(strConnString);
        SqlDataAdapter sda = new SqlDataAdapter();
        cmd.CommandType = CommandType.Text;
        cmd.Connection = con;
        try
        {
            con.Open();
            sda.SelectCommand = cmd;
            sda.Fill(dt);
            return dt;
        }
        catch
        {
            return null;
        }
        finally
        {
            con.Close();
            sda.Dispose();
            con.Dispose();
        }
    }

1 个答案:

答案 0 :(得分:0)

它没有返回任何内容,因为您正在捕获所有错误并返回null ...

catch
{
    return null;
}

获取数据的方法在返回null时什么都不做......

DataTable dt = GetData(cmd);
if (dt != null)
{
    download(dt);
}

您需要通过向用户显示错误消息来正确处理错误...