简体   繁体   中英

ASP.NET - Input string was not in a correct format

I am getting an error saying my input string was not in a correct format when I try to get, multiply and display I stored data's in cookies. It says there was an error in a part in total = total + (Convert.ToInt32(a[2].ToString()) * Convert.ToInt32(a[3].ToString())); Somebody help me please. Here is my code:

protected void Page_Init(object sender, EventArgs e)
{
    DataTable dt = new DataTable();
    dt.Columns.AddRange(new DataColumn[7] { new DataColumn("product_name"), new DataColumn("product_desc"), new DataColumn("product_price"), new DataColumn("product_qty"), new DataColumn("product_images"), new DataColumn("id"), new DataColumn("product_id") });

    if (Request.Cookies["aa"] != null)
    {
        s = Convert.ToString(Request.Cookies["aa"].Value);

        string[] strArr = s.Split('|');

        for (int i = 0; i < strArr.Length; i++)
        {
            t = Convert.ToString(strArr[i].ToString());
            string[] strArr1 = t.Split(',');

            for (int j = 0; j < strArr1.Length; j++)
            {
                a[j] = strArr1[j].ToString();
            }`enter code here`
            dt.Rows.Add(a[0].ToString(), a[1].ToString(), a[2].ToString(), a[3].ToString(), a[4].ToString(), i.ToString(), a[5].ToString());



            total = total + (Convert.ToInt32(a[2].ToString()) * Convert.ToInt32(a[3].ToString()));
            totalcount = totalcount + 1;

            cart_items.Text = totalcount.ToString();
            cart_price.Text = total.ToString();
        }
    }

I recomment you to use int.TryParse(...) if you want to convert form string. It could be like this:

int var2, var3 = 0;
if(int.TryParse(a[2].ToString(), out var2) 
 && int.TryParse(a[3].ToString(), out var3))
{
     total += (var2 * var3);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM