如何在C#中将数据从数据库加载到listview [英] How to load data from database into listview in C#

查看:242
本文介绍了如何在C#中将数据从数据库加载到listview的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你好,



如何在C#中将数据从数据库加载到listview中?

Hello,

How to load data from database into listview in C#?

推荐答案

你好如果您的数据由LINQToSQL类和WPF提供。您可以执行以下操作。假设您的mainWindow.xaml是:

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>



你必须添加一个LINQTO SqlClasses对象你的项目并通过拖放将NorthWind数据库的表放在它上面。

你的mainWindow.cs是:


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。



GoodLuck.



使用您的数据填充数据集并将其传递给下面的函数 -

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.


这篇关于如何在C#中将数据从数据库加载到listview的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