标题:C#连接ACCESS数据库,显示到dataGridView表格?
取消只看楼主
qcxabc
Rank: 1
等 级:新手上路
帖 子:4
专家分:5
注 册:2011-9-15
结帖率:0
已结贴  问题点数:20 回复次数:1 
C#连接ACCESS数据库,显示到dataGridView表格?
用C#写了一段程序,想把access数据库的数据显示到dataGridView表格中,下面是一段代码没有报错,就是dataGridView表格中不显示数据,不知道怎么回事?
public partial class CustomerEditor : Form
  {
  private OleDbConnection connection;
  public CustomerEditor()
  {
  InitializeComponent();
  }

   

  private void menuDataconnect_Click(object sender, EventArgs e)
  {
  Connect();
  }
  public void Connect()
  {
  if (DialogopenFile.ShowDialog(this) == DialogResult.OK)
  {
  try
  {
  string connectionString = string.Format(
  "Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};User ID=;Password=;", DialogopenFile.FileName);
   
  OleDbConnection newConnection = new OleDbConnection(connectionString);
  newConnection.Open();
  Connection = newConnection;


  }
  catch (Exception ex)
  {
  HandleException("A connection could not be made", ex);
  }
   
  }
  }

  private void HandleException(string p, Exception ex)
  {
  MessageBox.Show(this, string.Format("{0}\n{1}:{2}", p, ex.GetType().ToString(), ex.Message));
  }
  public OleDbConnection Connection
  {
  get
  {
  return connection;

  }
  set
  {
  disconnection();
  connection = value;
  }

  }
  public void disconnection()
  {
  if (connection != null)
  {
  if (connection.State != ConnectionState.Closed)
  connection.Close();
  connection = null;
  }
  }
  protected void Dispos(bool disposing1)
  {
  disconnection();
  if (disposing1)
  {
  if (components != null)
  {
  components.Dispose();
  }
  }
  base.Dispose(disposing1);
  }

  private void menuDataload_Click(object sender, EventArgs e)
  {
  LoadData();
  }

  public void LoadData()
  {
  if (connection == null)
  {
  MessageBox.Show(this, "you must connect to a database");
  return;

  }

  OleDbCommand command = connection.CreateCommand();
  OleDbDataAdapter adapter = new OleDbDataAdapter(command);
  try
  {
   
   = "Customers";
   = CommandType.TableDirect;
   
  DataSet dataset = new DataSet();
  adapter.Fill(dataset);
  dataGridCustomers.DataSource = dataset;
   
  }
  catch (Exception ex)
  {
  HandleException("the data could not be loaded", ex);

  }
  finally
  {
  if (adapter != null)
  adapter.Dispose();
  if (command != null)
  command.Dispose();
  }

  }
  }
}
搜索更多相关主题的帖子: 数据库 private 数据显示 access 
2011-09-15 09:31
qcxabc
Rank: 1
等 级:新手上路
帖 子:4
专家分:5
注 册:2011-9-15
得分:0 
主要是调试的也没发现什么问题,就是不显示数据。不知道怎么回事?
2011-09-15 09:32



参与讨论请移步原网站贴子:https://bbs.bccn.net/thread-349952-1-1.html




关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.025266 second(s), 8 queries.
Copyright©2004-2024, BCCN.NET, All Rights Reserved