Fill List view from database

Hi to all.

In this post we make code for populate list view from database.

first we take one list view and name them listdata. and set in form with require height and width.

listview
listview

now make one function FillList() to populate listview.

        private void FillList()
        {
            try
            {
                //use dbhelper class to fill datatable from database.
                DbHelper Db = new DbHelper();
                //make query string .
                string sQry = "Select * from Employee";
                //call function for fill datatable.
                DataTable Dt = Db.FillDataTable(sQry);
                //set property for view
                ListData.View = View.Details;
                //add columns in listview
                if (
ListData.Columns.Count == 0)
                {
                    
ListData.Columns.Add("Id", 50, HorizontalAlignment.Left);
                    
ListData.Columns.Add("Name", 100, HorizontalAlignment.Left);
                    
ListData.Columns.Add("Company", 150, HorizontalAlignment.Left);
                }
                //clear list view items.
                
ListData.Items.Clear();
                //loop for fill data in listview
                foreach (DataRow Dr in Dt.Rows)
                {
                    ListViewItem lv = new ListViewItem(Dr["Id"].ToString());
                    lv.SubItems.Add(Dr["Name"].ToString());
                    lv.SubItems.Add(Dr["Company"].ToString());
                    
ListData.Items.Add(lv);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message.ToString());
            }
        }

This function fill data from database. we can see in win form.

In function i use Db.FillDataTable(sQry); function that we discus in previous post. that return datatable from database.

I add columns that specify proper view in list view.and after add data in listviewitem, to populate list view.

Comments

Popular posts from this blog

Populate combo box for month and year in c#

How to get month days count from date or month and year

CRUD Operations in win form application with access database