Windows Forms: Search DataGridView by using TextBox in C#

How to search or filter DataGridView by using a TextBox in C#

Step 1Click 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

search datagridview using textbox in c#Step 2: Design your form as below

c# search datagridview

Step 3: Add a connection string to the app.config file as below

    <add name="cn" connectionString="data source=.;initial catalog=NORTHWND;user id=sa;password=123@qaz" providerName="System.Data.SqlClient"/>

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()

        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)
                    using(SqlDataAdapter da = new SqlDataAdapter("select *from products", cn))
                        //Fill data to datatable
                        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();