Click here to Skip to main content
15,917,997 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Dear All,

I am new to Visual Basic. Facing Problem with DataGridView Sorting based on a value from a TextBox.

I am using code as below:
VB
Dim dt As New DataTable()
dt = TryCast(DataGridView1.DataSource, DataTable)
If dt IsNot Nothing Then
    Try
        dt.DefaultView.RowFilter = "LabelRef like '%TextBox2.Text%'" 'JMA-JF-3057
    Catch ex As Exception
        MsgBox(ex.ToString)
    End Try
End If

and output is blank, no error as well.

But when I provide the value directly in code as below, output is fine.
VB
dt.DefaultView.RowFilter = "LabelRef like 'JMA-JF-3057'"

Whats wrong with me?
Posted
Updated 4-Jan-15 22:49pm
v2
Comments
Kornfeld Eliyahu Peter 5-Jan-15 4:55am    
dt.DefaultView.RowFilter = "LabelRef like '%TextBox2.Text%'"
Did you expect the actual value of the textbox to be 'magicaly' inserted here? Why? How?
Shafiul Alam 5-Jan-15 4:58am    
Hi Thanks, I just found the right code

dt.DefaultView.RowFilter = String.Format("[LabelRef] Like '{0}%'", Me.TextBox2.Text.Trim())

1 solution

Try
VB
dt.DefaultView.RowFilter = "LabelRef like '%" + TextBox2.Text + "%'" 'JMA-JF-3057


Note if you are using a date column to filter then the syntax may depend on the driver (data provider) and you need to drop the wildcard character, so it would be
VB
dt.DefaultView.RowFilter = "LabelRef = '" + TextBoxDate.Text + "'"
or
VB
dt.DefaultView.RowFilter = "LabelRef = #" + TextBoxDate.Text + "#"
 
Share this answer
 
v2
Comments
Shafiul Alam 5-Jan-15 20:30pm    
Hi this code works fine. Not working, if TextBox2 value is date. Showing "Syntax Error: Missing Operand After (Column Name) Operator"

What need to be done differently?
CHill60 6-Jan-15 4:06am    
What is the actual content of the text box?
Shafiul Alam 7-Jan-15 3:58am    
I have 3 textbox, 2 for Simple Text and one for Date.
CHill60 7-Jan-15 6:19am    
I've updated my solution with some stuff about dates
Shafiul Alam 8-Jan-15 4:18am    
Thanks a lot, It works great.

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