从DataBase检索数据并填充列表

时间:2010-12-22 20:54:43

标签: .net wpf database list datatable

public List<Item> ListItemCollection;  

String connString = "SERVER=;" +
          "DATABASE=;" +
          "UID=;" +
          "PASSWORD=;"; 


private void GetItems()
{

String query = @"myQuery";
DataTable theTable = new DataTable();

using (MySqlConnection conn = new MySqlConnection(connString))
            {

                MySqlDataAdapter da = new MySqlDataAdapter(query, conn);
                MySqlCommand command = new MySqlCommand(query);

                da.Fill(theTable); // here all works fine.

                using (MySqlDataReader reader = command.ExecuteReader()) 
                {
                             /// At this point throws the exception .....

                    // Loop through each record.
                    while (reader.Read())  
                    {
                        ListItemCollection.Add(new Item());
                    }
                }

            }
}

theTable.Columns.Clear();
theTable.Rows.Clear();
theTable.Clear();

ListItemCollection.Items.Clear();
DataContext = ListItemCollection;
ListItemCollection.Items.Refresh();

内部异常.. {“连接必须有效且开放。”}

如果我使用DataAdapter并填充dataTable“da.Fill(theTable)”事情工作相当顺利,也许有办法将数据从DataTable传输到List? theTable.Columns.List?

所有这一切的最终目的是,我想将分组添加到ListControl(ListBox,DataGrid,ListView),设置DataContext代码隐藏&amp;在XAML中绑定ItemSource。也许您可以对数据表的列表进行分组?

3 个答案:

答案 0 :(得分:0)

您必须在某个时刻打开MySqlConnection:

conn.Open();

ExecuteReader();

之前建议

这将确保您不会获得Connection must be valid and open例外。

答案 1 :(得分:0)

为什么不直接绑定到您正在填充的数据表?看起来你也在代码隐藏中这样做了。使用xaml会更清洁......

您可以填充数据表然后在读取器上出错的原因是datadapter可以管理自己的连接,而datareader需要显式引用连接对象。

顺便说一句。你以这种方式两次击中数据库。

答案 2 :(得分:0)

我添加了一个CollectionViewSource,其中包含一个groupDescription,我的控制项源的getdefaultview。

myView =(CollectionView)CollectionViewSource.GetDefaultView(myItemsControl.ItemsSource);        PropertyGroupDescription groupDescription = new PropertyGroupDescription(“order”);        myView.GroupDescriptions.Add(groupDescription);

在这里找到了这个例子:

http://blogs.msdn.com/b/brunoterkaly/archive/2009/07/16/wpf-xaml-listboxes-with-a-grouping-capability.aspx

相关问题