2017-04-06 27 views
0

嗨我正在一个项目中,我有一个网格视图中的按钮命名为生成条例草案,当点击生成条例草案按钮时,我可以下载.pdf文件。我面临的问题是我得到所有从该表中检索行,但我需要只需要获取生成的单据按钮被点击的选定行。这是我的代码:如何从数据库中检索单行并在asp.net中以.pdf格式显示帐单?

[前端代码]:

<form id="form1" runat="server"> 
<div> 
</div> 
<table border="0" width="90%" height="300px" align="center" class="tableshadow"> 
    <tr> 
     <td class="toptd" style="color: white; font-size: 24px; text-align: center; height: 40px; 
      background-color: #60b2e7"> 
      View Enquiry 
     </td> 
    </tr> 
    <tr> 
     <td align="center" valign="top" style="padding-top: 10px;"> 
      <table border="0" align="center" width="95%"> 
       <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" OnRowCommand="GridView1_RowCommand" 
        Font-Bold="True" Font-Size="Small" GridLines="None"> 
        <Columns> 
         <asp:BoundField ItemStyle-Width="150px" DataField="enquiryid" HeaderText="ID"> 
          <ItemStyle Width="150px"></ItemStyle> 
         </asp:BoundField> 
         <asp:BoundField ItemStyle-Width="150px" DataField="packname" HeaderText="Package"> 
          <ItemStyle Width="150px"></ItemStyle> 
         </asp:BoundField> 
         <asp:BoundField ItemStyle-Width="150px" DataField="name" HeaderText="Name"> 
          <ItemStyle Width="150px"></ItemStyle> 
         </asp:BoundField> 
         <asp:BoundField ItemStyle-Width="150px" DataField="gender" HeaderText="Gender"> 
          <ItemStyle Width="150px"></ItemStyle> 
         </asp:BoundField> 
         <asp:BoundField ItemStyle-Width="150px" DataField="mobileno" HeaderText="Mobile No"> 
          <ItemStyle Width="150px"></ItemStyle> 
         </asp:BoundField> 
         <asp:BoundField ItemStyle-Width="150px" DataField="email" HeaderText="Email"> 
          <ItemStyle Width="150px"></ItemStyle> 
         </asp:BoundField> 
         <asp:BoundField ItemStyle-Width="150px" DataField="noofdays" HeaderText="No. of Days"> 
          <ItemStyle Width="150px"></ItemStyle> 
         </asp:BoundField> 
         <asp:BoundField ItemStyle-Width="150px" DataField="child" HeaderText="No. of Children"> 
          <ItemStyle Width="150px"></ItemStyle> 
         </asp:BoundField> 
         <asp:BoundField ItemStyle-Width="150px" DataField="adults" HeaderText="No of Adults"> 
          <ItemStyle Width="150px"></ItemStyle> 
         </asp:BoundField> 
         <asp:TemplateField HeaderText="Status Field"> 
          <ItemTemplate> 
           <asp:Button ID="Button1" runat="server" CausesValidation="false" CommandName="MYCOMMAND" 
            CommandArgument='<%#Eval("enquiryid")%>' Text='<%# Bind("statusfield")%>' BorderStyle="None" 
            Font-Bold="True" /> 
          </ItemTemplate> 
         </asp:TemplateField> 
         <asp:TemplateField> 
          <ItemTemplate> 
           <asp:Button ID="Button2" runat="server" CausesValidation="false" BorderStyle="None" 
            OnClick="Generate_bill" Text="Generate Bill" /> 
          </ItemTemplate> 
         </asp:TemplateField> 
         <asp:TemplateField> 
          <ItemTemplate> 
           <asp:Button ID="Button3" runat="server" CausesValidation="false" BorderStyle="None" 
            Text="Delete Enquiry" /> 
          </ItemTemplate> 
         </asp:TemplateField> 
        </Columns> 
       </asp:GridView> 
       <tr> 
        <td> 
         <br /> 
        </td> 
       </tr> 
      </table> 
     </td> 
    </tr> 
</table> 
</form> 

[后端代码]:

