2011-03-01 81 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