【问题标题】:C# Using MS Acess Database in Multiple FormsC# 以多种形式使用 MS Access 数据库
【发布时间】:2016-10-16 21:02:08
【问题描述】:

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

       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# database forms ms-access


    【解决方案1】:

    您的数据库可能被锁定在其中一种表单上。您应该尝试在 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
                }
    

    【讨论】:

    • 我将此代码用于第一个表单,它照常工作,但第二个表单现在仍然存在问题。
    • 很抱歉一开始没用,但现在效果很好:D 谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多