如何从数据库中检索一行并将其显示在账单中,该账单以 asp.net 的形式.pdf



嗨,我正在做一个项目,其中我在网格视图中有一个名为"生成账单"的按钮,单击"生成账单"按钮时,我可以下载.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 SEM6Online Tours and TravelsApp_DataToursandTravels.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 SEM6Online Tours and TravelsApp_DataToursandTravels.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 SEM6Online Tours and TravelsApp_DataToursandTravels.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 如下所示

您不应为"生成账单"按钮使用单独的单击事件。将命令名称设置为"GenerateBill",将 CommandArgument 设置为 GenerateBill 按钮的查询 ID,并在事件中使用它们GridView1_RowCommand从数据库中获取单行并打印包含数据的 pdf。

更改"生成账单"按钮 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 SEM6Online Tours and TravelsApp_DataToursandTravels.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
}

最新更新