How to bind data table with listview?

Total Post:412

Points:2888
C# 
C#
 17926  View(s)
Ratings:
Rate this:
Hello Everyone,
I'm facing a problem since last night, actually I want to bind data table with asp listview control but I don't have an idea how to do it. Please resolve my problem as soon as possible. Please paste code if possible.

Thanks in advance!!
  1. Post:604

    Points:4228
    Re: How to bind data table with listview?

    Hello Pravesh

    like gridview binding we can't bind listview so for binding listview take help of below code.


    private void btnDisplay_Click(object sender, EventArgs e)
            {
                // Create Data Table for MS-Office 2007 or 2003
                System.Data.DataTable dtExcel = new System.Data.DataTable();
                //DataTable Name
                dtExcel.TableName = "MyExcelData";
                //Path of excel file in local drive
                string SourceConstr = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source='F:\avi\information.xlsx';Extended Properties= 'Excel 8.0;HDR=Yes;IMEX=1'";
                //connectin
                OleDbConnection con = new OleDbConnection(SourceConstr);
                //Query string
                string query = "Select * from [Sheet1$]";
                //DataAdapter object
                OleDbDataAdapter data = new OleDbDataAdapter(query, con);
                //fill record into DataTable
                data.Fill(dtExcel);
                // Attach Subitems to the ListView
                listView1.Columns.Add("Name", 100, HorizontalAlignment.Left);
                listView1.Columns.Add("Address", 100, HorizontalAlignment.Left);
                listView1.Columns.Add("Contact", 100, HorizontalAlignment.Left);
                listView1.Columns.Add("Email Id", 100, HorizontalAlignment.Left);
                // Clear the ListView control
                listView1.Items.Clear();
                // Display items in the ListView control
                for (int i = 0; i < dtExcel.Rows.Count; i++)
                {
                    DataRow drow = dtExcel.Rows[i];
                    // Only row that have not been deleted
                    if (drow.RowState != DataRowState.Deleted)
                    {
                        // Define the list items
                        ListViewItem lvi = new ListViewItem(drow["Name"].ToString());
                        lvi.SubItems.Add(drow["Address"].ToString());
                        lvi.SubItems.Add(drow["Contact"].ToString());
                        lvi.SubItems.Add(drow["Email Id"].ToString());
                        // Add the list items to the ListView
                        listView1.Items.Add(lvi);
                    }
                }  
            }


    I hope it might be resolve your problem.

      Modified On Mar-29-2018 05:21:49 AM

Answer