Click here to Skip to main content
15,895,011 members
Please Sign up or sign in to vote.
1.44/5 (2 votes)
See more:
Hello,

How to load data from database into listview in C#?
Posted
Updated 28-Jun-17 20:47pm

Hi.if your Data is provided By LINQToSQL classes and WPF.you can do following.i assumed that your mainWindow.xaml is :
XML
<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 :
C#
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.
 
Share this answer
 
v3
Hi,
Fill dataset with your data and pass it to below function-
C#
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.
 
Share this answer
 

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



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900