Please refer below sample.
HTML
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/css/all.min.css" integrity="sha512-iBBXm8fW90+nuLcSKlbmrPcLa0OT92xO1BIsZ+ywDWZCvqsWgccV3gFoRBv0z+8dLJgyAHIhR35VZc2oM/gI1w==" crossorigin="anonymous" referrerpolicy="no-referrer" />
<link rel="stylesheet" href="https://pro.fontawesome.com/releases/v5.10.0/css/all.css" intergrity="sha384-AYmEC3Yw5cVb3ZcuHt0A9w35dYTsvhLPVnYs9eStHfGJv0vKxVfELGroGkvsg+p" crossorigin="anonymous" />
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" />
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/css/bootstrap.min.css" integrity="sha384-TX8t27EcRE3e/ihU7zmQxVncDAy5uIKz4rEkgIXeMed4M0jlfIDPvg6uqKI2xXr2" crossorigin="anonymous" />
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css" integrity="sha384-9gVQ4dYFwwWSjIDZnLEWnxCjeSWFphJiwGPXr1jddIhOegiu1FwO5qRGvFXOdJZ4" crossorigin="anonymous" />
<script defer src="https://use.fontawesome.com/releases/v5.0.13/js/fontawesome.js" integrity="sha384-6OIrr52G08NpOFSZdxxz1xdNSndlD4vdcf/q2myIUVO0VsqaGHJsB0RaBE01VTOY" crossorigin="anonymous"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/malihu-custom-scrollbar-plugin/3.1.5/jquery.mCustomScrollbar.min.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy" crossorigin="anonymous"></script>
<link href='https://fonts.googleapis.com/css?family=Nunito' rel='stylesheet' />
<link href="https://fonts.googleapis.com/css2?family=Roboto&display=swap" rel="stylesheet" />
<link href="http://fonts.cdnfonts.com/css/renogare" rel="stylesheet" />
<title></title>
<style>
.parent {
margin-left: auto;
margin-right: auto;
padding: 10px;
display: flex;
background-color: #ffffff;
border: 1px solid #ccc;
width: 90%;
}
.child {
width: 100%;
height: auto;
padding: .5rem;
}
.container {
width: 100%;
padding: .5rem;
margin: 0px;
}
.company-address {
border: 0px solid #ccc;
float: left;
width: 240pt;
font-size:smaller;
font-family:Nunito;
}
.invoice-details {
border: 0px solid #ccc;
float: right;
width: 240px;
margin-right: 10px;
}
.heading {
font-size:larger;
font-weight:bolder;
position: center;
margin-top: 0%;
}
.total{
float: right;
width: 250px;
font-size: small;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="script" runat="server"></asp:ScriptManager>
<div>
<br />
<div class="parent">
<div class="child" id="midcont" style="width: 100%;">
<div style="height: auto;">
<div class="heading" style="text-align: right;">
<asp:Label ID="Label4" runat="server" Font-Size="X-Large" Font-Names="Be Vietnam" ForeColor="#145c7c" Text="RECEIPT"></asp:Label>
</div>
</div>
<hr style="margin-top: 0%;" />
<br />
<asp:UpdatePanel ID="panel" runat="server">
<ContentTemplate>
<asp:GridView ID="Gridview1" runat="server" Font-Size="x-Small" ShowFooter="True" AutoGenerateColumns="False" OnRowCreated="Gridview1_RowCreated"
class="table table-striped table-condensed table-bordered" Style="max-width: 100%" HeaderStyle-ForeColor="#00003D" Height="50px" HeaderStyle-Height="10px" HeaderStyle-BackColor="#D3D9E5">
<Columns>
<asp:TemplateField HeaderText="ITEMS" ItemStyle-Width="47%">
<ItemTemplate>
<asp:TextBox ID="textBox1" runat="server" Class="form-control" Width="100%" Font-Size="Small" TextMode="MultiLine" Style="overflow: hidden; resize: none;" oninput="Resize(this)" />
<script type="text/javascript">
function Resize(textbox) {
textbox.style.height = "";
textbox.style.height = Math.min(textbox.scrollHeight, 300) + "px";
}
</script>
</ItemTemplate>
<FooterStyle HorizontalAlign="Left" />
<FooterTemplate>
<asp:Button ID="ButtonAdd" runat="server" Class="btn btn-primary" BackColor="#32657c" Font-Size="Small" Text="+ Item" OnClick="ButtonAdd_Click" />
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="QTY" ItemStyle-Width="11%">
<ItemTemplate>
<asp:TextBox CssClass="form-control" ID="txtQuantity" Height="25" Font-Size="Small" runat="server" Width="100%" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="PRICE" ItemStyle-Width="19%">
<ItemTemplate>
<span class="currency-symbol" style="font-weight: bolder">NGN</span>
<asp:TextBox ID="txtRate" Height="25" runat="server" Width="80%" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="AMOUNT" ItemStyle-Width="17%">
<ItemTemplate>
<span class="currency-symbol" style="font-weight: bolder">NGN</span>
<asp:Label ID="lblAmount" runat="server" Text="" Font-Bold="True"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="LinkButton1" ForeColor="Red" runat="server" OnClick="LinkButton1_Click">
<%--<asp:Image ID="Image1" runat="server" ImageUrl="~/images/del6.png" Height="25" />--%>Insert
</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<HeaderStyle Height="10px" />
</asp:GridView>
<hr />
<div class="total">
<asp:Label ID="Label1" runat="server" Font-Bold="true" Text="SUB TOTAL"></asp:Label>
<asp:Label ID="lblTotal" runat="server" Text=""></asp:Label>
<br />
<br />
<div class="row">
<asp:Label ID="Label5" runat="server" Font-Bold="true" Text="VAT:"></asp:Label>
<asp:TextBox ID="txtVAT" runat="server" CssClass="form-control" Width="120px" Font-Bold="true" Height="22px" Font-Size="8pt" placeholder="Value Added Tax" />
<asp:Label ID="warnlbl" runat="server" ForeColor="Red" Font-Size="Small" Font-Bold="true" Text=""></asp:Label>
</div>
<br />
<asp:Label ID="Label6" runat="server" Font-Bold="true" Text="GRAND TOTAL:"></asp:Label>
<asp:Label ID="lblGrandTotal" runat="server" Text=""></asp:Label>
<br />
<br />
<br />
<br />
</div>
<div class="dsign">
<canvas id="colors_sketch" width="300" height="100" style="border: 1px solid #ccc"></canvas>
<div class="tools">
<a href="#colors_sketch" data-tool="marker">Sign</a> <a href="#colors_sketch" data-tool="eraser">Erase</a>
</div>
<script src="https://cdn.rawgit.com/mobomo/sketch.js/master/lib/sketch.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(function () {
$('#colors_sketch').sketch();
$(".tools a").eq(0).attr("style", "color:#000");
$(".tools a").click(function () {
$(".tools a").removeAttr("style");
$(this).attr("style", "color:#000");
});
});
</script>
</div>
</ContentTemplate>
</asp:UpdatePanel>
<br />
<hr />
<label style="font-size: 9pt; font-weight: 700;">By signing this document, the customer agrees to the services and conditions described in this documemt.</label>
</div>
</div>
<br />
</div>
<asp:Button Text="Save" runat="server" OnClick="Button1_Click" />
</form>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.0/umd/popper.min.js" integrity="sha384-cs/chFZiN24E4KMATLdqdvsezGxaGsi4hLGOzlXwp5UZB1LY//20VyM2taTB4QvJ" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js" integrity="sha384-uefMccjFJAIv6A+rW+L4AHf99KvxDjWSu1z9VI8SKNVmz4sk7buKt/6v9KI65qnm" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/malihu-custom-scrollbar-plugin/3.1.5/jquery.mCustomScrollbar.concat.min.js"></script>
<script type="text/javascript">
$(function () {
CalculateTotal();
});
$("body").on("change keyup", "[id*=txtQuantity],[id*=txtRate]", function () {
var row = $(this).closest("tr");
//Check whether Quantity value is valid Float number.
var quantity = parseFloat($.trim($(row).find("[id*=txtQuantity]").val()));
if (isNaN(quantity)) {
quantity = 0;
}
var rate = parseFloat($.trim($(row).find("[id*=txtRate]").val()));
if (isNaN(rate)) {
rate = 0;
}
//Calculate and update Row Total.
$("[id*=lblAmount]", row).html(numberWithCommas(parseFloat(quantity * rate).toFixed(2)));
CalculateTotal();
});
function numberWithCommas(x) {
return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
$("body").on("change keyup", "[id*=txtVAT],[id*=Whttxt],[id*=Sdtxt]", function () {
CalculateTotal()
});
function CalculateTotal() {
//Calculate and update Grand Total.
var grandTotal = 0;
$("[id*=lblAmount]").each(function () {
var amount = 0;
if (!isNaN($(this).html().replace(/,/g, "")) && $(this).html().replace(/,/g, "") != "") {
amount = $(this).html().replace(/,/g, "");
}
grandTotal = grandTotal + parseFloat(amount);
});
$("[id*=lblTotal]").html(numberWithCommas(parseFloat(grandTotal).toFixed(2)));
var wht = $("[id*=Whttxt]").val() == "" || $("[id*=Whttxt]").val() == undefined ? "0" : parseInt($("[id*=Whttxt]").val()) / 100;
var std = $("[id*=Sdtxt]").val() == "" || $("[id*=Sdtxt]").val() == undefined ? "0" : parseInt($("[id*=Sdtxt]").val()) / 100;
var vat = $("[id*=txtVAT]").val() == "" || $("[id*=txtVAT]").val() == undefined ? "0" : parseInt($("[id*=txtVAT]").val()) / 100;
grandTotal = grandTotal + (grandTotal * vat) + (grandTotal * wht) + (grandTotal * std);
$("[id*=lblGrandTotal]").html(numberWithCommas(parseFloat(grandTotal).toFixed(2)));
}
</script>
</body>
</html>
Code
SqlCommand cmd = new SqlCommand();
SqlCommand cmd2 = new SqlCommand();
SqlDataAdapter sda = new SqlDataAdapter();
DataSet ds = new DataSet();
DataTable dt = new DataTable();
SqlConnection con = new SqlConnection("Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\\Dataregister.mdf;Integrated Security=True");
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
SetInitialRow();
}
}
private void SetInitialRow()
{
DataTable dt = new DataTable();
DataRow dr = null;
dt.Columns.Add(new DataColumn("RowNumber", typeof(string)));
dt.Columns.Add(new DataColumn("Column1", typeof(string)));
dt.Columns.Add(new DataColumn("Column2", typeof(string)));
dt.Columns.Add(new DataColumn("Column3", typeof(string)));
dt.Columns.Add(new DataColumn("Total", typeof(string)));
dr = dt.NewRow();
dr["RowNumber"] = 1;
dr["Column1"] = string.Empty;
dr["Column2"] = string.Empty;
dr["Column3"] = string.Empty;
dr["Total"] = string.Empty;
dt.Rows.Add(dr);
ViewState["CurrentTable"] = dt;
Gridview1.DataSource = dt;
Gridview1.DataBind();
}
private void AddNewRowToGrid()
{
int rowIndex = 0;
if (ViewState["CurrentTable"] != null)
{
DataTable dtCurrentTable = (DataTable)ViewState["CurrentTable"];
DataRow drCurrentRow = null;
if (dtCurrentTable.Rows.Count > 0)
{
for (int i = 1; i <= dtCurrentTable.Rows.Count; i++)
{
//extract the TextBox values
TextBox box1 = (TextBox)Gridview1.Rows[rowIndex].Cells[1].FindControl("TextBox1");
TextBox box2 = (TextBox)Gridview1.Rows[rowIndex].Cells[2].FindControl("txtQuantity");
TextBox box3 = (TextBox)Gridview1.Rows[rowIndex].Cells[3].FindControl("txtRate");
Label lblTtotal = (Label)Gridview1.Rows[rowIndex].Cells[4].FindControl("lblAmount");
drCurrentRow = dtCurrentTable.NewRow();
drCurrentRow["RowNumber"] = i + 1;
drCurrentRow["Column1"] = box1.Text;
drCurrentRow["Column2"] = box2.Text;
drCurrentRow["Column3"] = box3.Text;
drCurrentRow["Total"] = string.Format("{0:#,0.00}", (Convert.ToDecimal(box2.Text) * Convert.ToDecimal(box3.Text)));
rowIndex++;
}
dtCurrentTable.Rows.Add(drCurrentRow);
ViewState["CurrentTable"] = dtCurrentTable;
Gridview1.DataSource = dtCurrentTable;
Gridview1.DataBind();
}
}
else
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "Message", "alert('Empty Invoice Data');", true);
}
SetPreviousData();
}
private void SetPreviousData()
{
int rowIndex = 0;
if (ViewState["CurrentTable"] != null)
{
DataTable dt = (DataTable)ViewState["CurrentTable"];
if (dt.Rows.Count > 0)
{
for (int i = 1; i < dt.Rows.Count; i++)
{
TextBox box1 = (TextBox)Gridview1.Rows[rowIndex].Cells[1].FindControl("TextBox1");
TextBox box2 = (TextBox)Gridview1.Rows[rowIndex].Cells[2].FindControl("txtQuantity");
TextBox box3 = (TextBox)Gridview1.Rows[rowIndex].Cells[3].FindControl("txtRate");
Label lblTtotal = (Label)Gridview1.Rows[rowIndex].Cells[4].FindControl("lblAmount");
box1.Text = dt.Rows[i]["Column1"].ToString();
box2.Text = dt.Rows[i]["Column2"].ToString();
box3.Text = dt.Rows[i]["Column3"].ToString();
lblTtotal.Text = dt.Rows[i]["Total"].ToString();
rowIndex++;
}
}
ViewState["CurrentTable"] = dt;
}
}
protected void ButtonAdd_Click(object sender, EventArgs e)
{
AddNewRowToGrid();
}
protected void Gridview1_RowCreated(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
DataTable dt = (DataTable)ViewState["CurrentTable"];
LinkButton lb = (LinkButton)e.Row.FindControl("LinkButton1");
if (lb != null)
{
if (dt.Rows.Count > 1)
{
if (e.Row.RowIndex == dt.Rows.Count - 1)
{
lb.Visible = false;
}
}
else
{
lb.Visible = false;
}
}
}
}
protected void LinkButton1_Click(object sender, EventArgs e)
{
LinkButton lb = (LinkButton)sender;
GridViewRow gvRow = (GridViewRow)lb.NamingContainer;
int rowID = gvRow.RowIndex + 1;
if (ViewState["CurrentTable"] != null)
{
DataTable dt = (DataTable)ViewState["CurrentTable"];
if (dt.Rows.Count > 1)
{
if (gvRow.RowIndex < dt.Rows.Count - 1)
{
dt.Rows.Remove(dt.Rows[rowID]);
}
}
ViewState["CurrentTable"] = dt;
Gridview1.DataSource = dt;
Gridview1.DataBind();
}
SetPreviousData();
}
protected void Button1_Click(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(txtVAT.Text))
{
int rowIndex = 0;
StringCollection sc = new StringCollection();
if (ViewState["CurrentTable"] != null)
{
DataTable dtCurrentTable = (DataTable)ViewState["CurrentTable"];
if (dtCurrentTable.Rows.Count > 0)
{
for (int i = 1; i <= dtCurrentTable.Rows.Count; i++)
{
//extract the TextBox values
TextBox box1 = (TextBox)Gridview1.Rows[rowIndex].Cells[1].FindControl("TextBox1");
TextBox box2 = (TextBox)Gridview1.Rows[rowIndex].Cells[2].FindControl("txtQuantity");
TextBox box3 = (TextBox)Gridview1.Rows[rowIndex].Cells[3].FindControl("txtRate");
Label total = (Label)Gridview1.Rows[rowIndex].Cells[4].FindControl("lblAmount");
sc.Add(box1.Text + "," + box2.Text + "," + box3.Text + "," + total.Text);
rowIndex++;
}
InsertRecords(sc);
}
}
}
else
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "Message", "alert('All Fields are Required!');", true);
warnlbl.Visible = true;
warnlbl.Text = "**";
warnlbl.ForeColor = System.Drawing.Color.Red;
}
}
private void InsertRecords(StringCollection sc)
{
StringBuilder sb = new StringBuilder(string.Empty);
string[] splitItems = null;
List<string> item = new List<string>();
List<string> quantity = new List<string>();
List<string> rate = new List<string>();
List<decimal> amount = new List<decimal>();
foreach (string Item in sc)
{
if (Item.Contains(","))
{
splitItems = Item.Split(",".ToCharArray());
item.Add(splitItems[0]);
quantity.Add(splitItems[1]);
rate.Add(splitItems[2]);
amount.Add(Convert.ToDecimal(string.Format("{0:N2}", (Convert.ToDecimal(splitItems[1]) * Convert.ToDecimal(splitItems[2])))));
}
}
SqlConnection con = new SqlConnection("Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\\Dataregister.mdf;Integrated Security=True");
try
{
decimal total = amount.Sum();
decimal grandTotal = total + (total * (Convert.ToDecimal(txtVAT.Text) / 100));
string sqlStatement = "INSERT INTO receipt (Item,Qty,Rate,Amount,Total,VAT,GrandTotal,CreatedDate) " +
"VALUES (@Item,@Qty,@Rate,@Amount,@Total,@VAT,@GrandTotal,@CreatedDate)";
con.Open();
SqlCommand cmd = new SqlCommand(sqlStatement, con);
cmd.Parameters.AddWithValue("@Item", string.Join(",", item.ToArray()));
cmd.Parameters.AddWithValue("@Qty", string.Join(",", quantity.ToArray()));
cmd.Parameters.AddWithValue("@Rate", string.Join(",", rate.ToArray()));
cmd.Parameters.AddWithValue("@Amount", string.Join(",", amount.ToArray()));
cmd.Parameters.AddWithValue("@Total", total);
cmd.Parameters.AddWithValue("@VAT", txtVAT.Text.ToString());
cmd.Parameters.AddWithValue("@GrandTotal", grandTotal);
cmd.Parameters.AddWithValue("@CreatedDate", DateTime.Now);
cmd.CommandType = CommandType.Text;
cmd.ExecuteNonQuery();
}
catch (SqlException ex)
{
string msg = "Insert Error:";
msg += ex.Message;
throw new Exception(msg);
}
finally
{
con.Close();
}
}
Screenshot
Output