简体   繁体   English

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

[英]input string is not in a correct format c#

I want to multiply the text value and combo box value and display it in a orderprice textbox the data types that I use in sql are 'float' for all of these 我想将文本值和组合框值相乘,并在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();                                
}

Use int.TryParse to see if the text can be converted first. 使用int.TryParse查看是否可以首先转换文本。 That error seems to point to text not being able to be converted to int. 该错误似乎表明文本无法转换为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
}

Also the cb_oqty.SelectedItem will not convert to an int as it is an Object. 另外,cb_oqty.SelectedItem不会转换为int,因为它是Object。 you need to use SelectedValue. 您需要使用SelectedValue。

If your SQL datattype is float, your C# datatype should be float as well: 如果您的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();
    }

Better would be using the TryParse method. 最好使用TryParse方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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