有关"ConnectionString 属性尚未初始化"的一点困惑
问题是这样的:
想实现功能:当form1load时,form2.show()被触发,然后显示出一个连接数据库的窗体,里面有服务器名、数据库名、用户名和密码四项,把四个textbox的text分别作为connString(数据库连接字符串)的Data Source、Initial Catalog、User Id和Password的值。
private void Form1_Load(object sender, EventArgs e)
{
Form6 form = new Form6();
form.ShowDialog();
if (form.DialogResult == DialogResult.OK)
{
connString = "Data Source = " + form.textBox1.Text +
";Initial Catalog = " + form.textBox2.Text +
";User Id = " + form.textBox3.Text +
";Password = " + form.textBox4.Text + ";Integrated Security = True";
MessageBox.Show("成功连接数据库!");
UpdateTreeView();
}
else
this.Close();
个人觉得这个思路还正确,可不能解决在执行如下代码时的这个问题:
public static string connString;
SqlConnection conn = new SqlConnection(connString);
................................
public void UpdateTreeView()
{
string sqlstr = "select depart_fullname from department";
SqlDataAdapter da = new SqlDataAdapter(sqlstr, conn);
DataSet ds = new DataSet();
int myRowCount = da.Fill(ds, "department");#会在此处报错“ConnectionString 属性尚未初始化”
....
}
------解决方案--------------------
你这个conn必须用之前重新初始化.
conn=new SqlConnection(connString);
string sqlstr = "select depart_fullname from department";
SqlDataAdapter da = new SqlDataAdapter(sqlstr, conn);
DataSet ds = new DataSet();
int myRowCount = da.Fill(ds, "department");#会在此处报错“ConnectionString 属性尚未初始化”
....