Windows Forms: Search DataGridView by using TextBox in C#
By FoxLearn 8/13/2017 10:01:27 AM 24.97K
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
- Windows Forms: Text to speech in C#
- Windows Forms: Print Picture Box in C#
- Windows Forms: Advanced Filter DataGridView in C#
- Windows Forms: Progress Bar in C#
- How to create a Lucky Draw games in C#
- Windows Forms: Youtube Search with Paging in C#
- Windows Forms: How to Create a Random Password Generator in C#
- Windows Forms: Tag Control in C#
Categories
Popular Posts
Visual Studio: Auto increment version
04/01/2024
What is ARM architecture?
04/01/2024