输入字符串的格式不正确c#

input string is not in a correct format c#

我想将文本值和组合框值相乘并将其显示在订单价格文本框中 我在 sql 中使用的数据类型是 'float' 所有这些

private void cb_oqty_SelectedIndexChanged(object sender, EventArgs e)
{
    int orderprice;
    int proprice=Convert.ToInt16(txt_oprice.Text);
    int quantity = Convert.ToInt16(cb_oqty.SelectedItem);

    orderprice = proprice * quantity;
    txt_orderprice.Text = Convert.ToString(orderprice);
    txt_orderprice.Update();                                
}

先用int.TryParse看能不能转换文字。该错误似乎指向文本无法转换为 int。

int orderprice = 0;
int proprice = 0;
int quantity = 0;

if (int.TryParse(txt_oprice.Text, out proprice) && int.TryParse(cb_oqty.SelectedValue.ToString(), out quantity))
{
    // It was assigned.
    orderprice = proprice * quantity;
}
else
{
    //Error
}

此外,cb_oqty.SelectedItem 不会转换为 int,因为它是一个对象。您需要使用 SelectedValue。

如果您的 SQL 数据类型是浮点型,您的 C# 数据类型也应该是浮点型:

    private void cb_oqty_SelectedIndexChanged(object sender, EventArgs e)
    {
        var proprice = Convert.ToSingle(txt_oprice.Text);
        var quantity = Convert.ToSingle(cb_oqty.SelectedItem);

        var orderprice = proprice * quantity;
        txt_orderprice.Text = orderprice.ToString();

        // this does not do what you think it does. You can remove this line.
        txt_orderprice.Update();
    }

最好使用 TryParse 方法。