简体   繁体   中英

Runtime assigning connection string not working

I am having following scenario

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
    }
 }

Following is the exception

ConnectionString property is not initialized

Why i am getting this even i have assigned the connection string properly to connection ?

Try this:

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");

By the way, I'd add a try/finally statement to dispose connection object properly. And I hope you're not constructing your queries the same that connection string...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM