简体   繁体   中英

How do I display data from a SQL Server database based on checked box in VB.Net?

I need to retrieve data from SQL Server based on a checkbox list in VB.Net. When I check an item, all rows which contain that item must be displayed in a DataGridView. How do I make this happen?

Use this query:

Select column1, column2 
from tablename 
where columnname= '"& checkbox.text& "'

That must filter your database.

First, you need to get all selected items in the checkbox:

For Each checkBox As CheckBox In chkbxlst.Items
    If (checkBox.Checked = True) Then
        'its selected
    End If
Next

Next, write a SQL query,

select * from tablename where column in ({0})

We can go parameterized way or non-parameterized way. Parameterized is recommended to avoid SQL Injection attack.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM