2016-10-04 49 views
0

我正在尝试执行一个计算游乐园员工每周工资的项目。付款计算程序中的“从字符串转换为Double类型无效”

当我运行它并将数字放在文本框中时,出现一条错误消息,提示“字符串转换为Double类型无效”。

有人可以善意解释我出错的地方吗?

Dim ticketCollection As Double 
Dim foodService As Double 
Dim cleaningService As Double 
Dim ridingAssistance As Double 
Dim totalAmount As Double 
Dim totalCollectionPay As Double 
Dim totalFoodPay As Double 
Dim totalCleaningPay As Double 
Dim totalRidingPay As Double 

ticketCollection = txtCollection.Text 
foodService = txtFood.Text 
cleaningService = txtCleaning.Text 
ridingAssistance = txtRide.Text 

totalCollectionPay = ticketCollection * 5 
totalFoodPay = foodService * 10 
totalCleaningPay = cleaningService * 6 
totalRidingPay = ridingAssistance * 5 

totalAmount = totalCollectionPay + totalFoodPay + totalCleaningPay + totalRidingPay 

lblTotalDue.Text = totalAmount 
+0

它发生在哪一行?这可能会更好(更简单)在Excel中构建。基本上你的文本字段中有一个非数字字符(可能是空白)。你可以试试这个方法来确保只输入数字:http://stackoverflow.com/questions/463299/how-do-i-make-a-textbox-that-only-accepts-numbers –

+0

@ Nick.McDermaid错误显示在foodservice = txtFood.Text –

+3

@RomarioAlleyne - 您应该在代码的顶部放置'Option Strict On',看看编译器告诉你什么。在提出关于VB.NET的任何问题之前,你应该这样做。 – Enigmativity

回答

0

你的声明都是双倍的。当它从

.Text 

它变成一个字符串通过这样适当地将其转换为双先 see msdn conversion guide here

+0

我早些时候尝试过,可悲的是它没有工作 –

+0

@RomarioAlleyne我在visual studio 2015 vb.net上试过你的代码,它工作正常。奇怪的。为什么它是lblTotalDue.Text?它是一个标签或文本框刚刚命名为lbl? –

+0

以及我使用的是旧版本,我会下载2015并试一试。 –

1

我认为它会工作......试试看

Dim ticketCollection As Double 
Dim foodService As Double 
Dim cleaningService As Double 
Dim ridingAssistance As Double 
Dim totalAmount As Double 
Dim totalCollectionPay As Double 
Dim totalFoodPay As Double 
Dim totalCleaningPay As Double 
Dim totalRidingPay As Double 

ticketCollection = val(txtCollection.Text) 
foodService = val(txtFood.Text) 
cleaningService = val(txtCleaning.Text) 
ridingAssistance = val(txtRide.Text) 

totalCollectionPay = ticketCollection * 5 
totalFoodPay = foodService * 10 
totalCleaningPay = cleaningService * 6 
totalRidingPay = ridingAssistance * 5 

totalAmount = totalCollectionPay + totalFoodPay + totalCleaningPay +  totalRidingPay 

lblTotalDue.Text = totalAmount 

再次如果您得到totalamount的任何错误分配值像这样,

lblTotalDue.Text = val(totalAmount) 
0

尝试将输入转换为第一个。 CDbl将字符串类型的输入转换为双精度型。还要在代码顶部放置option strict on以查看发生的任何隐式转换,这总是很好,我建议在编写任何项目时始终打开此代码。我看到在另一个答案,他们要求做的一样,但val,这也可以工作,但val可以有一些有趣的副作用,example。所以最好不要因为这些原因使用valThis question也有一个很好的答案解释这一点,你怎么也可以尝试使用TryParse方法,它使用整数,但你只需要用双取代它。但我会尝试下面的第一个。

ticketCollection = CDbl(txtCollection.Text) 
foodService = CDbl(txtFood.Text) 
cleaningService = CDbl(txtCleaning.Text) 
ridingAssistance = CDbl(txtRide.Text) 

,并与该行lblTotalDue.Text = totalAmount可以使用lblTotalDue.Text = CStr(totalAmount)CStr转换为字符串。

相关问题