在为变量赋值之前使用变量?

时间:2012-04-03 15:47:59

标签: vb.net stringbuilder

从MSDN文章我读到我应该使用StringBuilder而不是连接普通字符串。但是我不知道为什么我会得到以下错误:“在赋值之前使用变量'ShowString'。在运行时可能会产生空引用异常。”

以下代码:

Dim ShowString As StringBuilder
    Dim ShowSort As StringBuilder
    'ShowString.
    ShowString.Append("POS,tdate,Product")
    '========Show Options==================
    If CheckBox1.Checked = True Then
        ShowString.Append(",tkey")
    End If
    If CheckBox2.Checked = True Then
        ShowString.Append(",Price")
    End If
    If CheckBox3.Checked = True Then
        ShowString.Append(",FID")
    End If
    '==========End Show Options============

    '=========Sort Options================
    If RadioButton1.Checked = True Then
        ShowSort.Append("tdate")
        If RadioButton8.Checked Then
            ShowSort.Append(" desc")
        End If
    End If
    If RadioButton2.Checked = True Then
        ShowSort.Append("tkey")
        If RadioButton8.Checked Then
            ShowSort.Append(" desc")
        End If
    End If
    '=======End Sort Options=============
    Dim sort As String = ShowSort.ToString
    Dim show As String = ShowString.ToString
    Try
        con.Open()
    Catch ex As Exception
        MessageBox.Show("Please contact support, there was a database error with the following message: " & ex.Message, "Cannot Connect", MessageBoxButtons.OK, MessageBoxIcon.Error)
    End Try

1 个答案:

答案 0 :(得分:6)

您需要为引用分配StringBuilder对象:

Dim ShowString As StringBuilder = New StringBuilder()

或者:

Dim ShowString As New StringBuilder()