我的代码出现问题。它在错误中说我应该在代码中加New
但我不知道在哪里放它。这是该函数的完整代码:
Private Sub TextBox1_TextChanged(sender As Object, e As EventArgs) Handles TextBox1.TextChanged
Try
Dim TA As New POSCanteenTableAdapters.ItemsTableAdapter
Dim TB = TA.GetDataByBarcode(TextBox1.Text)
If TB.Rows.Count = 0 Then
TextBox2.Text = ""
TextBox3.Text = ""
Button1.Enabled = False
Exit Sub
End If
Button1.Enabled = True
Dim IR As POSCanteen.ItemsRow = TB.Rows(0)
TextBox2.Text = IR.ItemName
TextBox3.Text = IR.SellPrice
Button2.Tag = IR
Catch ex As Exception
MsgBox(ex.Message, MsgBoxStyle.Critical Or MsgBoxStyle.OkOnly)
End Try
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim IR As POSCanteen.ItemsRow = Button1.Tag
Dim RI As New Integer
Dim ItemLoc As Integer = -1
For RI = 0 To CDGV3.Rows.Count - 1
If IR.Barcode = CDGV3.Rows(RI).Cells(0).Value Then
ItemLoc = RI
Exit For
End If
Next
If ItemLoc = -1 Then
CDGV3.Rows.Add(IR.Barcode, IR.ItemName, IR.BuyPrice, IR.SellPrice, 1, IR.SellPrice)
Else
Dim ItemCount As Long = CDGV3.Rows(ItemLoc).Cells(4).Value
ItemCount += 1
Dim NewPrice As Decimal = IR.SellPrice * ItemCount
CDGV3.Rows(ItemLoc).Cells(4).Value = ItemCount
CDGV3.Rows(ItemLoc).Cells(5).Value = NewPrice
End If
TextBox1.Text = ""
TextBox1.Focus()
End Sub
应该在数据网格中添加一个项目,但由于该错误,它不会。我不知道在哪里放它,因为编译器没告诉我在哪里。
这是异常消息:Object reference not set to an instance of an object.
答案 0 :(得分:1)
你需要提前考虑一个对象不能转换的可能性(尤其是当你让编译器猜测时)。不确定这是否是导致问题的对象,但您可能知道。了解如何使用调试器逐步完成代码。
Dim IR = TryCast(Button1.Tag, {type})
If Not IR Is Nothing Then
'rest of your code
End If
答案 1 :(得分:0)
我无法得到你的线,所以我建议你这样做。
尝试以下任何一项
Dim IR As New POSCanteen.ItemsRow = Button1.Tag
Dim ItemCount As New Long = CDGV3.Rows(ItemLoc).Cells(4).Value
Dim NewPrice As New Decimal = IR.SellPrice * ItemCount