3

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

3 Answers 3

9
listView.ItemsSource = dataTable.DefaultView;
Sign up to request clarification or add additional context in comments.

1 Comment

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.
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>

1 Comment

The rows are not able to select when using gridview in listview
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 [email protected]

1 Comment

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?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.