我需要根据vb.net中的复选框从SQL Server检索数据。当我检查一个项目时,所有包含该项目的行都必须在DataGridView中显示。我该如何实现?
使用此查询:
Select column1, column2
from tablename
where columnname= '"& checkbox.text& "'
必须过滤您的数据库。
首先,您需要在复选框中获取所有选定的项目:
For Each checkBox As CheckBox In chkbxlst.Items
If (checkBox.Checked = True) Then
'its selected
End If
Next
接下来,写一个SQL查询,
select * from tablename where column in ({0})
我们可以以参数化的方式或非参数化方式。建议进行参数化以避免SQL注入攻击。
Dim query as String = "select * from tablename where column in ({0})"
Dim i as Int = 0
Dim sqlCommand = new SqlCommand()
sqlCommand.Connection = connection
sqlCommand.CommandType = CommandType.Text
Dim sb = new new List<string>()
For Each checkBox As CheckBox In chkbxlst.Items
If (checkBox.Checked = True) Then
Dim paramName as String = "paramName" + i
sb.Append(paramName)
sqlCommand.Parameters.AddWithValue(paramName, checkBox.Text)
End If
Next
sqlCommand.CommandText = String.Format(query, string.Join(",", sb))
'..execute the command and get response