关于SelectCommand.Connection 属性尚未初始化的问题
我想把datagridview里的数据存储在access里面,编了一段程序,但是出现SelectCommand.Connection 属性尚未初始化的错误提示,请问我应该还加什么命令,加在哪里
OleDbConnection oleCon;
OleDbDataAdapter oleDa;
//刷新dataGridView1数据显示
void DataRefresh()
{
oleCon = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0; Data Source=pinch.mdb" );
oleDa = new OleDbDataAdapter("Select * From [数据]", oleCon);
DataSet ds = new DataSet();
oleDa.Fill(ds);
dataGridView1.DataSource = ds.Tables[0].DefaultView;
}
//将dataGridView1数据操作更新到数据库
private Boolean dbUpdate()
{
string strOdb = "Select * From [数据]";
DataTable dtUpdate = new DataTable();
oleDa = new OleDbDataAdapter(strOdb, oleCon);
oleDa.Fill(dtUpdate);
dtUpdate.Rows.Clear();
DataTable dtShow = new DataTable();
dtShow = (DataTable)dataGridView1.DataSource;
for (int i = 0; i < dtShow.Rows.Count; i++)
{
dtUpdate.ImportRow(dtShow.Rows[i]);
}
try
{
this.oleCon.Open();
OleDbCommandBuilder CommandBuilder;
CommandBuilder = new OleDbCommandBuilder(oleDa);
oleDa.Update(dtUpdate);
oleCon.Close();
}
catch (Exception ex)
{
MessageBox.Show("数据库操作失败: " + ex.Message.ToString(), "提示",
MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
return false;
}
dtUpdate.AcceptChanges();
return true;
}
//保存数据操作到数据库
private void button3_Click(object sender, EventArgs e)
{
if (button3.Text == "完成")
{
if (dbUpdate())
{
MessageBox.Show("完成");
}
button3.Text = "编辑";
}
else
{
DataRefresh();
button3.Text = "完成";
}
}
------解决方案--------------------
oleCon.Open()没看到
------解决方案--------------------
给个Access数据库操作类你
C# code
//属性:数据库链接对象
private static OleDbConnection conn;
public static OleDbConnection Conn
{
get
{
try
{
string connstr = "Provider = Microsoft.Jet.OLEDB.4.0;Data Source=" + "" + Application.StartupPath + @"\Database.mdb";
if (conn == null)
conn = new OleDbConnection(connstr);
if (conn.State == ConnectionState.Closed)
conn.Open();
if (conn.State == ConnectionState.Broken)
{
conn.Close();
conn.Open();
}
return conn;
}
catch (Exception ex)
{
throw;
}
}
}