Hello,
I have a big issue. Some time ago I was taught how to build an application for invoice or receipt generation.
Its working, its inserts into database table but the issue is, when I click to add a row in the GridView and I leave the row empty without inputting data, then if I click on submit button I get this error.
Input string was not in a correct format.
amount.Add(Convert.ToDecimal(string.Format("{0:N2}", (Convert.ToDecimal(splitItems[1]) * Convert.ToDecimal(splitItems[2])))));
However, it is supposed to show me an error message that I left a GridView Row empty. Example: Please Provide Data in the Row
HTML (Gridview)
<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="#E5E4E2">
<Columns>
<asp:TemplateField HeaderText="ITEM DESCRIPTION" 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="QUANTITY" ItemStyle-Width="11%">
<ItemTemplate>
<asp:TextBox CssClass="form-control" ID="txtQuantity" Height="25" Font-Size="Small" runat="server" Width="100%" onkeypress="return onlyNumbersWithDot(event);" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="RATE" ItemStyle-Width="19%">
<ItemTemplate>
<span class="currency-symbol" style="font-weight: bolder">NGN</span>
<asp:TextBox ID="txtRate" Height="25" runat="server" Width="80%" onkeypress="return onlyNumbersWithDot(event);" />
</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" />
</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<HeaderStyle Height="10px" />
</asp:GridView>
</ContentTemplate>
</asp:UpdatePanel>
Code
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);
//dr = dt.NewRow();
//Store the DataTable in ViewState
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);
}
//Set Previous Data on Postbacks
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 Button1_Click(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(txtVAT.Text) & !string.IsNullOrEmpty(ftxtaddress.Text) & !string.IsNullOrEmpty(ftxtmail.Text) & !string.IsNullOrEmpty(ftxtphone.Text) & !string.IsNullOrEmpty(txtnat.Text) & !string.IsNullOrEmpty(txtdress.Text) & !string.IsNullOrEmpty(txtmal.Text) & !string.IsNullOrEmpty(txtfon.Text) & !string.IsNullOrEmpty(txtdated.Text))
{
SqlConnection con = new SqlConnection("Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\\Dataregister.mdf;Integrated Security = True");
decimal amount = AmountGet(Session["user"].ToString());
if (amount == 0)
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "Message", "alert('You do no have enough Units');", true);
}
else
{
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++)
{
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)
{
string InvoiceID = Labelinvoice.Text;
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
{
byte[] image;
Stream s = fuUpload.PostedFile.InputStream;
BinaryReader br = new BinaryReader(s);
image = br.ReadBytes((Int32)s.Length);
decimal total = amount.Sum();
decimal grandTotal = total + (total * (Convert.ToDecimal(txtVAT.Text) / 100));
string sqlStatement = "INSERT INTO Table (Uid,email,CreatedBy,Role,fname,faddress,fmail,fphone,Tname,Taddress,Tmail,Tphon,Datdue,Invoice_no,Item,Qty,Rate,Amount,Total,holdtax,stampD,VAT,GrandTotal,CreatedDate,logo) VALUES (@Uid,@email,@CreatedBy,@Role,@fname,@faddress,@fmail,@fphone,@Tname,@Taddress,@Tmail,@Tphon,@Datdue,@Invoice_no,@Item,@Qty,@Rate,@Amount,@Total,@holdtax,@stampD,@VAT,@GrandTotal,@CreatedDate,@logo)";
con.Open();
SqlCommand cmd = new SqlCommand(sqlStatement, con);
cmd.Parameters.AddWithValue("@Uid", labelid.Text.ToString());
cmd.Parameters.AddWithValue("@email", user.Text.ToString());
cmd.Parameters.AddWithValue("@CreatedBy", createby.Text.ToString());
cmd.Parameters.AddWithValue("@Role", role.Text.ToString());
cmd.Parameters.AddWithValue("@fname", ftxtname.Text.ToString());
cmd.Parameters.AddWithValue("@faddress", ftxtaddress.Text.ToString());
cmd.Parameters.AddWithValue("@fmail", ftxtmail.Text.ToString());
cmd.Parameters.AddWithValue("@fphone", ftxtphone.Text.ToString());
cmd.Parameters.AddWithValue("@Tname", txtnat.Text.ToString());
cmd.Parameters.AddWithValue("@Taddress", txtdress.Text.ToString());
cmd.Parameters.AddWithValue("@Tmail", txtmal.Text.ToString());
cmd.Parameters.AddWithValue("@Tphon", txtfon.Text.ToString());
cmd.Parameters.AddWithValue("@Datdue", txtdated.Text.ToString());
cmd.Parameters.AddWithValue("@Invoice_no", Labelinvoice.Text.Trim());
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("@holdtax", Whttxt.Text.ToString());
cmd.Parameters.AddWithValue("@stampD", Sdtxt.Text.ToString());
cmd.Parameters.AddWithValue("@VAT", txtVAT.Text.ToString());
cmd.Parameters.AddWithValue("@GrandTotal", grandTotal);
cmd.Parameters.AddWithValue("@CreatedDate", DateTime.Now);
cmd.Parameters.AddWithValue("@logo", image);
cmd.CommandType = CommandType.Text;
cmd.ExecuteNonQuery();
}
catch (SqlException ex)
{
string msg = "Insert Error:";
msg += ex.Message;
throw new Exception(msg);
}
finally
{
con.Close();
}
Session["InvoiceID"] = InvoiceID;
Response.Redirect("RecordPage.aspx?Id=" + InvoiceID);
}
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)
{
//Remove the Selected Row data
dt.Rows.Remove(dt.Rows[rowID]);
}
}
//Store the current data in ViewState for future reference
ViewState["CurrentTable"] = dt;
//Re bind the GridView for the updated data
Gridview1.DataSource = dt;
Gridview1.DataBind();
}
//Set Previous Data on Postbacks
SetPreviousData();
}