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

时间:2016-03-08 10:34:03

标签: c# sql types textbox int

我想将文本值和组合框值相乘,并将其显示在orderprice文本框中 我在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();                                
}

2 个答案:

答案 0 :(得分:1)

使用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,因为它是一个Object。你需要使用SelectedValue。

答案 1 :(得分:0)

如果您的SQL数据类型是float,那么您的C#数据类型也应该是float:

    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方法。