Click here to Skip to main content
12,291,230 members (62,656 online)
Rate this:
 
Please Sign up or sign in to vote.
See more: C#
Hello,

How to load data from database into listview in C#?
Posted 14-Feb-13 23:30pm
Rate this: bad
 
good
Please Sign up or sign in to vote.

Solution 1

Hi.if your Data is provided By LINQToSQL classes and WPF.you can do following.i assumed that your mainWindow.xaml is :
<Grid>
        <ListView x:Name="myListView" Background="Gray" FlowDirection="RightToLeft" Loaded="myListView_Loaded">
            <ListView.View>
                <GridView AllowsColumnReorder="True" >
                    <GridView.Columns>
                        <GridViewColumn Header="ProductName" Width="150" DisplayMemberBinding="{Binding ProductName}"/>
                        <GridViewColumn Header="Unit Price" Width="100" DisplayMemberBinding="{Binding UnitPrice}"/>
                    </GridView.Columns>
                </GridView>
            </ListView.View>
        </ListView>
    </Grid>
and you must add a LINQTOSqlClasses object to your project and place tables of NorthWind Database on it by Drag and Drop.
your mainWindow.cs is :
private void myListView_Loaded(object sender, RoutedEventArgs e)
{
//MainDataContext is the name of LINQTOSQL object that you add to your project
MainDataContext context=new MainDataContext();
myListView.ItemsSource=context.Products.ToList();
 
}

GoodLuck.
  Permalink  
v3
Rate this: bad
 
good
Please Sign up or sign in to vote.

Solution 2

Hi,
Fill dataset with your data and pass it to below function-
private void LoadList(DataSet _DataSet)
{
    // Get the table from the data set
    DataTable dtable = _DataSet.Tables["table_name"];
 
    // Clear the ListView control
    listView1.Items.Clear();
 
    // Display items in the ListView control
    for (int i = 0; i < dtable.Rows.Count; i++)
    {
        DataRow drow = dtable.Rows[i];
 
        // Only row that have not been deleted
        if (drow.RowState != DataRowState.Deleted)
        {
            // Define the list items
            ListViewItem lvi = new ListViewItem(drow["column1"].ToString());
            lvi.SubItems.Add (drow["column2"].ToString());
            lvi.SubItems.Add (drow["column3"].ToString());
            lvi.SubItems.Add (drow["column4"].ToString());
 
            // Add the list items to the ListView
            listView1.Items.Add(lvi);
        }
    }
}

Good luck.
  Permalink  

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Top Experts
Last 24hrsThis month


Advertise | Privacy | Mobile
Web02 | 2.8.160518.1 | Last Updated 16 Nov 2013
Copyright © CodeProject, 1999-2016
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100