3

How to display a DataTable in a ListView control in WPF?

abatishchev
  • 98,240
  • 88
  • 296
  • 433
kartal
  • 17,436
  • 34
  • 100
  • 145

3 Answers3

9
listView.ItemsSource = dataTable.DefaultView;
Jerod Houghtelling
  • 4,783
  • 1
  • 22
  • 30
  • 5
    That will display `System.Data.DataRowView` for every row in the table, and nothing else. It's necessary to define a view and columns in the `ListView.` – Robert Rossney Oct 12 '11 at 18:49
7

enter image description here
If you want a ListView like above, and if your DataTable has 3 columns with name "Date", "PCName", "Price" then between your tags add following code:

<ListView.View>
   <GridView>
     <GridViewColumn DisplayMemberBinding="{Binding Path=Date}"
                     Header="Date"
                     Width="100"/>
     <GridViewColumn DisplayMemberBinding="{Binding Path=PCName}"
                     Header="Computer No."
                     Width="100"/>
     <GridViewColumn DisplayMemberBinding="{Binding Path=Price}"
                     Header="Amount (Tk)"
                     Width="100"/>
   </GridView>
</ListView.View>
Ehsan
  • 767
  • 7
  • 18
Towhid
  • 1,920
  • 3
  • 36
  • 57
1

*Convert listview to datatable in c#* Just iterate the entire listview table. Here is the code,

private DataTable ConvertList_To_Datatable(ListView lvDetails)
       {
           DataTable dtTable = new DataTable("ExportToPdf");
           if (lvDetails.Items.Count < 1)
           {
               return dtTable;
           }
           else
           {
               for (int ncount = 0; ncount <= lvDetails.Columns.Count-1; ncount++)
               {
                   DataColumn dtColumn =new DataColumn(lvDetails.Columns[ncount].Text);
                   dtTable.Columns.Add(dtColumn);
               }
           }          
           for (int nRowCount = 0; nRowCount <= lvDetails.Items.Count - 1; nRowCount++)
           {
               DataRow dtRow = dtTable.NewRow();
               for (int nItem = 0; nItem <=lvDetails.Items[nRowCount].SubItems.Count - 1; nItem++)
               {                    
                   dtRow[lvDetails.Columns[nItem].Text] = lvDetails.Items[nRowCount].SubItems[nItem].Text;

               } dtTable.Rows.Add(dtRow);

           } return dtTable;

       }

Just try this .It works If any dout .U can reach me at prinsuyakob20@gmail.com

Botz3000
  • 39,020
  • 8
  • 103
  • 127
Prinsu J
  • 27
  • 1
  • 7
    This one has me scratching my head. Why, instead of displaying what is in a datatable in a listview, which is what is asked, do you offer a means to fetch the data of an already populated listview into that datatable? – Richard Robertson Aug 04 '15 at 05:57