[Solved] int.Parse Error: Input string was not in a correct format in ASP.Net

akhter
 
on Aug 09, 2020 11:52 PM
1284 Views

I am facing below error Input string was not in a correct format some time on form.

Button behine coding 

        protected void btnSave_Click(object sender, EventArgs e)
        {
            if (txtOrder.Text == "")
            {
                lblMessage.Text = "Please Input Ref NO";
            }

            else if (GVbal.Rows.Count == 0)
            {
                lblMessage.Text = "Please insert Pack";
            }
            else
            {
                btnSave.Visible = false;

                using (SqlCommand cmd = new SqlCommand("[Sp_ints_Dispatch_SBM]", con))
                {
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.Parameters.AddWithValue("@Orderno", txtOrder.Text);
                    cmd.Parameters.AddWithValue("@remarks", txtrmk.Text);
                    cmd.Parameters.AddWithValue("@Date", txtEntrydate.Text);
                    cmd.Parameters.AddWithValue("@IPAddress", lblIP.Text);
                    cmd.Parameters.AddWithValue("@ETime", DateTime.Now.ToString("HH:mm:ss"));
                    con.Open();
                    ID = Convert.ToInt32(cmd.ExecuteScalar());
                    con.Close();

                    DataTable dt = (DataTable)ViewState["dt"];
                    int pid, ptype;

                    foreach (DataRow row in dt.Rows)
                    {
                        pid = int.Parse(row["PID"].ToString());
                        ptype = int.Parse(row["PType"].ToString());
                        this.InsertRows(pid, ptype);
                    }
                }
            }
        }
Download FREE API for Word, Excel and PDF in ASP.Net: Download
dharmendr
 
on Aug 10, 2020 11:58 PM
akhter says:
int pid, ptype;
 
                  foreach (DataRow row in dt.Rows)
                  {
 
                      pid = int.Parse(row["PID"].ToString());
                      ptype = int.Parse(row["PType"].ToString());
                      this.InsertRows(pid, ptype);
                  }

Replace above with below code.

int pid, ptype;
foreach (DataRow row in dt.Rows)
{
    if (!int.TryParse(row["PID"].ToString(), out pid))
    {
        pid = 0;
    }
    if (!int.TryParse(row["PType"].ToString(), out ptype))
    {
        ptype = 0;
    }
    this.InsertRows(pid, ptype);
}