I have a gridview where I input figures for receipt creation. The gridview is made up of 5 columns - Items, Quantity, Rate, Amount and Action. I also have some Textboxes where other data are inputted, the value in the last row of the Amount column returns back to it's oiginal position, it does not remain. For example, if the Amount last row, has 40 as its value, and I click on button, the value will return to "ZERO")
How do I make the value in the last row of the Amount column remain and not change even after page loads on button click?
I just copied the code and send. If you can, just copy the whole HTML and paste. Then input values just in the gridview alone. After you finish with the first row, add new row by clicking on "Add another item", then input values in the second row too. When you're done, click on the "Create Invoice" button, after the page refreshes, you will see that the last value in the Amount column returns to 0.00
<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>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="css/bootstrap.min.css" rel="stylesheet" media="all" />
<link href="css/bootstrap.css" rel="stylesheet" media="all" />
<link href="css/style2.css" rel="stylesheet" />
<title></title>
</head>
<body style="background-color: #fdfdfd; font-family: 'Graphik', sans-serif; font-size: 17px; font-weight: 400;">
<form id="form1" runat="server">
<asp:ScriptManager ID="script" runat="server"></asp:ScriptManager>
<div class="wrapper">
<div id="content" style="font-size: 10pt; width: 100%;">
<div class="line"></div>
<div class="grids">
<div class="container" id="center-content" style="margin: 0 auto; padding: 6px;">
<div class="form-horizontal">
<div class="parent col-sm-11" style="margin-left: auto; margin-right: auto; padding: 6px; display: flex; background-color: #ffffff; width: 100%; height: auto;">
<div class="child" id="midcont2" style="width: 100%; height: auto; border: none;">
<div class="grid-corner" style="width: 100%; background-color: white; margin: 0 auto; padding: 5px;">
<asp:UpdatePanel ID="panelcurrency" runat="server" Font-Size="9pt" UpdateMode="Conditional">
<ContentTemplate>
<div style="margin-bottom: 0.5%; padding: 10px;">
<asp:Label ID="Label7" runat="server" Font-Size="10pt" Text="# "></asp:Label><asp:Label ID="Labelinvoice" runat="server" Font-Size="10pt" Text=""></asp:Label>
<div class="">
<br />
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label runat="server" id="Label23">Due date</label>
<div class="input-group">
<asp:TextBox ID="txtdated" runat="server" CssClass="form-control" type="date" BorderStyle="Solid" BorderWidth="1"></asp:TextBox>
</div>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label runat="server" id="Label22">Select preferrd currency</label>
<div class="input-group">
<asp:DropDownList ID="CurrencyDropDown" runat="server" CssClass="form-control" AutoPostBack="true" OnSelectedIndexChanged="CurrencyDropDown_SelectedIndexChanged">
</asp:DropDownList>
</div>
</div>
</div>
</div>
<br />
</div>
<br />
</div>
<asp:Label ID="securelbl" runat="server" Visible="false" ForeColor="#40576d" Text="8"></asp:Label>
<asp:GridView ID="Gridview1" runat="server" Font-Size="10pt" HeaderStyle-Font-Size="10pt" CellPadding="5" GridLines="None" ShowFooter="True" AutoGenerateColumns="False" HeaderStyle-Font-Bold="false"
Style="width: 100%" FooterStyle-BackColor="#fdfdfd" HeaderStyle-ForeColor="#000000" Height="50px" HeaderStyle-Height="10px">
<Columns>
<asp:TemplateField HeaderText="Description" ItemStyle-Width="45%" HeaderStyle-Font-Bold="false">
<ItemTemplate>
<asp:TextBox ID="textBox1" runat="server" Class="form-control" Width="100%" TextMode="MultiLine" Font-Size="10pt" Style="overflow: hidden; text-transform: capitalize; 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" VerticalAlign="Bottom" />
<FooterTemplate>
<asp:LinkButton ID="LinkButton2" runat="server" Font-Size="10pt" ForeColor="#145c7c" OnCommand="ButtonAdd_Command">Add another item</asp:LinkButton>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Quantity" ItemStyle-Width="15%" HeaderStyle-Font-Bold="false">
<ItemTemplate>
<asp:TextBox CssClass="form-control" ID="txtQuantity" Font-Size="10pt" runat="server" Width="100%" onkeypress="return onlyNumbersWithDot(event);" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Unit price" ItemStyle-Width="20%" HeaderStyle-Font-Bold="false">
<ItemTemplate>
<asp:Label class="currency-symbol" runat="server" ID="symbolA" Style="font-weight: 400;"></asp:Label>
<asp:TextBox ID="txtRate" runat="server" Font-Size="10pt" Width="90%" CssClass="form-control" placeholder="0.00" onkeypress="return onlyNumbersWithDot(event);" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Amount" ItemStyle-Width="50%" HeaderStyle-Font-Bold="false">
<ItemTemplate>
<asp:Label class="currency-symbol" runat="server" ID="symbolB" Style="font-weight: 400;"></asp:Label>
<asp:Label ID="lblAmount" runat="server" Text="0.00" Font-Size="10pt"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="LinkButton1" ForeColor="Red" runat="server" OnClick="LinkButton1_Click">
<i class="fad fa-trash" aria-hidden="true" style="margin: 0 7px; font-size: 1.4rem; color: #0b2436;"></i>
</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<HeaderStyle Height="10px" />
</asp:GridView>
<hr />
<div runat="server" style="width: 100%; margin: 0 auto; font-weight: 500; margin-bottom: 1%;">
<div class="total" style="margin-right: 0%; padding: 6px;">
<div class="row">
<div class="col-md-6"></div>
<div class="col-md-6">
<div class="form-group">
<asp:Label ID="Label1" runat="server" Font-Size="10pt" Text="Subtotal"></asp:Label>
<asp:Label ID="warnlbl" runat="server" Font-Size="6pt"></asp:Label>
<div class="input-group">
<asp:Label ID="currency" class="currency-symbol" runat="server" Text=""></asp:Label>
<asp:Label ID="lblTotal" runat="server" Font-Size="10pt" Text=""></asp:Label>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-6"></div>
<div class="col-md-6">
<div class="form-group">
<asp:Label ID="Label9" runat="server" Text="Add Vat"></asp:Label>
<label class="optional">(optional)</label>
<div class="input-group">
<div class="input-group-append">
<span class="input-group-text" style="color: #2d6193; border: none; background-color: #fff; border: 0.5px solid #ccc; border-radius: 3px; border-top-right-radius: unset; border-bottom-right-radius: unset;">
<span>%</span>
</span>
</div>
<asp:TextBox ID="txtVAT" runat="server" CssClass="form-control" Width="100px" Text="" Font-Size="9pt" onkeypress="return onlyNumbersWithDot(event);" />
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-6"></div>
<div class="col-md-6">
<div class="form-group">
<asp:Label ID="Label2" runat="server" Text="Withholding tax"></asp:Label>
<label class="optional">(optional)</label>
<div class="input-group">
<div class="input-group-append">
<span class="input-group-text" style="color: #2d6193; border: none; background: #fff; border: 0.5px solid #ccc; border-radius: 4px; border-top-right-radius: unset; border-bottom-right-radius: unset;">
<span>%</span>
</span>
</div>
<asp:TextBox ID="Whttxt" runat="server" CssClass="form-control" Width="100px" Text="" Font-Size="9pt" onkeypress="return onlyNumbersWithDot(event);" />
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-6"></div>
<div class="col-md-6">
<div class="form-group">
<asp:Label ID="Label4" runat="server" Text="Stamp Duty"></asp:Label>
<label class="optional">(optional)</label>
<div class="input-group">
<div class="input-group-append">
<span class="input-group-text" style="color: #2d6193; border: none; background-color: #fff; border: 0.5px solid #ccc; border-radius: 3px; border-top-right-radius: unset; border-bottom-right-radius: unset;">
<span>%</span>
</span>
</div>
<asp:TextBox ID="Sdtxt" runat="server" CssClass="form-control" Width="100px" Text="" Font-Size="9pt" onkeypress="return onlyNumbersWithDot(event);" />
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-6"></div>
<div class="col-md-6">
<div class="form-group">
<asp:Label ID="Label25" runat="server" Font-Size="11pt" Text="Total"></asp:Label>
<div class="input-group">
<asp:Label class="currency-symbol" ID="curcy" runat="server" Text=""></asp:Label>
<asp:Label ID="lblGrandTotal" Font-Size="11pt" runat="server" Text=""></asp:Label>
</div>
</div>
</div>
</div>
</div>
</div>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="CurrencyDropDown" EventName="SelectedIndexChanged" />
</Triggers>
</asp:UpdatePanel>
</div>
</div>
</div>
<br />
<div class="col-sm-11" style="margin-left: auto; margin-right: auto; padding: 6px; display: flex; width: 100%; height: auto;">
<asp:Button ID="Button1" runat="server" CssClass="btn btn-primary" Font-Size="10pt" BackColor="#32657c" Text="Create invoice" />
</div>
<br />
</div>
</div>
</div>
</div>
</div>
</form>
</body>
</html>
ViewState is being used in the below code.
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
AutoGenerateNumber();
GetCurrency();
}
if (!Page.IsPostBack)
{
SetInitialRow();
}
}
private string GetAutoNumber()
{
string numbers = "1234567890";
string characters = numbers;
int length = 9;
string id = string.Empty;
for (int i = 0; i < length; i++)
{
string character = string.Empty;
do
{
int index = new Random().Next(0, characters.Length);
character = characters.ToCharArray()[index].ToString();
} while (id.IndexOf(character) != -1);
id += character;
//label.Text = "ID" + id;
}
return id;
}
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++)
{
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, GetType(), "Message", "alert('Empty Data');", true);
}
SetPreviousData();
}
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();
}
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_Command(Object sender, CommandEventArgs e)
{
AddNewRowToGrid();
}
private void GetCurrency()
{
using (SqlConnection con = new SqlConnection())
{
con.ConnectionString = ConfigurationManager.ConnectionStrings["ConString"].ConnectionString;
using (SqlCommand cmd = new SqlCommand("SELECT Currency FROM countrycurrency", con))
{
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
con.Open();
CurrencyDropDown.DataSource = cmd.ExecuteReader();
CurrencyDropDown.DataTextField = "Currency";
CurrencyDropDown.DataValueField = "Currency";
CurrencyDropDown.DataBind();
con.Close();
CurrencyDropDown.Items.Insert(0, new ListItem("Select currency", " "));
CurrencyDropDown.Items[0].Selected = true;
CurrencyDropDown.Items[0].Attributes["disabled"] = "disabled";
}
}
}
protected void CurrencyDropDown_SelectedIndexChanged(object sender, EventArgs e)
{
CurrencyDropDown.SelectedItem.Text = CurrencyDropDown.SelectedItem.Text.ToString();
currency.Text = CurrencyDropDown.SelectedItem.Value.ToString();
curcy.Text = CurrencyDropDown.SelectedItem.Value.ToString();
foreach (GridViewRow row in Gridview1.Rows)
{
if (row.RowType == DataControlRowType.DataRow)
{
Label lbl2 = (Label)row.FindControl("symbolB");
lbl2.Text = CurrencyDropDown.SelectedItem.Value.ToString();
}
}
}
private void AutoGenerateNumber()
{
try
{
using (SqlConnection con = new SqlConnection())
{
con.ConnectionString = ConfigurationManager.ConnectionStrings["ConString"].ConnectionString;
SqlDataReader dr;
using (SqlCommand cmd = new SqlCommand())
{
cmd.Parameters.Clear();
cmd.CommandText = "SELECT Invoice_no FROM InvoiceTable WHERE Invoice_no=@Invoice_no";
cmd.Parameters.AddWithValue("@Invoice_no", Labelinvoice.Text);
cmd.Connection = con;
con.Open();
dr = cmd.ExecuteReader();
}
if (dr.HasRows)
{
}
else
{
List<string> result = new List<string>();
if (Session["Numbers"] != null)
{
result = (List<string>)Session["Numbers"];
}
string number = GetAutoNumber();
if (!result.Contains(number))
{
result.Add(number);
Session["Numbers"] = result;
Labelinvoice.Text = number;
}
}
}
}
catch (SqlException ex)
{
string msg = "Error:";
msg += ex.Message;
throw new Exception(msg);
}
}
protected void Button1_Click(object sender, EventArgs e)
{
}