protected void Page_Load(object sender, EventArgs e) 
{ 
    if (!IsPostBack) 
    { 
     List<string> lst = new List<string>() { "asd", "xxx" }; 
     GridView1.DataSource = lst; 
     this.BindGrid(); 
    } 
} 
private void BindGrid() 
{ 

    using (SqlConnection con = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=D:\PROJECT SEM6\Online Tours and Travels\App_Data\ToursandTravels.mdf;Integrated Security=True;User Instance=True")) 
    { 

     using (SqlCommand cmd = new SqlCommand("SELECT enquiryid,packname,name, gender,mobileno,email,noofdays,child,adults,statusfield FROM enquiry")) 
     { 
      using (SqlDataAdapter sda = new SqlDataAdapter()) 
      { 
       cmd.Connection = con; 
       sda.SelectCommand = cmd; 
       using (DataTable dt = new DataTable()) 
       { 
        sda.Fill(dt); 
        GridView1.DataSource = dt; 
        GridView1.DataBind(); 
       } 
      } 
     } 
    } 
} 
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e) 
{ 
    if (e.CommandName == "MYCOMMAND") 
    { 
     int enquiryId = Int32.Parse(e.CommandArgument.ToString()); 

     Button Button1 = (Button)e.CommandSource; 
     if (Button1 != null) 
      Button1.Text = "Confirm"; 
     string status = Button1.Text.ToString(); 
     string query = string.Format("UPDATE Enquiry SET statusfield= '{0}' WHERE enquiryid={1}", status, enquiryId); 

     using (SqlConnection con = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=D:\PROJECT SEM6\Online Tours and Travels\App_Data\ToursandTravels.mdf;Integrated Security=True;User Instance=True")) 
     { 
      SqlCommand comm = new SqlCommand(query, con); 
      con.Open(); 
      comm.ExecuteNonQuery(); 
     } 
    } 



} 
protected void Generate_bill(object sender, EventArgs e) 
{ 

    string companyName = "Dream Holidays"; 
    int enquiryid = 1234; 
    SqlConnection con = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=D:\PROJECT SEM6\Online Tours and Travels\App_Data\ToursandTravels.mdf;Integrated Security=True;User Instance=True"); 
    SqlCommand cmd = new SqlCommand("SELECT E.[enquiryid],E.[packname],E.[name],E.[mobileno],E.[email],P.[packageprice] FROM [enquiry] E INNER JOIN package P ON E.[packname]=P.[packname]"); 
    SqlDataAdapter sda = new SqlDataAdapter(); 
    cmd.Connection = con; 
    sda.SelectCommand = cmd; 
    DataTable dt = new DataTable(); 
    sda.Fill(dt); 


    GridView1.DataSource = dt; 


    using (StringWriter sw = new StringWriter()) 
    { 
     using (HtmlTextWriter hw = new HtmlTextWriter(sw)) 
     { 
      StringBuilder sb = new StringBuilder(); 

      //Generate Invoice (Bill) Header. 
      sb.Append("<table width='100%' cellspacing='0' cellpadding='2'>"); 
      sb.Append("<tr><td align='center' style='background-color: #18B5F0' colspan = '2'><b>Invoice</b></td></tr>"); 
      sb.Append("<tr><td colspan = '2'></td></tr>"); 
      sb.Append("<tr><td><b>Enquiry Id: </b>"); 
      sb.Append(enquiryid); 
      sb.Append("</td><td align = 'right'><b>Date: </b>"); 
      sb.Append(DateTime.Now); 
      sb.Append(" </td></tr>"); 
      sb.Append("<tr><td colspan = '2'><b>Company Name: </b>"); 
      sb.Append(companyName); 
      sb.Append("</td></tr>"); 
      sb.Append("</table>"); 
      sb.Append("<br />"); 

      //Generate Invoice (Bill) Items Grid. 
      sb.Append("<table border = '1'>"); 
      sb.Append("<tr>"); 
      foreach (DataColumn column in dt.Columns) 
      { 
       sb.Append("<th style = 'background-color: #D20B0C;color:#ffffff'>"); 
       sb.Append(column.ColumnName); 
       sb.Append("</th>"); 
      } 
      sb.Append("</tr>"); 
      foreach (DataRow row in dt.Rows) 
      { 
       sb.Append("<tr>"); 
       foreach (DataColumn column in dt.Columns) 
       { 
        sb.Append("<td>"); 
        sb.Append(row[column]); 
        sb.Append("</td>"); 
       } 
       sb.Append("</tr>"); 
      } 
      sb.Append("<tr><td align = 'right' colspan = '"); 
      sb.Append(dt.Columns.Count - 1); 
      sb.Append("'>Package Price:</td>"); 
      sb.Append("<td>"); 
      sb.Append(dt.Compute("sum(packageprice)", "")); 
      sb.Append("</td>"); 
      sb.Append("</tr></table>"); 

      //Export HTML String as PDF. 
      StringReader sr = new StringReader(sb.ToString()); 
      Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 10f, 0f); 
      HTMLWorker htmlparser = new HTMLWorker(pdfDoc); 
      PdfWriter writer = PdfWriter.GetInstance(pdfDoc, Response.OutputStream); 
      pdfDoc.Open(); 
      htmlparser.Parse(sr); 
      pdfDoc.Close(); 
      Response.ContentType = "application/pdf"; 
      Response.AddHeader("content-disposition", "attachment;filename=Invoice_" + enquiryid + ".pdf"); 
      Response.Cache.SetCacheability(HttpCacheability.NoCache); 
      Response.Write(pdfDoc); 
      Response.End(); 
     } 
    } 
} 

