c#在多种形式中使用MS access数据库

本文关键字:MS access 数据库 多种形式 | 更新日期: 2023-09-27 18:13:14

我制作了一个包含3个表单的程序。我已经使用了微软访问数据库的第一种形式,它完美地工作在这里是我使用的代码。

       public partial class newRegisteration : Form
{
    private OleDbConnection connection = new OleDbConnection();
    public newRegisteration()
    {
        InitializeComponent();
        connection.ConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:'Users'OmarS_000'Documents'Visual Studio 2015'Projects'School System'School System'School.accdb;
    Persist Security Info=False;";
    }
    private void button1_Click(object sender, EventArgs e)
    {
        try
        {
            connection.Open();
            OleDbCommand command = new OleDbCommand();
            command.Connection = connection;
            command.CommandText = "INSERT into School ([Name], [Age], [Grade], [Class]) VALUES('" + nameTextBox2.Text + "', '" + ageTextBox2.Text + "', '" + gradeTextBox2.Text + "', '" + classTextBox2.Text + "') ";
            command.ExecuteNonQuery();
            MessageBox.Show("Data Saved");
            connection.Close();
        }
        catch (Exception ex)
        {
            MessageBox.Show("Error" + ex);
            Clipboard.SetText(ex.ToString());
        }
    }        
}

现在在第二个表单中,当我将网格视图数据库从数据源拖动到表单时,它不工作,尽管它与第一个表单一起工作。我试着写代码来调用数据库的网格视图,但它没有工作太我得到的是数据库的空列,没有代码写在代码页。当我复制代码并修改它以与新表单匹配时,它会得到意外处理程序错误。那么我该如何解决这个问题呢?我如何使用数据库与相同的连接不止一次?

PS:我试图做另一个连接到同一个数据库不工作,

编辑:第二个表单代码
      private void CurrentStudents_Load(object sender, EventArgs e)
    {                         
        using (OleDbConnection connection2 = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:'Users'OmarS_000'Documents'Visual Studio 2015'Projects'School System'School System'School.accdb;Persist Security Info=False;")) 
        {
            OleDbCommand cmd = new OleDbCommand("Select * from School", connection2);
            OleDbDataAdapter olda = new OleDbDataAdapter(cmd);
            DataTable dt = new DataTable();
            olda.Fill(dt);
            schoolDataGridView.DataSource = dt;
            schoolDataGridView.AutoGenerateColumns = true;
        }
    }

c#在多种形式中使用MS access数据库

您的数据库可能锁定在其中一个表单上。你应该尝试在USING块中访问你的连接,这样你就不需要显式地关闭或处置你的连接对象。

using (OleDbConnection  connection = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:'Users'OmarS_000'Documents'Visual Studio 2015'Projects'School System'School System'School.accdb;Persist Security Info=False;"))
            {
                connection.Open();
                //Your code goes here
            }