让我先说一下,我只写了3-4个月的c#代码。
我正试图得到数据库是如何在Visual studio内访问的一个基本的了解,这样我就可以插入,更新和删除数据。我尝试了各种不同的测试,我想我已经得出结论,WPF的一些东西是OleDb不太喜欢的。我创建了2个相同的项目,一个使用Windows窗体,另一个使用WPF。Windows窗体版本的项目工作绝对良好,但WPF项目没有,给我错误
" ConnectionString属性尚未初始化"
我不知道如何解决这个问题。我已经在网上搜索了将近12个小时,但仍然一无所获。
这是WPF文件的原始代码。它与Windows窗体代码
相同public partial class MainWindow : Window
{
OleDbCommand cmd = new OleDbCommand();
OleDbConnection cn = new OleDbConnection();
OleDbDataReader dr;
public MainWindow()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
cn.ConnectionString = @"Provider = Microsoft.Jet.OLEDB.4.0; Data Source = C:UsersMarkBDocumentstesting.mdb";
cmd.Connection = cn;
loaddata();
}
private void loaddata()
{
listBox1.Items.Clear();
listBox2.Items.Clear();
listBox3.Items.Clear();
listBox4.Items.Clear();
try
{
string q = "select * from info";
cmd.CommandText = q;
cn.Open();
dr = cmd.ExecuteReader();
if(dr.HasRows)
{
while(dr.Read())
{
listBox1.Items.Add(dr[0].ToString());
listBox2.Items.Add(dr[1].ToString());
listBox3.Items.Add(dr[2].ToString());
listBox4.Items.Add(dr[3].ToString());
}
}
dr.Close();
cn.Close();
}
catch(Exception e)
{
cn.Close();
MessageBox.Show(e.Message.ToString());
}
}
private void listBox2_SelectedIndexChanged(object sender, EventArgs e)
{
ListBox l = sender as ListBox;
if(l.SelectedIndex != -1)
{
listBox1.SelectedIndex = l.SelectedIndex;
listBox2.SelectedIndex = l.SelectedIndex;
listBox3.SelectedIndex = l.SelectedIndex;
listBox4.SelectedIndex = l.SelectedIndex;
}
}
private void button1_Click(object sender, EventArgs e)
{
if ((textBox1.Text!="") && (textBox2.Text!=""))
{
string q ="insert into info (firstname,surname,address) values ('" + textBox1.Text + "','" + textBox2.Text + "','" + textBox3.Text +"')";
dosomething(q);
textBox1.Text = null;
textBox2.Text = null;
textBox3.Text = null;
}
}
private void dosomething(String q)
{
try
{
cn.Open();
cmd.CommandText = q;
cmd.ExecuteNonQuery();
MessageBox.Show("Data Saved");
cn.Close();
loaddata();
}
catch (Exception e)
{
cn.Close();
MessageBox.Show(e.Message.ToString());
}
}
private void button2_Click(object sender, EventArgs e)
{
if(listBox1.SelectedIndex !=-1)
{
string q = "delete from info where id =" + listBox1.SelectedItem.ToString();
dosomething(q);
}
}
}
如果有人能帮忙,我将不胜感激。我知道问题一定源于代码的连接方面
该错误提示在连接字符串传递给它之前的某个时刻正在调用连接。也许可以尝试在第一次实例化OleDbConnection对象时将连接字符串设置在顶部:
OleDbConnection cn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0; Data Source=C:\Users\MarkB\Documents\testing.mdb");
然后创建一个新的cmd对象,每次你需要它(而不是在顶部):
string query = "select * from somethingorother";
OleDbCommand cmd = new OleDbCommand(query, cn);