search code in datagrid

Posted on 2016-08-17
Last Modified: 2016-08-17
I have some code That searches a listbox from text enetered in a textbox and would like to create  the same but using data grid instead if it is possible, i posted this code so the functionality can be seen, i suspect the datagrid code would be entirely different.

The code I have provided by one of the experts but the question id is unknown is the following. ive amended the textbox search name and added the datagrid name in the code but the method to do this must be slightly different. I want to type something into the search box and once entered it finds the text in the grid based on column

   Private Sub TextSearchStrDescCW_KeyUp(sender As Object, e As KeyEventArgs) Handles TextSearchStrDescCW.KeyUp
        Dim index = -1
        If TypeOf sender Is TextBox Then
            Dim tb = DirectCast(sender, TextBox)
            If tb.Equals(TextSearchStrDescCW) Then
                If e.KeyCode.Equals(Keys.Enter) Then
                    index = DataGridViewStringsCW.FindString(tb.Text)  'underlined here
                    If index <> -1 Then
                        DataGridViewStringsCW.SetSelected(index, True) 'underlined here
                    End If
                    e.Handled = True
                End If
            End If
        ElseIf TypeOf sender Is ListBox Then
            Dim lb = DirectCast(sender, ListBox)
            If lb.Equals(DataGridViewStringsCW) Then
                If e.KeyCode.Equals(Keys.Enter) Then
                    index = lb.FindString(TextSearchStrDescCW.Text)
                    If index <> -1 Then
                        lb.SetSelected(index, True)
                    End If
                    e.Handled = True
                ElseIf e.KeyCode.Equals(Keys.Back) Then
                    If TextSearchStrDescCW.Text.Length > 0 Then
                        TextSearchStrDescCW.Text = TextSearchStrDescCW.Text.Substring(0, TextSearchStrDescCW.Text.Length - 1)
                    End If
                    TextSearchStrDescCW.Text = TextSearchStrDescCW.Text + Convert.ToChar(e.KeyCode)
                End If
            End If
        End If
    End Sub

Open in new window

Question by:PeterBaileyUk
  • 2

Author Comment

ID: 41759217
I tried this approach but no joy with this

    Private Sub TextSearchStrDescCW_KeyUp(sender As Object, e As KeyEventArgs) Handles TextSearchStrDescCW.KeyUp
        DataGridViewStringsCW.SelectionMode = DataGridViewSelectionMode.FullRowSelect
        Dim intcount As Integer = 0
        For Each Row As DataGridViewRow In DataGridViewStringsCW.Rows
            If DataGridViewStringsCW.Rows(intcount).Cells(0).Value.ToString = TextSearchStrDescCW.Text.ToString() Then
                DataGridViewStringsCW.Rows(intcount).Selected = True

            End If
            intcount += 1
        Next Row

    End Sub

Open in new window

LVL 33

Accepted Solution

it_saige earned 500 total points
ID: 41759848
Just so that I am clear, you want to find text in a specific column in a datagridview using a textbox and select the row if the text is found?

Ok, let's make this work:

Form1.vb -
Imports System.Runtime.CompilerServices
Imports System.ComponentModel

Public Class Form1

	Private Sub OnLoad(sender As Object, e As EventArgs) Handles MyBase.Load
		DataGridView1.DataSource = (From i In Enumerable.Range(0, 20) Select New With {.ID = i, .FirstName = String.Format("{0}{1}", If(i Mod 5 = 0, "Paul", If(i Mod 4 = 0, "Larry", If(i Mod 3 = 0, "Susan", If(i Mod 2 = 0, "Mary", "Peter")))), i), .LastName = String.Format("LastName{0}", i), .BirthDate = DateTime.Now.AddYears(-(9 * i)), .IsWorking = i Mod 2 = 0}).ConvertToDataTable()
		Dim columns As New List(Of String)(From column As DataColumn In CType(DataGridView1.DataSource, DataTable).Columns Select column.ColumnName)
		columns.Insert(0, "- All Columns -")
		ComboBox1.DataSource = columns
	End Sub

	Private Sub OnKeyUp(sender As Object, e As KeyEventArgs) Handles TextBox1.KeyUp
		Dim tb = DirectCast(sender, TextBox)
		If tb.Equals(TextBox1) Then
			If e.KeyCode.Equals(Keys.Enter) Then
				DataGridView1.SearchAndSelect(tb.Text, ComboBox1.SelectedItem, True)
				e.Handled = True
			End If
		End If
	End Sub

	Private Sub OnClick(sender As Object, e As EventArgs) Handles Button1.Click
		MessageBox.Show(String.Format("Selected Rows = {1}{0}Values:{2}", Environment.NewLine, DataGridView1.SelectedRows.Count, String.Join(Environment.NewLine, (From selected As DataGridViewRow In DataGridView1.SelectedRows Let row = CType(selected.DataBoundItem, DataRowView).Row Select New With {.ID = row("ID"), .FirstName = row("FirstName"), .LastName = row("LastName"), .BirthDate = row("BirthDate"), .IsWorking = row("IsWorking")}))))
	End Sub
End Class

Module Extensions
	<Extension()> _
	Public Function ConvertToDataTable(Of T)(ByVal source As IEnumerable(Of T)) As DataTable
		Dim properties As PropertyDescriptorCollection = TypeDescriptor.GetProperties(GetType(T))
		Dim table As DataTable = New DataTable()

		For i As Integer = 0 To properties.Count - 1
			Dim [property] As PropertyDescriptor = properties(i)
			If [property].PropertyType.IsGenericType AndAlso [property].PropertyType.GetGenericTypeDefinition().Equals(GetType(Nullable)) Then
				table.Columns.Add([property].Name, [property].PropertyType.GetGenericArguments()(0))
				table.Columns.Add([property].Name, [property].PropertyType)
			End If

		Dim values(properties.Count - 1) As Object
		For Each item As T In source
			For i As Integer = 0 To properties.Count - 1
				values(i) = properties(i).GetValue(item)

		Return table
	End Function

	<Extension()> _
	Public Sub SearchAndSelect(grid As DataGridView, term As String, selector As String, Optional clearSelected As Boolean = False)
		If grid IsNot Nothing AndAlso grid.Rows.Count < 1 Then Return
		If String.IsNullOrWhiteSpace(term) Then Return
		Dim counter = 0
		If clearSelected Then
			For Each row In grid.SelectedRows.Cast(Of DataGridViewRow)()
				row.Selected = False
		End If

		For Each row In grid.Rows.Cast(Of DataGridViewRow)()
			If selector <> "- All Columns -" Then
				If row.Cells(selector).Value IsNot Nothing AndAlso row.Cells(selector).Value.ToString().IndexOf(term, StringComparison.OrdinalIgnoreCase) <> -1 Then
					row.Selected = True
					counter += 1
					Continue For
				End If
				For Each column In grid.Columns.Cast(Of DataGridViewColumn)()
					If row.Cells(column.Name).Value IsNot Nothing AndAlso row.Cells(column.Name).Value.ToString().IndexOf(term, StringComparison.OrdinalIgnoreCase) <> -1 Then
						row.Selected = True
						counter += 1
						Exit For
					End If
			End If

		If counter = 0 Then MessageBox.Show(String.Format("No rows were found that matched - {0}", term))
	End Sub
End Module

Open in new window

