Filter data in datagridview in c#

Advertisement
In this article I will explain how to create filter by entering id or name in text box.

My out will be looks like this Now i am entering Empid and Empname





My solution looks like this


Write the code code in Form1.cs
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 IdSearch
{
    public partial class Form1 : Form
    {
        BindingSource bs = new BindingSource();
        public Form1()
        {
            InitializeComponent();
        }

        public void displayDataGridView()
        {

            using (SqlConnection con = new SqlConnection("Data Source = CHINNU;Initial Catalog = dotnetdb;Uid = sa;Password = password123;"))
            {
                SqlCommand cmd;
                cmd = new SqlCommand("select * from Employee", con);
                cmd.CommandType = CommandType.Text;
                SqlDataAdapter da = new SqlDataAdapter(cmd);
                DataSet ds = new DataSet();
                da.Fill(ds);
                dataGridView1.DataSource = ds.Tables[0];

                dataGridView1.AutoGenerateColumns = false;
                dataGridView1.AllowUserToAddRows = false;
            }

        }

        private void Form1_Load(object sender, EventArgs e)
        {
            displayDataGridView();
        }

        private void txtfind_TextChanged(object sender, EventArgs e)
        {
            try
            {
            
                bs.DataSource = dataGridView1.DataSource;
          
               bs.Filter = string.Format("EmpId LIKE '%{0}%' OR [EmpName] LIKE '%{0}%'", txtfind.Text);
                dataGridView1.DataSource = bs;
            }
            catch (Exception ex)
            {
                
            }
        }

       
    }
}
Advertisements
SHARE

Unknown

  • Image
  • Image
  • Image
  • Image
  • Image
    Blogger Comment
    Facebook Comment

2 comments:

  1. This is my first time i visit here and I found so many interesting stuff in your blog especially it's discussion, thank you. odzyskiwanie danych

    ReplyDelete