【问题标题】:Put content of access database into two listboxs将access数据库的内容放入两个listbox
【发布时间】:2016-03-03 19:30:12
【问题描述】:

您好,我有一个包含两个表的数据库:1.) Country (Table name: 2.) Website 每个国家/地区都有 1 个或多个网站。

我正在尝试制作一个 C# WindowsForm 应用程序,我希望用户首先从第一个 listbox1 中选择一个国家,然后所有网站都将基于数据库在第二个 listbox2 中。我不知何故无法显示所有在第一个文本框中使用 select 语句的国家:代码如下

try
{ 
    connection.Open();
    OleDbCommand command = new OleDbCommand();
    command.Connection = connection;
    command.CommandText = "SELECT CountryName FROM Countries ";
    //whenever you want to get some data from the database
    using (OleDbDataReader reader = command.ExecuteReader())
    {
        listBox.Items.Add(reader);
    }
    //OleDbDataReader reader   = command.ExecuteReader();
    connection.Close();
}
catch(Exception l)
{
    MessageBox.Show("Error:" + l);
}

此代码不显示列表框中的项目。

有人可以建议吗?

【问题讨论】:

    标签: c# database


    【解决方案1】:

    您可能希望从阅读器获取数据并将其转换为对象,然后再将其放入列表框中。您可以通过reader["columnname"] 获取每列的值。不要忘记您还需要将每个值转换为正确的类型,您可能会在System.Convert 中找到您需要的所有转换类型。

    考虑到您的情况,您应该能够做到

    using (OleDbDataReader reader = command.ExecuteReader())
    {
        while(reader.Read())
        {
            listBox.Items.Add(reader["CountryName"].ToString());
        }
    }
    

    【讨论】:

      【解决方案2】:

      您正在尝试将 OleDbDataReader 添加为列表框项,而不是使用它来读取数据,以下是如何使用它的示例:

      try
      {
          connection.Open();
          using (OleDbCommand command = new OleDbCommand())
          {
              command.Connection = connection;
              command.CommandText = "SELECT CountryName FROM Countries ";
              //whenever you want to get some data from the database
              using (OleDbDataReader reader = command.ExecuteReader())
              {
                  while (reader.NextResult())
                  {
                      listBox.Items.Add(reader.GetString(0));
                  }
              }
          }
      }
      catch (Exception l)
      {
          MessageBox.Show("Error:" + l);
      }
      finally
      {
          connection.Close();
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-05-27
        • 2019-07-16
        • 2016-08-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-02-08
        相关资源
        最近更新 更多