Hi, I hope you are in a great day!.
Im new in asp.net and follow the instruction in this link https://www.aspsnippets.com/Articles/Search-records-in-GridView-and-highlight-results-in-ASPNet-using-C-and-VBNet.aspx
I changed the "constr" into "Server=DESKTOP-C6IEOUN\SQLEXPRESS;database =TestPhilSoft; Integrated Security=True" and I got an error saying "Object reference not set to an instance of an object." How can I fix it?
Any response is much appreciated. Thanks a lot!
Imports System.Data
Imports System.Data.SqlClient
Imports System.Configuration
Imports System.Text.RegularExpressions
Public Class _Default
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not IsPostBack Then
Me.BindGrid()
End If
End Sub
Protected Sub txtSearch_TextChanged(sender As Object, e As EventArgs) Handles txtSearch.TextChanged
End Sub
Protected Sub btnSearch_Click(sender As Object, e As EventArgs) Handles btnSearch.Click
If txtSearch.Text = "" Then
MsgBox("Please Type Name", vbInformation, "Empty Filed!")
End If
End Sub
Protected Sub Search(sender As Object, e As EventArgs)
Me.BindGrid()
End Sub
Private Sub BindGrid()
Dim constr As String = ConfigurationManager.ConnectionStrings("Server=DESKTOP-C6IEOUN\SQLEXPRESS;database =TestPhilSoft; Integrated Security=True").ConnectionString
Using con As New SqlConnection(constr)
Using cmd As New SqlCommand()
cmd.CommandText = "SELECT Name FROM tblInformation WHERE Name LIKE '%' + @Name + '%'"
cmd.Connection = con
cmd.Parameters.AddWithValue("@Name", txtSearch.Text.Trim())
Dim dt As New DataTable()
Using sda As New SqlDataAdapter(cmd)
sda.Fill(dt)
GridView1.DataSource = dt
GridView1.DataBind()
End Using
End Using
End Using
End Sub
Protected Sub OnPageIndexChanging(sender As Object, e As GridViewPageEventArgs)
GridView1.PageIndex = e.NewPageIndex
Me.BindGrid()
End Sub
Protected Sub OnRowDataBound(sender As Object, e As GridViewRowEventArgs)
If e.Row.RowType = DataControlRowType.DataRow Then
e.Row.Cells(0).Text = Regex.Replace(e.Row.Cells(0).Text, txtSearch.Text.Trim(),
Function(match As Match) String.Format("<span style = 'background-color:#D9EDF7'>{0}</span>", match.Value),
RegexOptions.IgnoreCase)
End If
End Sub
End Class