Form1.Designer.vb -
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _
Partial Class Form1
    Inherits System.Windows.Forms.Form

    'Form overrides dispose to clean up the component list.
    <System.Diagnostics.DebuggerNonUserCode()> _
    Protected Overrides Sub Dispose(ByVal disposing As Boolean)
            If disposing AndAlso components IsNot Nothing Then
            End If
        End Try
    End Sub

    'Required by the Windows Form Designer
    Private components As System.ComponentModel.IContainer

    'NOTE: The following procedure is required by the Windows Form Designer
    'It can be modified using the Windows Form Designer.  
    'Do not modify it using the code editor.
    <System.Diagnostics.DebuggerStepThrough()> _
    Private Sub InitializeComponent()
		Me.Label1 = New System.Windows.Forms.Label()
		Me.TextBox1 = New System.Windows.Forms.TextBox()
		Me.Label2 = New System.Windows.Forms.Label()
		Me.ComboBox1 = New System.Windows.Forms.ComboBox()
		Me.DataGridView1 = New System.Windows.Forms.DataGridView()
		Me.Button1 = New System.Windows.Forms.Button()
		CType(Me.DataGridView1, System.ComponentModel.ISupportInitialize).BeginInit()
		Me.Label1.AutoSize = True
		Me.Label1.Location = New System.Drawing.Point(12, 16)
		Me.Label1.Name = "Label1"
		Me.Label1.Size = New System.Drawing.Size(62, 13)
		Me.Label1.TabIndex = 0
		Me.Label1.Text = "Search For:"
		Me.TextBox1.Location = New System.Drawing.Point(80, 12)
		Me.TextBox1.Name = "TextBox1"
		Me.TextBox1.Size = New System.Drawing.Size(253, 20)
		Me.TextBox1.TabIndex = 1
		Me.Label2.AutoSize = True
		Me.Label2.Location = New System.Drawing.Point(348, 16)
		Me.Label2.Name = "Label2"
		Me.Label2.Size = New System.Drawing.Size(33, 13)
		Me.Label2.TabIndex = 2
		Me.Label2.Text = "From:"
		Me.ComboBox1.FormattingEnabled = True
		Me.ComboBox1.Location = New System.Drawing.Point(387, 12)
		Me.ComboBox1.Name = "ComboBox1"
		Me.ComboBox1.Size = New System.Drawing.Size(196, 21)
		Me.ComboBox1.TabIndex = 3
		Me.DataGridView1.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize
		Me.DataGridView1.Location = New System.Drawing.Point(15, 39)
		Me.DataGridView1.Name = "DataGridView1"
		Me.DataGridView1.RowHeadersVisible = False
		Me.DataGridView1.SelectionMode = System.Windows.Forms.DataGridViewSelectionMode.FullRowSelect
		Me.DataGridView1.Size = New System.Drawing.Size(568, 216)
		Me.DataGridView1.TabIndex = 4
		Me.Button1.Location = New System.Drawing.Point(430, 262)
		Me.Button1.Name = "Button1"
		Me.Button1.Size = New System.Drawing.Size(152, 23)
		Me.Button1.TabIndex = 5
		Me.Button1.Text = "Get Selected Records"
		Me.Button1.UseVisualStyleBackColor = True
		Me.AutoScaleDimensions = New System.Drawing.SizeF(6.0!, 13.0!)
		Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font
		Me.ClientSize = New System.Drawing.Size(595, 289)
		Me.Name = "Form1"
		Me.Text = "Form1"
		CType(Me.DataGridView1, System.ComponentModel.ISupportInitialize).EndInit()

	End Sub
	Friend WithEvents Label1 As System.Windows.Forms.Label
	Friend WithEvents TextBox1 As System.Windows.Forms.TextBox
	Friend WithEvents Label2 As System.Windows.Forms.Label
	Friend WithEvents ComboBox1 As System.Windows.Forms.ComboBox
	Friend WithEvents DataGridView1 As System.Windows.Forms.DataGridView
	Friend WithEvents Button1 As System.Windows.Forms.Button

End Class

Open in new window

Produces the following output -

Initial load:Capture.JPGSearching for 1962 from all columns (row id 6 has a birthdate  year of 1962):Capture.JPGPress enter and viola:Capture.JPGChange to single column; say FirstName and search for ry:Capture.JPGPress enter and viola:Capture.JPGThere are records off the screen that are selected which is the reason for the button:Capture.JPG

Author Comment

ID: 41760581
For some reason my final comment didnt show..thank you so much the presentation stage by stage really aids my learning.

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

I think the Typed DataTable and Typed DataSet are very good options when working with data, but I don't like auto-generated code. First, I create an Abstract Class for my DataTables Common Code.  This class Inherits from DataTable. Also, it can …
Introduction As chip makers focus on adding processor cores over increasing clock speed, developers need to utilize the features of modern CPUs.  One of the ways we can do this is by implementing parallel algorithms in our software.   One recent…
A short film showing how OnPage and Connectwise integration works.
I designed this idea while studying technology in the classroom.  This is a semester long project.  Students are asked to take photographs on a specific topic which they find meaningful, it can be a place or situation such as travel or homelessness.…

932 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

13 Experts available now in Live!

Get 1:1 Help Now