Firstly, your code is vulnerable to
SQL Injection[
^].
NEVER use string concatenation to build a SQL query.
ALWAYS use a parameterized query.
Everything you wanted to know about SQL injection (but were afraid to ask) | Troy Hunt[
^]
How can I explain SQL injection without technical jargon? | Information Security Stack Exchange[
^]
SQL injection attack mechanics | Pluralsight [
^]
Secondly, you are saving the PDF file
on the server. You are then passing the local path of the file on the server back to the client and asking it to display that file.
That
will not work. Either the client will try to open the file in it's own
D:
drive, which will fail as the file doesn't exist; or, more likely, the browser will refuse to attempt to open a local file in an
iframe
from an internet site.
You need to point the
iframe
to a URL on your server which will generate the PDF and send it back to the client. Something like this should work:
public partial class dropdown_to_gridview : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
if (Request.QueryString["action"] == "export")
{
string salary = Request.QueryString["salary"];
GridViewBind(salary);
ExportPdf();
Response.End();
}
}
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
GridViewBind(DropDownList1.SelectedValue);
}
protected void btnExportPDF_Click(object sender, EventArgs e)
{
iframepdf.Attributes["src"] = Request.Path + "?action=export&salary=" + HttpUtility.UrlEncode(DropDownList1.SelectedValue);
}
private void GridViewBind(string salary)
{
const string cs = "Data Source=HOME;Initial Catalog=Registration;Integrated Security=True";
using (SqlConnection con = new SqlConnection(cs))
using (SqlCommand cmd = new SqlCommand("select * from employeep where Salary = @Salary", con))
{
cmd.Parameters.AddWithValue("@Salary", salary);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
}
}
private void ExportPdf()
{
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition", "attachment;filename=report.pdf");
StringWriter sw = new StringWriter();
using (HtmlTextWriter hw = new HtmlTextWriter(sw))
{
GridView1.RenderControl(hw);
}
Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 10f, 0f);
PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
HTMLWorker htmlparser = new HTMLWorker(pdfDoc);
pdfDoc.Open();
htmlparser.Parse(new StringReader(sw.ToString()));
pdfDoc.Close();
}
public override void VerifyRenderingInServerForm(Control control)
{
}
}