【发布时间】: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