首先让我说我只编写C#约3-4个月。
我试图基本了解如何在Visual Studio中访问数据库,以便我可以插入,更新和删除数据。我已经尝试了各种不同的测试,我想我已经得出结论,关于WPF的东西,OleDb并不是很喜欢。我创建了两个相同的项目,一个使用Windows Forms,另一个使用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:\Users\MarkB\Documents\testing.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);
}
}
}
如果有人可以提供帮助,我们将不胜感激。我知道问题必须源于代码的连接方面
答案 0 :(得分:2)
错误表明在连接字符串传递给连接字符串之前的某个时刻正在调用连接。当您第一次实例化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);