运行时分配连接字符串不起作用

时间:2013-06-12 12:24:35

标签: c# winforms connection-string

我有以下情景

SqlConnection  sqlMdfCon = new SqlConnection();
sqlMdfCon.ConnectionString = "Data Source=" + txtDataSource.Text + ";Initial Catalog=" + txtDatabase.Text + ";Database=" + txtDatabase.Text + ";User ID=" + txtUserID.Text + ";Password=" + txtPassword.Text + ";Integrated Security=False";
if (sqlMdfCon.State == ConnectionState.Closed)
{
    sqlMdfCon.Open();
}
dTable = sqlMdfCon.GetSchema("Tables"); 
 foreach (DataRow DRow in dTable.Rows)
 {

    if (DRow["TABLE_TYPE"].ToString() == "TABLE" || DRow["TABLE_TYPE"].ToString() == "VIEW" || DRow["TABLE_TYPE"].ToString() == "BASE TABLE")
    {
       intPos = DRow["TABLE_NAME"].ToString().LastIndexOf("FilterDatabase");
       lstTables.Items.Add(DRow["TABLE_NAME"]); // Getting error here
    }
 }

以下是例外

ConnectionString property is not initialized

为什么我得到这个,即使我已正确地将连接字符串分配给连接?

1 个答案:

答案 0 :(得分:0)

试试这个:

SqlConnection  sqlMdfCon = new SqlConnection(sqlMdfCon.ConnectionString = "Data Source=" +     txtDataSource.Text + ";Initial Catalog=" + txtDatabase.Text + ";Database=" + txtDatabase.Text + ";User ID=" + txtUserID.Text + ";Password=" + txtPassword.Text + ";Integrated Security=False";);
sqlMdfCon.Open();
dTable = sqlMdfCon.GetSchema("Tables");

顺便说一下,我会添加一个try / finally语句来正确处理连接对象。我希望你不是像连接字符串那样构建你的查询......