2011-03-01 98 views
0

使用VB6如何顯示所有值

我在窗體中使用複選框和組合框。

當我點擊複選框,組合框將啓用,默認情況下組合框將被禁用。

代碼。

Private Sub chkbox1_Click() 
    combobox1.enable = true 
End Sub 

Private Sub chkbox2_Click() 
    combobox2.enable = true 
End Sub 

輸出代碼爲

If chkbox1.Value = 1 Then 
    sql2 = "Select * from table1 where value = '" & combobox1 & "' " 
ElseIf chkbox2.Value = 1 Then 

    sql2 = "Select * from table1 where value = '" & combobox2 & "'" 
Else 
    sql2 = "Select * from table1" 
End If 

上面的代碼工作,但是當我點擊兩個複選框,則需要兩個組合框啓用,然後我運行查詢它顯示了combobox1值。

例如

I selected the value = 50 from combobox1 (checkbox1 clicked) 
I selected the value = 100 from combobox2 (checkbox2 clicked) 
當我運行輸出代碼

,則輸出爲顯示值,其中值= 50,它沒有顯示值= 100也。

它應該在輸出代碼中顯示兩個值

如何解決此問題。

需要VB6代碼幫助

+1

在'如果-ElseIf',如果一個條件滿足,則條件語句的其餘部分不會被執行。如果你想得到兩者,請嘗試用if語句保留'chkcombin.Value = 1'的條件。 – Mahesh 2011-03-01 18:44:19

+0

你的描述不是很清楚。例如,什麼是「chkcombin1」?我建議您添加表單的屏幕截圖以作進一步說明。 – Abbas 2011-03-01 18:46:23

回答

2
If chkcombin1.Value = 1 And chkcombin2.Value = 0 Then 
    sql2 = "Select * from table1 where value = '" & combobox1 & "' " 
ElseIf chkcombin2.Value = 1 And chkcombin1.Value = 1 Then 

    sql2 = "Select * from table1 where value = '" & combobox2 & "'" 
ElseIf chckcombin1.Value = And chkcombin2.Value = 1 
    sql2 = "Select * from table 1 Where value = '" & combobox1 & "' and value = '" & combobox2 & "'" 
Else 
    sql2 = "Select * from table1" 
End If 

如果同時選中第一種情況是真實的,因爲chkcombin1.Value = 1 所以你需要進行檢查,以確保其他框未選中正在發生的事情是。

編輯運算評論

既然你有多個複選框,那麼我建議這樣的:

這不是測試,也不是最佳的,但它應該給你一個想法

Dim select As String = "Select * from table 1" 

'This needs to be a field for the whole class 
Dim where As String = "" 

If chkcombin1.Value = 1 Then 
    where += CreateCaluse(combobox1) 
End If 

'Then do that for each of your comboboxes 

'Then 
sql2 = select + where 

Private Function CreateClause(ByVal comboboxValue As String) As String 
    If where = "" Then 
     Return " Where value = '" & comboboxValue & "'" 
    Else 
     Return " and value = '" & comboboxValue & "'" 
    End If 
End Function 

SO所做的是寫入你的語句的no複選框選中部分,然後它準備where子句,使用一個函數來生成必要的部分,如果where子句是一個空字符串,它將寫入它應該爲1的地方,然後附加所有必需的and子句。最後它將這個陳述結合在一起。如果沒有任何在where子句中,那麼你得到的Select * from table1

+0

我有超過10個複選框,所以對於任何替代代碼是否存在,或者我必須這樣做...? – Gopal 2011-03-01 18:48:08

+0

@Gopal那麼,那實際上改變了你應該完全做到這一點。我會做一些編輯和建議 – msarchet 2011-03-01 19:11:14

+0

你能否介紹一下你的代碼。我很困惑... – Gopal 2011-03-01 19:35:54

0

你可以試試這個

sql2 = "SELECT * FROM table1 WHERE 0=1" 
If chkbox1.Value = vbChecked Then 
    sql2 = sql2 & " OR value = '" & Replace(combobox1.Text, "'", "''") & "'" 
End If 
If chkbox2.Value = vbChecked Then 
    sql2 = sql2 & " OR value = '" & Replace(combobox2.Text, "'", "''") & "'" 
End If 
If chkbox3.Value = vbChecked Then 
    ... 

或者,如果您使用的控件數組中的代碼將大大減少

sql2 = "SELECT * FROM table1 WHERE 0=1" 
For i = 1 To 10 
    If chkbox(i).Value = vbChecked Then 
     sql2 = sql2 & " OR value = '" & Replace(ComboBox(i).Text, "'", "''") & "'" 
    End If 
Next