Click here to Skip to main content
15,901,283 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
above mentioned error appears....in following line.

Dim con As New SqlConnection(ConfigurationManager.ConnectionStrings("Data Source=KARANDE\sqlexpress;Initial Catalog=nitink;Integrated Security=True").ConnectionString)
Posted

The reason is that the ConfigurationManager.ConnectionStrings returns a System.Configuration.ConnectionStringSettingsCollection as explained here
http://msdn.microsoft.com/en-us/library/system.configuration.configurationmanager.connectionstrings.aspx[^]

The indexer property of System.Configuration.ConnectionStringSettingsCollection takes either a numerical index or the Connection string name as the index as explained here http://msdn.microsoft.com/en-us/library/c6t3b6f3.aspx[^], whereas in the above code the ConnectionString itself is used as the index to the indexer property which returns a null (or nothing in VB.NET). So accessing the .ConnectionString property on a null object throws the above error.

To avoid this error either use connection name as the index or loop through the ConfigurationManager.ConnectionStrings collection and compare the required property of the connection string as given in the example at http://msdn.microsoft.com/en-us/library/system.configuration.configurationmanager.connectionstrings.aspx[^]
 
Share this answer
 
v2
Normally, you would try to read a connection string from Web.Config by using its name:
XML
<connectionStrings>
  <add name="LoggingDatabase" connectionString="Database=XXX;Data Source=XXX;Initial Catalog=XXX;Integrated Security=True"/>

C#
/// <summary>
/// Gets the connection string for the Logging database
/// </summary>
public static string Logging { get { return ConfigurationManager.ConnectionStrings["LoggingDatabase"].ConnectionString; } }


You appear to be trying to retrieve a connection string by using the string itself as the name...which is why you get the error, it doesn't exist so it returns null.
 
Share this answer
 
Comments
VJ Reddy 7-Jun-12 11:02am    
Good answer. 5!
I do not understand why you use such a weird construction. A connection string is a string, and the SQLConnection can take a string (with the meaning of the connection string) as a parameter. And you already know the (hard-coded) connection string. So do:
VB
Dim connectionString as string = "Data Source=KARANDE\sqlexpress;Initial Catalog=nitink;Integrated Security=True"
Dim con As SqlConnection = New SqlConnection(connectionString)

By the way, it is good practise to store the connection string somewhere and read it from there, e.g. in a configuration file.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900