The Easy Way to Search Data in ListView Using C# and MS Access Database
Submitted by janobe on Saturday, March 23, 2019 - 21:22.
In this tutorial, I will teach you how to search for data in the listview with ease by using MS Access database and C#. This method is the easiest way to retrieve data in the database and display it into the listview. It also has an automatic searching of data in the listview. This technique is very useful for you when you are a beginner in this field.
The complete source code is included you can download it and run it on your computer.
For any questions about this article. You can contact me @
Email – [email protected]
Mobile No. – 09305235027 – TNT
Or feel free to comment below.
Creating Application
Step 1
Open Microsoft Visual Studio 2015 and create a new windows form application for c#.
Step 2
Do the form just like shown below.
Step 3
Press F7 to open the code editor. In the code editor, add a namespace to accessOleDB
libraries
- using System.Data.OleDb;
Step 4
Establish a connection between C# and MS access database. After that, declare all the classes that are needed.- OleDbConnection con = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + Application.StartupPath + "/persondb.accdb");
- OleDbCommand cmd;
- OleDbDataAdapter da;
- DataTable dt;
- string sql;
Step 5
Create a method for retrieving data in the database.- private void load_data(string sql,ListView lst)
- {
- try
- {
- con.Open();
- cmd.Connection = con;
- cmd.CommandText = sql;
- da.SelectCommand = cmd;
- da.Fill(dt);
- lst.Items.Clear();
- foreach (DataRow r in dt.Rows)
- {
- var list = lst.Items.Add(r.Field<string>(1).ToString());
- list.SubItems.Add(r.Field<string>(2).ToString());
- list.SubItems.Add(r.Field<string>(3).ToString());
- }
- }
- catch (Exception ex)
- {
- MessageBox.Show(ex.Message);
- }
- finally
- {
- con.Close();
- da.Dispose();
- }
- }
Step 6
Write the following codes to display the data into the ListView in the first load of the form.- private void Form1_Load(object sender, EventArgs e)
- {
- sql = "SELECT * FROM tblperson";
- load_data(sql, listView1);
- }
Step 7
Write the following codes for searching data in the ListView.- private void textBox1_TextChanged(object sender, EventArgs e)
- {
- sql = "SELECT * FROM tblperson WHERE Name LIKE '%" + textBox1.Text + "%'";
- load_data(sql, listView1);
- }
Add new comment
- 945 views