Filter DataGridView Rows Depending upon Value in TextBox

Step 1: Design form, shown as below.
 
Step 2:  Write the following code,

using System;
using
System.Collections.Generic;
using
System.ComponentModel
using System.Data;
using
System.Drawing;
using
System.Linq;
using
System.Text;
using
System.Windows.Forms;
using
System.Data.SqlClient;

namespace DataGridViewFilter
{
    public partial class Form1 : Form
    {
        SqlConnection conn;
        SqlDataAdapter da;


        public Form1()
        {
            InitializeComponent();
        }


        private void Form1_Load(object sender, EventArgs e)
        {
            conn = new SqlConnection("Data Source=.; initial catalog=ranjit; integrated security=true");
            da = new SqlDataAdapter("Select ename from emp", conn);
            DataSet ds = new DataSet();
            da.Fill(ds);
            dataGridView1.DataSource = ds.Tables[0];
        }


        private void txtSearch_KeyUp(object sender, KeyEventArgs e)
        {
            foreach (DataGridViewRow row in dataGridView1.Rows)
            {
                string s = row.Cells[0].Value.ToString();

                if (!s.StartsWith(txtSearch.Text, true, null))
                {
                    CurrencyManager currencyManager1 = (CurrencyManager)BindingContext[dataGridView1.DataSource];
                   
currencyManager1.SuspendBinding();
                    row.Visible = false;
                   
currencyManager1.ResumeBinding();
                }
                else
                    row.Visible = true;
            }
        }
    }
}

Step 3: Run the application
 
 
 Step 4: Type in the search textbox
 
 
Ebook Download
View all
Learn
View all