Hi this post explains how to filter data in DataGridView using textbox as filter to search data in Gridview. For this tutorial I am using Northwnd database "Customer" Table .
Create a New Windows Project and Drag and drop
Datagrid and
textbox to windows Form.My Form Design
Source 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.Net.Configuration;
using System.Configuration;
using System.Data.SqlClient;
namespace DataGridExample
{
public partial class Form1 : Form
{
static DataTable dt;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection conn = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = "SELECT Top 20 * FROM CUSTOMERS";
cmd.Connection = conn;
cmd.CommandType = CommandType.Text;
DataTable dt = new DataTable();
SqlDataAdapter sda = new SqlDataAdapter(cmd);
dataGridView1.AutoGenerateColumns = false;
dataGridView1.RowHeadersVisible = false;
sda.Fill(dt);
dataGridView1.DataSource = dt;
}
}
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
(dataGridView1.DataSource as DataTable).DefaultView.RowFilter = string.Format("CustomerID LIKE '{0}%'", textBox1.Text);
}
}
}
Output:
No comments :
Post a Comment