PDF that I am Downloading looks like this

+0

为什么不选择你想要的SQL语句? – NicoRiff

+0

只有我不知道该怎么做才能帮助我做到这一点? @NicoRiff –

+0

您不应该为GenerateBill按钮使用单独的单击事件。将commandName设置为“GenerateBill”并将CommandArgument设置为enquiryID GenerateBill按钮,并在GridView1_RowCommand事件中使用它们从db中获取单行,并将PDF与数据一起打印出来。 –

回答

0

为GenerateBill按钮,你不应该使用单独的单击事件。将commandName设置为“GenerateBill”并将CommandArgument设置为enquiryID GenerateBill按钮,并在GridView1_RowCommand事件中使用它们从db中获取单行,并将PDF与数据一起打印出来。

更改GenerateBill按钮HTML如下。

<asp:TemplateField> 
    <ItemTemplate> 
     <asp:Button ID="Button2" runat="server" CausesValidation="false" 
      BorderStyle="None" CommandArgument='<%#Eval("enquiryid")%>' 
      CommandName="GenerateBill" Text="Generate Bill" /> 
    </ItemTemplate> 
</asp:TemplateField> 

更改GridView1_RowCommand事件来处理CommandArgument“GenerateBill”。

protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e) 
{ 
    if (e.CommandName == "MYCOMMAND") 
    { 
     //Existing code related to "MYCOMMAND" 
    } 
    //Handle "GenerateBill" command as following. 
    else if(e.CommandName == "GenerateBill") 
    { 
     int enquiryId = Int32.Parse(e.CommandArgument.ToString()); 
     GenerateBill(enquiryId) //Calling generate bill method with enquiryid. 
    } 
} 

变化

protected void Generate_bill(object sender, EventArgs e) 

如下。

protected void GenerateBill(int enquiryId) 
{ 
    string companyName = "Dream Holidays"; 
    SqlConnection con = new SqlConnection(@"Data Source=.\SQLEXPRESS; 
     AttachDbFilename=D:\PROJECT SEM6\Online Tours and Travels\App_Data\ToursandTravels.mdf; 
     Integrated Security=True;User Instance=True"); 

    SqlCommand cmd = new SqlCommand("SELECT E.[enquiryid],E.[packname], 
     E.[name],E.[mobileno],E.[email],P.[packageprice] 
     FROM [enquiry] E INNER JOIN package P ON E.[packname]=P.[packname] 
     WHERE E.[enquiryId] = @enquiryId"); 

    SqlDataAdapter sda = new SqlDataAdapter(); 
    cmd.Connection = con; 
    cmd.Parameters.Add(new SqlParameter("@enquiryId", enquiryId)); 
    sda.SelectCommand = cmd; 
    DataTable dt = new DataTable(); 
    sda.Fill(dt); 

    // Rest of the code of printing PDF 
} 
+0

非常感谢你@Chetan Ranpariya你可以直接告诉我如何添加标题文本以便以pdf格式发票?这是用户定义的 –

+0

我不知道PDF的样子和你想放在哪里的头值。一些更多细节将会有所帮助。 –

+0

https://www.photobox.co.uk/my/photo/full?photo_id=21649752533我标记了我必须提供标题文字的地方@Chetan Ranpariya –

相关问题