【问题标题】:Retrieve data from DataBase and Fill a List从数据库中检索数据并填写列表
【发布时间】:2011-05-29 15:44:30
【问题描述】:
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?表.列.列表?

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

【问题讨论】:

    标签: .net wpf database list datatable


    【解决方案1】:

    你必须在某个时候打开你的 MySqlConnection:

    conn.Open();
    

    在你的ExecuteReader();之前建议

    这将确保您不会收到Connection must be valid and open 异常。

    【讨论】:

    • 我的怀疑(多年后我试图规范化潜在的欺骗)是这是 DataAdapter 打开和关闭连接以及随后的 conn.Open() 进入不受支持的情况MySqlDbConnection 代码中的状态 - 但我没有要测试的 MySql 堆栈。自我回答这个问题可能对这个泡菜中的其他人有用,虽然....
    【解决方案2】:

    为什么不直接绑定到您正在填写的数据表?看起来您也在代码隐藏中执行此操作。使用 xaml 会更干净...

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

    顺便说一句。您以这种方式访问​​数据库两次。

    【讨论】:

    • 好吧,谢谢,我只是想提供更多关于填充表的信息。无论如何,我需要对 datagrid itemsource 进行分组,为此,我需要填写一个 List。有没有办法在没有任何 ListCollection 的情况下完成分组?其实我只是设置 DataContext = theTable。
    • 我相信如果你将你的表绑定到 xaml 中的集合视图,然后将你的数据网格绑定到你能够然后分组的那个......到目前为止我只使用过一次数据网格,它花了很多时间设置让它以我想要的方式工作。这种情况下的分组实际上是通过collectionview
    【解决方案3】:

    我添加了一个带有 groupDescription 的 CollectionViewSource,getdefaultview 我的控件 itemsource。

    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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-12-09
      • 2017-05-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多