[dba-VB] How to set password for a DataTable(Adapter)'s connection?

Gustav Brock Gustav at cactus.dk
Thu Feb 21 06:33:41 CST 2008


Hi all

OK, I found out. The DataTableAdapter has a Connection which has a ConnectionString property, and you can modify that using the SqlConnectionStringBuilder.

Here is for my targetDataTableAdapter:

  Console.WriteLine(targetDataTableAdapter.Connection.ConnectionString);

  // Define password.
  string password = (string)"YourSecretPassword";
  // Retrieve connection string.
  SqlConnectionStringBuilder sqlConnectionStringBuilder = new SqlConnectionStringBuilder(); 
  sqlConnectionStringBuilder.ConnectionString = targetDataTableAdapter.Connection.ConnectionString;
  // Apply password to connection string.
  sqlConnectionStringBuilder.Password = password;
  // Apply the modifed connection.
  targetDataTableAdapter.Connection = new SqlConnection(sqlConnectionStringBuilder.ToString());

  Console.WriteLine(targetDataTableAdapter.Connection.ConnectionString);

/gustav

>>> Gustav at cactus.dk 20-02-2008 20:38 >>>
Hi all

Is it possible at runtime to set the password for the connection when you open a DataTableAdapter?

I have code like this:

            // DataTableAdapter to copy from.
            RemoteTableAdapters.CompanyTableAdapter sourceDataTableAdapter =
                new RemoteTableAdapters.CompanyTableAdapter();
            Remote.CompanyDataTable sourceDataTable;

            // DataTableAdapter to copy to.
            LocalTableAdapters.CompanyTableAdapter targetDataTableAdapter =
                new LocalTableAdapters.CompanyTableAdapter();
            Local.CompanyDataTable targetDataTable;

            // DataTable for source.
            sourceDataTable = sourceDataTableAdapter.GetData();
            // DataTable for target.
            targetDataTable = targetDataTableAdapter.GetData();

If the underlying database connection needs a password, the code fails at the line with GetData().

Would I need to go all the way back to read the ConnectionString, modify this, and reapply? How?
Or is there a more clever method? At best like:

          targetDataTableAdapter.Connection.SetPassword("secret");

/gustav





More information about the dba-VB mailing list