打开时表格崩溃

时间:2017-02-09 10:24:39

标签: c# forms

每当我打开我的表格(正在发送的东西)时,它会崩溃,因为某个部分。打破它的部分是Convert.ToInt32(txt_cost)。我想知道如何在不崩溃程序的情况下将其发送到我的其他表单

private void btn_HomepageSearch_Click(object sender, EventArgs e)
    {
        if (isValidData())
        {
            string destination = cbo_Destination.Text;

            DateTime checkIn = date_FlightDate.Value;
            frm_BookingPg frm_HomePge = new frm_BookingPg(cbo_Destination.Text, cbo_AmountOfPeople.Text, Convert.ToInt32(txt_cost));

            frm_HomePge.Show();
            this.Hide();               
        }         
    }

3 个答案:

答案 0 :(得分:2)

Assuming you have an integer in your text box, i believe that should be

 Convert.ToInt32(txt_cost.Text)

如果它仍然崩溃,那么txt_cost的值不能是有效的int。试试下面的

var intValue = 0;

            if (int.TryParse(txt_cost.Text, out intValue))
            {
                //do something with intValue    
            }

答案 1 :(得分:1)

已编辑

  

@Minimarshman的评论中的代码部分):

case "ten":
    price1 = 10; 
    break;

decimal total = price * price1;
txt_cost.Text = total.ToString("c");

因为您可以看到您正在将decimal转换为string,然后将其分配到TextBox的{​​{1}}媒体资源中。

总是留下一些误差,尤其是在进行软件开发时。这意味着您永远不会信任该用户将按预期使用您的软件。您对Text的使用表明您过分信任您的/用户数据。

要处理此问题,您必须检查您正在转换的每个数据(如果它确实是有效数据)。 有许多内置的方法/函数可以验证它,你应该使用的是Convert.ToInt32(txt_cost),它可以确保数据对类型转换有效。

另一件事是你使用decimal.TryParseToString)的特殊格式,表示它应该在字符串中加上货币标记。你必须记住然后摆脱这个。

代码说明:

"C"

备注:

这样做会让您感到混乱,因为使用显式类型转换从decimal IfValueIsConvertibleItWillBeHeldHere = 0; if(decimal.TryParse(txt_cost.Text.Split(' ')[0], out IfValueIsConvertibleItWillBeHeldHere) { frm_BookingPg frm_HomePge = new frm_BookingPg( cbo_Destination.Text, cbo_AmountOfPeople.Text, (int)IfValueIsConvertibleItWillBeHeldHere // see the difference ? ); frm_HomePge.Show(); this.Hide(); } else { // show some message to the user that input was invalid } 转换为decimal会削减该值。例如int显式转换为decimal d = 0.5M;,如int将返回int i = (int)d;,因为它会在小数点后标记0

您应该重写.以接受frm_BookingPg类型而不是decimal类型,以便价值准确无误:

int

而不是你的实际:

public frm_BookingPg(string destination, string amountOfPeople, decimal cost)

答案 2 :(得分:0)

你有没有尝试过更换 Convert.ToInt32(txt_cost) 只有一个int32字面值?

如下: -

frm_BookingPg frm_HomePge = new frm_BookingPg(cbo_Destination.Text, cbo_AmountOfPeople.Text, 1234);

它还会崩溃吗?

相关问题