Click here to Skip to main content
15,893,337 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi Coders,

Could you help find code for my problem. I want to filter my database using another table or datagridview, instead of the usual textbox.

Table 1:
(Column)Name	Surname
        Name1	Surname1
        Name2	Surname2
        Name3	Surname3


Table 2: (Search Parameter)
(Column)Name	Surname
        Name1	Surname1


Expected Output to Table 1 is below:
(Column)Name	Surname
        Name1   Surname1


Any help is appreciated. My below code only shows the first row.

What I have tried:

I have tried using for loop.
VB
For i as integer = 0 To dgv2.rowcount -1
Dim query as string = "SELECT * From db_table WHERE Name LIKE '%" & dgv2.rows(i).cells(0).value &"'"
Dim comm as new sqlcommand(query,conn)
dim adapter as new sqladapter(comm)
dim table as new datatable()
adapter.fill(table)
dgv1.datasource = table
Posted
Updated 1-Dec-19 23:39pm
v2
Comments
Richard Deeming 3-Dec-19 10:40am    
Dim query as string = "SELECT * From db_table WHERE Name LIKE '%" & dgv2.rows(i).cells(0).value &"'"

Don't do it like that!

Your code is vulnerable to SQL Injection[^]. NEVER use string concatenation to build a SQL query. ALWAYS use a parameterized query.

Everything you wanted to know about SQL injection (but were afraid to ask) | Troy Hunt[^]
How can I explain SQL injection without technical jargon? | Information Security Stack Exchange[^]
Query Parameterization Cheat Sheet | OWASP[^]

Const query As String = "SELECT * FROM db_table WHERE Name LIKE @Name"
Dim comm as New SqlCommand(query, conn)
comm.Parameters.AddWithValue("@Name", "%" & dgv2.rows(i).cells(0).value & "%")

1 solution

As you are using a DataTable, you could use an additional DataTable.Select for the Surname, see examples here:
https://www.dotnetperls.com/datatable-select-vbnet[^]
vb.net - Filter datatable with Like [SOLVED] | DaniWeb[^]
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900