简体   繁体   中英

Input string was not in a correct format. C# SQL

I am putting SQL values inside <td> and this line below it's causing a format error, i don't know if the parsing is incorrect or missing something. Please help

litAccordionFooter.Text += "<td style='width: 12.2%;font-weight: bold;'>" 
    + string.Format("{0:C}", (((ds.Tables[1].Rows[0]["TOTAL_AMT"]))
    == DBNull.Value ? 1 
        : decimal.Parse((ds.Tables[1].Rows[0]["TOTAL_AMT"]).ToString())) 
        / ((int.Parse((ds.Tables[1].Rows[0]["TOTAL_QTY"]).ToString())) == 0 
            || ds.Tables[1].Rows[0]["TOTAL_QTY"] == DBNull.Value ? 1 
                : (int.Parse((ds.Tables[1].Rows[0]["TOTAL_QTY"]).ToString())))) + "</td>";

As @JoãoKleberson says, you should validate they are not null or empty and that they have actually a int and decimal representation

int     total_Amt = default(int);
decimal total_Qty = default(decimal);

if (decimal.TryParse(ds.Tables[1].Rows[0]["TOTAL_AMT"].ToString(), out total_Qty) &&
        int.TryParse(ds.Tables[1].Rows[0]["TOTAL_QTY"].ToString(), out total_Amt))
{
    var myString = "<td style='width: 12.2%;font-weight:bold;'>" +
    string.Format("{0:C}", total_Amt / total_Qty == 0 ? 1 : total_Qty) + "</td>";
}
else
{
    // The TOTAL_AMT and/or TOTAL_QTY values are not valid to convert them, 
    // verify they are not null and that they have the correct format
}

This way you can safety try to convert the values to the desired type, if the can't be converted the flow is going to be to the else clause

Make sure this statement:

(ds.Tables [1] .Rows [0] ["TOTAL_AMT"])
(ds.Tables [1] .Rows [0] ["TOTAL_QTY"])

It is not null or empty

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