2016-03-08 45 views
1

我想乘文本值和組合框的值,並在orderprice文本 顯示它,我在SQL中使用的數據類型是所有這些輸入字符串是不正確的格式C#

「浮動」
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();         
} 
+0

您需要放置斷點並調試個別行。只有這樣你才能找出哪個語句拋出異常。 – Yahya

+0

我覺得組合填充所有項目時,它會拋出異常。 它是在選擇組合值之前還是選擇之後? –

+0

我在這一行上收到錯誤int proprice = Convert.ToInt16(txt_oprice.Text); –

回答

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,因爲它是一個對象。你需要使用SelectedValue。

+0

它給int.tryparse(cb_oqty.selectedvalue,出數量)錯誤 –

+0

什麼是錯誤? –

+0

最佳重載方法類型錯誤 –

0

如果你的SQL datattype是浮,你的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方法。

+0

我得到同樣的錯誤,因爲我第一次得到 –