I have added a TextBox, Button and GridView on the form.
You need to add the connection string in Application config file. Also add the reference of System.Configuration in your project
1) Right click on project
2)Select Add Reference
3)Click on .Net tab
4)Search for System.Configuration and add then OK.
Namespaces
using System.Configuration;
using System.Data.SqlClient;
C#
public partial class SearchGridViewTextBox : Form
{
public SearchGridViewTextBox()
{
InitializeComponent();
}
private void btnSearchEmployees_Click(object sender, EventArgs e)
{
this.dataGridView1.AutoGenerateColumns = true;
string conString = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
string sqlStatment = "SELECT EmployeeId, LastName, Country FROM Employees WHERE LastName LIKE @LastName + '%'";
using (SqlConnection con = new SqlConnection(conString))
{
using (SqlCommand cmd = new SqlCommand(sqlStatment, con))
{
using (SqlDataAdapter da = new SqlDataAdapter(cmd))
{
cmd.Parameters.AddWithValue("@LastName", this.txtName.Text.Trim());
DataTable dt = new DataTable();
da.Fill(dt);
this.dataGridView1.DataSource = dt;
this.dataGridView1.AllowUserToAddRows = false;
}
}
}
}
}
VB
Public Partial Class SearchGridViewTextBox
Inherits Form
Public Sub New()
InitializeComponent()
End Sub
Private Sub btnSearchEmployees_Click(sender As Object, e As EventArgs)
Me.dataGridView1.AutoGenerateColumns = True
Dim conString As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
Dim sqlStatment As String = "SELECT EmployeeId, LastName, Country FROM Employees WHERE LastName LIKE @LastName + '%'"
Using con As New SqlConnection(conString)
Using cmd As New SqlCommand(sqlStatment, con)
Using da As New SqlDataAdapter(cmd)
cmd.Parameters.AddWithValue("@LastName", Me.txtName.Text.Trim())
Dim dt As New DataTable()
da.Fill(dt)
Me.dataGridView1.DataSource = dt
Me.dataGridView1.AllowUserToAddRows = False
End Using
End Using
End Using
End Sub
End Class
Screenshot