How to Search DataGridView by using TextBox in C#
By FoxLearn 12/7/2024 3:47:49 AM 25.77K
In this article, we'll explore how to implement search functionality in a DataGridView
in C#.
How to Filter and Search a DataGridView using a TextBox in C#?
Open Visual Studio, then 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
Drag and drop the Label, TextBox, DataGridView controls from the Visual Toolbox onto your form designer, then design your form as shown below.
The DataGridView
will display the data from the SQL Server database, and the TextBox
will allow users to type in a search query.
We begin by defining a connection string in the app.config
file, allowing the application to connect to a SQL Server database.
<configuration> <connectionStrings> <add name="cn" connectionString="data source=.;initial catalog=NORTHWND;user id=sa;password=123@qaz" providerName="System.Data.SqlClient"/> </connectionStrings> </configuration>
In this example, we are connecting to the NORTHWND
database (Northwind sample database) on the local SQL Server instance. The connection string specifies the user id
and password
for authentication.
Next, we set up a Form1
with a DataGridView
and a TextBox
for the search functionality.
In this step, we will load data from the Products
table in the SQL Server database and bind it to the DataGridView
when the form loads. We will use the SqlDataAdapter to fetch the data from the database and fill it into a DataTable.
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)) { // Create a DataTable to hold the data da.Fill(dt); // Bind the DataTable to the DataGridView dataGridView.DataSource = dt; } } } catch (Exception ex) { MessageBox.Show(ex.Message, "Message", MessageBoxButtons.OK, MessageBoxIcon.Error); } }
One of the key features of this application is the ability to filter data in real-time as the user types in the TextBox
. This is done using the RowFilter property of the DataView
, which allows us to filter rows based on a condition.
In the txtSearch_KeyPress
event handler, we listen for the Enter key press and filter the data accordingly.
// search datagridview c# private void txtSearch_KeyPress(object sender, KeyPressEventArgs e) { if (e.KeyChar == (char)13) // Enter key { DataView dv = dt.DefaultView; // Apply filter to the DataView based on the search text dv.RowFilter = string.Format("productname like '%{0}%'", txtSearch.Text); // Bind the filtered DataView to the DataGridView dataGridView.DataSource = dv.ToTable(); } }
This event is triggered whenever a key is pressed while the TextBox
is focused. We check if the Enter key was pressed (represented by (char)13
).
The RowFilter
property allows us to filter the rows based on a given condition. In this case, we filter by productname
matching the text entered in txtSearch
. Then, we convert the filtered DataView
back into a DataTable
and bind it to the DataGridView
.
To hold the product data from the SQL Server database, we declare a DataTable
in the Form1
class:
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"); } }
This DataTable
will store the data fetched from the database, and it will be used for filtering and binding to the DataGridView
.
By using search DataGridView C#, you can easily enhance the usability of your application by enabling quick, efficient searches over large datasets.
VIDEO TUTORIAL
- How to update UI from another thread in C#
- How to get CheckedListBox selected values in C#
- How to use Advanced Filter DataGridView in C#
- How to create a Notification Popup in C#
- How to Use Form Load and Button click Event in C#
- How to Link Chart /Graph with Database in C#
- How to Check SQL Server Connection in C#
- How to Generate Serial Key in C#