簡體   English   中英

在vb.net中使用多個復選框為SQL語句生成字符串

[英]Build string for SQL statement with multiple checkboxes in vb.net

我目前正在使用SQL后端和vb.net Windows窗體前端。 我試圖根據用戶將選擇的復選框列表從SQL中提取報告。

為此,我將在SQL中使用IN子句。 唯一的問題是,如果我在vb.net中使用if語句來構建字符串,那將是設置該字符串的大量代碼。

我希望有人知道更好的方法。 下面的代碼示例僅顯示選擇第1行,同時選擇第1行和第2行。我將需要使代碼能夠選擇任何種類的行。 該字符串必須是行號,並在其后加一個逗號。 這樣,當我在SQL查詢中包含代碼時,它不會出錯。

這是代碼:

Dim LineString As String
    'String set up for line pull
    If CBLine1.Checked = False And CBLine2.Checked = False And CBLine3.Checked = False And CBLine4.Checked = False And _
         CBLine7.Checked = False And CBLine8.Checked = False And CBLine10.Checked = False And CBLine11.Checked = False And CBLine12.Checked = False Then
        MsgBox("No lines selected for download, please select lines for report.")
        Exit Sub
    End If

    If CBLine1.Checked = True And CBLine2.Checked = False And CBLine3.Checked = False And CBLine4.Checked = False And _
        CBLine7.Checked = False And CBLine8.Checked = False And CBLine10.Checked = False And CBLine11.Checked = False And CBLine12.Checked = False Then
        MsgBox("This will save the string as only line 1")

    ElseIf CBLine1.Checked = True And CBLine2.Checked = True And CBLine3.Checked = False And CBLine4.Checked = False And _
    CBLine7.Checked = False And CBLine8.Checked = False And CBLine10.Checked = False And CBLine11.Checked = False And CBLine12.Checked = False Then
        MsgBox("This will save the string as only line 1 and 2")
    End If

最后的字符串將必須插入如下的SQL語句中:

SELECT * 
FROM tabl1 
WHERE LineNumber IN (-vb.netString-)

上面的代碼將需要在字符串中添加逗號。

首先,您需要設置所有復選框,並將“標記”屬性設置為它們所引用的行號。 因此,例如,CBLine1復選框會將其屬性Tag設置為值1(對於其他所有復選框,依此類推)。

使用WinForm設計器可以輕松完成此操作,或者,如果願意,可以在運行時在Form load事件中完成此操作。

下一步是檢索所有選中的復選框,並提取Tag屬性以構建所需行的列表。 這可以使用一些Linq來完成

Dim linesSelected = new List(Of String)()
For Each chk in Me.Controls.OfType(Of CheckBox)().
                   Where(Function(c) c.Checked)
   linesSelected.Add(chk.Tag.ToString())
Next

現在您可以開始驗證輸入

if linesSelected.Count = 0 Then
   MessageBox.Show("No lines selected for download, please select lines for report.")
Else If linesSelected.Count = 1 Then
   MessageBox.Show("This will save the string only for line " & linesSelected(0))
Else
   Dim allLines = string.Join(",", linesSelected)
   MessageBox.Show("This will save the string for lins " & allLines)
End If

當然,List(Of String)和string.Join方法非常適合為查詢建立IN子句

我覺得我只收到您問題的一半,但是希望對您有所幫助。 在VB.net中,我們顯示狀態為已啟用或已禁用的表單列表。

有一個復選框,當選中時僅顯示啟用的表單。

SELECT * FROM forms WHERE (Status = 'Enabled' or @checkbox = 0)

該查詢實際上具有更長的where子句,該子句以相同方式處理下拉選項。 這應該可以幫助您將后端VB傳遞給簡單的SQL語句。

If checkboxes 3...10 = false then
    If checkbox 1 = true then
        If checkbox 2 is true then
            A
        Else if checkbox 2 = false then
            B
        End if
Else
    C
End if

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM