Dynamic Search In DataGridView

eIn this article, I am going to share with you the information of Dynamic Search in C# DataGridView.

Here, we are going to learn to display the Excel file data into DataGridView and Dynamic Seardch on the basis of Header columns in C# Windows.Forms applications. We are going to make a small single-form application which takes an Excel file from the user and displays the  Excel data in a Data GridView so that the user searches the data on the basis of header column names.

Targeted Audiences

People with basic knowledge of C#.

Explanation

Things to do,

  • Make a C# WinForm application.
  • Create Excel File / can use Exists file.
  • Create UI
  • Code

Create a new project and give it a suitable name as I gave the project name ‘DynamicSearchDGV’.



After creating a project, create an Excel file with sample data, I am using the following data; if you download the project files, you will get the Excel file too. Else, you can use your own Excel file too.

 

Now, make a UI which contains four Buttons, two Textboxes, one ComboBox, a single DataGridView, and an OpenFileDialog tool. So, here, our UI looks like the following.

 

Now, I will explain you the functionality of these components which we used in the form. We are binding the DataGridView on FormLoad. Here, we're taking the default data from ‘Students Data.xlsx’ Excel file which we are setting default in the code, and if we want to change Excel file, we can browse new file by clicking on Browse button. After selecting the file, click on ‘Import Excel File’ to import the Excel data into DataGrdiView. The ‘Total No of Records’ field will show the number of records displaying in DataGridView, and now, you can search the data by Column Name which lists out in the ComboBox that we placed on the top of the form.
 
First, we have to select the search by field, then type the search keyword, and then click on the ‘Search’ button. It will show the search result. If the user wants to see all the data, then there is a button ’Show All’ that will show you all the data again.

Code
  1. using System.Data;  
  2. using System.Data.OleDb;   
Create LoadData Function. In this function, we are converting the Excel data into DataTable and binding this data to DataGridView, as shown in the below code.

  1. // Loading Data From EXcel to DataGridView    
  2. private void LoadData() {  
  3.     try {  
  4.         cmbSearchType.Items.Clear(); // Clear Search Box Data    
  5.         DataTable dt = GetTableDataFromXl(XlFile); // Converting Excel Data into DataTable    
  6.         dataGrid2.DataSource = dt;  
  7.         lbRowCount.Text = (dataGrid2.Rows.Count - 1).ToString(); // Total No of Records    
  8.         string[] ColNameList = dt.Columns.OfType < DataColumn > ().Select(x => x.ColumnName).ToArray();  
  9.         cmbSearchType.Items.AddRange(ColNameList); // Adding Column Names in ComoBox List    
  10.         if (cmbSearchType.Items.Count > 0) cmbSearchType.SelectedIndex = 0;  
  11.     } catch (Exception ex) {}  
  12. }  

In ‘GetTableDataFromXl’ function, we are simply converting the Excel data into ‘DataTable’. This function returns a DataTable and in next function, displays this DataTable data into DataGridView.

  1. private DataTable GetTableDataFromXl(string XlFile) {  
  2.     DataTable dt = new DataTable();  
  3.     try {  
  4.         string Ext = Path.GetExtension(XlFile);  
  5.         string connectionString = "";  
  6.         if (Ext == ".xls") { //For Excel 97-03    
  7.             connectionString = "Provider=Microsoft.Jet.OLEDB.4.0; Data Source =" + XlFile + "; Extended Properties = 'Excel 8.0;HDR=YES'";  
  8.         } else if (Ext == ".xlsx") { //For Excel 07 and greater    
  9.             connectionString = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source =" + XlFile + "; Extended Properties = 'Excel 8.0;HDR=YES'";  
  10.         }  
  11.         OleDbConnection conn = new OleDbConnection(connectionString);  
  12.         OleDbCommand cmd = new OleDbCommand();  
  13.         OleDbDataAdapter dataAdapter = new OleDbDataAdapter();  
  14.         cmd.Connection = conn;  
  15.         //Fetch 1st Sheet Name    
  16.         conn.Open();  
  17.         DataTable dtSchema;  
  18.         dtSchema = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);  
  19.         string ExcelSheetName = dtSchema.Rows[0]["TABLE_NAME"].ToString();  
  20.         conn.Close();  
  21.         //Read all data of fetched Sheet to a Data Table    
  22.         conn.Open();  
  23.         cmd.CommandText = "SELECT * From [" + ExcelSheetName + "]";  
  24.         dataAdapter.SelectCommand = cmd;  
  25.         dataAdapter.Fill(dt);  
  26.         conn.Close();  
  27.     } catch (Exception ex) {}  
  28.     return dt;  
  29. }  
This is the code for Form Load event. Here, we are calling ‘LoadData’ function on form load so it will by default load the ‘Students Data.xlsx’ file.

  1. private void Form1_Load(object sender, EventArgs e) {  
  2.     LoadData();  
  3. }  

In ‘CreateDataTableFromXml’ function, we are simply converting the XML data into ‘DataTable’. This function returns a DataTable and we are exporting this DataTable into the Excel file.

  1. // Creating DataTable With Xml Data    
  2. public System.Data.DataTable CreateDataTableFromXml(string XmlFile) {  
  3.         System.Data.DataTable Dt = new System.Data.DataTable();  
  4.         try {  
  5.             DataSet ds = new DataSet();  
  6.             ds.ReadXml(XmlFile);  
  7.             Dt.Load(ds.CreateDataReader());  
  8.         } catch (Exception ex) {}  
  9.         return Dt;  

Code for the file browse button click event

  1. private void btnImportExcelPath_Click(object sender, EventArgs e) {  
  2.     DialogResult drResult = OFD.ShowDialog();  
  3.     if (drResult == System.Windows.Forms.DialogResult.OK) txtImportExcelPath.Text = OFD.FileName;  
  4. }  

Code for the file ‘Import Excel File’ button click event

  1. private void btnImportExcel_Click(object sender, EventArgs e) {  
  2.     if (txtImportExcelPath.Text != "" && File.Exists(txtImportExcelPath.Text)) {  
  3.         XlFile = txtImportExcelPath.Text;  
  4.         LoadData();  
  5.         MessageBox.Show("File Imported!!!");  
  6.     }  
  7. }  

Code for the ‘Search’ button click event

Here, we are searching the data by using ‘RowFilter’ Property of DataGridView. Here, "Search By" is the ComboBox value that we are taking from DataGridView Header Column Names, and the Search Key is search TextBox’s Value.

  1. private void btnSearch_Click(object sender, EventArgs e) {  
  2.     try {  
  3.         ((DataTable) dataGrid2.DataSource).DefaultView.RowFilter = string.Format("" + cmbSearchType.Text + " like '%{0}%'", txtSearchBox.Text.Trim().Replace("'""''"));  
  4.         lbRowCount.Text = (dataGrid2.Rows.Count - 1).ToString();  
  5.     } catch (Exception ex) {}  
  6. }  

Code for the ‘Show All’ button click event

It is reloading the data from the Excel file.

  1. private void btnShowAll_Click(object sender, EventArgs e) {  
  2.     LoadData();  
  3. }  

Output

 
 
Conclusion

By using these easy and simple methods, we can search the data in DataGridView, and the best thing about this article is that there is no dependency on data format and column format. It will accept each type of data, and it allows any Excel file to load and display the data, and according to its column’s header, it will create the search criteria. Also, this is the best way to search within a DataGridView.

Please give your valuable feedback in the comments section.

Up Next
    Ebook Download
    View all
    Learn
    View all