我正在VB.Net中编写一个在我的数据库上运行LINQ查询的方法,并将查询中的信息放入表单上的文本框中。
Public Sub OpenPartWindow(ByVal partNumber As String)
Using dbContext As New DB_LINQDataContext
Dim query = (From p In dbContext.Parts
Join ppl In dbContext.Part_Price_Logs On p.Part_ID Equals ppl.Part_ID
Where p.Part_Number = partNumber
Select p.Part_Number, p.Part_Description, p.Part_Information, p.Supplier.Supplier_Name, _
p.Part_Manufacturer.Manufacturer_Name, p.Part_Subcategory.Part_Category.Category_Description, _
p.Part_Subcategory.Subcategory_Description, ppl.Cost_Per_Unit, ppl.Discount_Percentage).First()
MessageBox.Show(query.ToString())
txtPartNum.Text = query.Part_Number.ToString()
txtSupplier.Text = query.Supplier_Name.ToString()
txtManufacturer.Text = query.Manufacturer_Name.ToString()
txtPrice.Text = query.Cost_Per_Unit.ToString()
txtDiscount.Text = query.Discount_Percentage.ToString()
txtDescription.Text = query.Part_Description.ToString()
txtInfo.Text = query.Part_Information.ToString()
Me.Show()
End Using
End Sub
我现在遇到的问题是最后一个字段txtInfo
TextBox。您会看到数据库上的Part_Information
字段允许NULL
值。所以当我在字段为空时去填充字段时,我得到一个NullReferenceException
,这是可以理解的。但是,我无法找到解决此异常的方法。
我试过了:
If Not IsNothing(query._Part_Information.ToString()) Then
以及
If query.Part_Information.Length > 0 Then
As If语句首先运行。但我每次都会收到错误。所以我对如何处理这个错误感到困惑。
答案 0 :(得分:1)
您可以使用以下任一选项:
txtInfo.Text = String.Format("{0}", query.Part_Information)
txtInfo.Text = $"{query.Part_Information}"
→$ - String Interpolation txtInfo.Text = query.Part_Information?.ToString()
→?. - Null Conditional Operator 如果query.Part_Information
为空,则前两个表达式会生成Sting.Empty
,最后一个表达式会生成Nothing
。