Add items to listview using Reader class in C#


Welcome to another code poetry post. Suppose you have a database application and want to display those records from database to a listview, what should you know?. This tutorial will help you.

C# has a neater ways to code with ListView and Database. List View Control work much faster than Grid. Let’s do it with fun.

For this C# project, we need a connection string and method to connect the database, command object which can be used to fetch records from the table. We are already discussed about OLEDB connections (if you are not familiar, attempt a search).

Secondly we need a Reader object which let you move through the records, this method proved to be faster than data views.

How to add items

We are filling listView items with values using following ,
  1. Create List of Strings and gather items
  2. We create ListViewItem object and add those List we are collected to it.
  3. Final step we just fill ListView control with ListViewItem object .

The code

We used a connection method for this project, and called using connect, the rest of the code look like

public void MediceineList(ListView ls, List filter)
        {
            string qstr;
            List lst=new List();

            if (filter[0] == “All”) {
                qstr = “Select * from new_Medicines”;
            }
            else
            {
                qstr = “Select * from new_Medicines where ” + filter[1] + ” =” + filter[0];
            }
            Rs = new OleDbCommand(qstr , conn);

            OleDbDataReader dr = Rs.ExecuteReader(System.Data.CommandBehavior.CloseConnection);
            int i = 1;
            while (dr.Read())

            {
                lst.Add(i++.ToString ());
                lst.Add(dr.GetValue(0).ToString());//Pcode
                lst.Add(dr.GetValue(1).ToString ());//PName
                ListViewItem lsvitm = new ListViewItem(lst.ToArray() );
                ls.Items.Add(lsvitm);
                lst.Clear();
            }
            ls.Items.Add(“”);
            ls.Items.Add(“TOTAL: “+ i);
        }
        }

I also used some filtering capabilities. Lets finish the final code and test the application.
 List fltr;

            fltr = new List();
            fltr.Add(“All”);
            db.MediceineList(listView1,fltr);

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.