Solved

search code in vb.net datagrid

Posted on 2016-08-17
3
56 Views
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
                    tb.Clear()
                    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
                    TextSearchStrDescCW.Clear()
                    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
                Else
                    TextSearchStrDescCW.Text = TextSearchStrDescCW.Text + Convert.ToChar(e.KeyCode)
                End If
            End If
        End If
    End Sub

Open in new window

0
Comment
Question by:PeterBaileyUk
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 2
3 Comments
 

Author Comment

by:PeterBaileyUk
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

0
 
LVL 33

Accepted Solution

by:
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)
				tb.Clear()
				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))
			Else
				table.Columns.Add([property].Name, [property].PropertyType)
			End If
		Next

		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)
			Next
			table.Rows.Add(values)
		Next

		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
		grid.BeginEdit(True)
		Dim counter = 0
		If clearSelected Then
			For Each row In grid.SelectedRows.Cast(Of DataGridViewRow)()
				row.Selected = False
			Next
		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
			Else
				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
				Next
			End If
		Next
		grid.EndEdit()

		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)
        Try
            If disposing AndAlso components IsNot Nothing Then
                components.Dispose()
            End If
        Finally
            MyBase.Dispose(disposing)
        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.SuspendLayout()
		'
		'Label1
		'
		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:"
		'
		'TextBox1
		'
		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
		'
		'Label2
		'
		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:"
		'
		'ComboBox1
		'
		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
		'
		'DataGridView1
		'
		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
		'
		'Button1
		'
		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
		'
		'Form1
		'
		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.Controls.Add(Me.Button1)
		Me.Controls.Add(Me.DataGridView1)
		Me.Controls.Add(Me.ComboBox1)
		Me.Controls.Add(Me.Label2)
		Me.Controls.Add(Me.TextBox1)
		Me.Controls.Add(Me.Label1)
		Me.Name = "Form1"
		Me.Text = "Form1"
		CType(Me.DataGridView1, System.ComponentModel.ISupportInitialize).EndInit()
		Me.ResumeLayout(False)
		Me.PerformLayout()

	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
-saige-
1
 

Author Comment

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

Featured Post

Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

Question has a verified solution.

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

Suggested Solutions

1.0 - Introduction Converting Visual Basic 6.0 (VB6) to Visual Basic 2008+ (VB.NET). If ever there was a subject full of murkiness and bad decisions, it is this one!   The first problem seems to be that people considering this task of converting…
The ECB site provides FX rates for major currencies since its inception in 1999 in the form of an XML feed. The files have the following format (reducted for brevity) (CODE) There are three files available HERE (http://www.ecb.europa.eu/stats/exch…
Finds all prime numbers in a range requested and places them in a public primes() array. I've demostrated a template size of 30 (2 * 3 * 5) but larger templates can be built such 210  (2 * 3 * 5 * 7) or 2310  (2 * 3 * 5 * 7 * 11). The larger templa…
I've attached the XLSM Excel spreadsheet I used in the video and also text files containing the macros used below. https://filedb.experts-exchange.com/incoming/2017/03_w12/1151775/Permutations.txt https://filedb.experts-exchange.com/incoming/201…

763 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