Step 1: Click New Project, then select Visual C# on the left, then Windows and then select Windows Forms Application. Name your project "SearchDataGridView" and then click OK
Step 2: Design your form as below

Step 3: Add a connection string to the app.config file as below
<configuration>
<connectionStrings>
<add name="cn" connectionString="data source=.;initial catalog=NORTHWND;user id=sa;password=123@qaz" providerName="System.Data.SqlClient"/>
</connectionStrings>
</configuration>
Step 4: Add code to handle your form as below
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace SearchDataGridView
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
DataTable dt = new DataTable("Products");
private void Form1_Load(object sender, EventArgs e)
{
try {
using (SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["cn"].ConnectionString))
{
if (cn.State == ConnectionState.Closed)
cn.Open();
using(SqlDataAdapter da = new SqlDataAdapter("select *from products", cn))
{
//Fill data to datatable
da.Fill(dt);
dataGridView.DataSource = dt;
}
}
}
catch(Exception ex)
{
MessageBox.Show(ex.Message, "Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void txtSearch_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == (char)13)//Enter key
{
DataView dv = dt.DefaultView;
//Filter datagridview using textbox
dv.RowFilter = string.Format("productname like '%{0}%'", txtSearch.Text);
dataGridView.DataSource = dv.ToTable();
}
}
}
}
VIDEO TUTORIALS