Windows Forms: Search DataGridView by using TextBox in C#
By FoxLearn 8/13/2017 10:01:27 AM 25.23K
How to search or filter DataGridView by using a TextBox in C#
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
- How to Add Combobox to DataGridView in C#
- How to Create Multiple pages on the Form using Panel control in C#
- How to insert Math Equation to RichTextBox in C#
- How to Send and Receive email in Microsoft Outlook using C#
- How to Print Windows Form in C#
- How to Use Form Load and Button click Event in C#
- How to use Advanced Filter DataGridView in C#
- How to use TagListControl in C#
Categories
Popular Posts
How to implement Jint in C#
09/14/2024
How to Download Chromedriver for Selenium
09/14/2024