0

I'm getting an error when dragging my usercontrol with a sql connection onto my form. The reason for the exception is I'm trying to access the sql connection at design time. How can I change my usercontrol that I don't get this error anymore? Where to store the connection string (in a seperate file or somewhere else ??) and how to acces it from my control?

My usercontrol class code snippet

    SqlConnection sqlConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["REINVENT.Quality.Properties.Settings.REINVENT_QualityConnectionString"].ConnectionString);
    SqlCommand cmd = new SqlCommand();

    //The SQL connection causes the error, how to solve?

Edit app.config

    <?xml version="1.0" encoding="utf-8" ?>
 <configuration>
<configSections>
</configSections>
<connectionStrings>
    //mystring
</connectionStrings>
<startup> 
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>

Sybren
  • 970
  • 2
  • 14
  • 44
  • 1
    [What is a NullReferenceException and how do I fix it?](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – Soner Gönül Oct 08 '14 at 07:34
  • I know it's a NullReferenceException but where to store my sqlconnection? The link provided doesn't provide a solution for me. And when I comment the connectionstring and move the usercontrol onto the form and uncomment the connectstring it works. – Sybren Oct 08 '14 at 07:37
  • Can you share us your `web.config` to help you – MrMins Oct 08 '14 at 07:40

2 Answers2

0

Try:

Using (SqlConnection sqlConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["REINVENT.Quality.Properties.Settings.REINVENT_QualityConnectionString"].ConnectionString))
{
    SqlCommand cmd = new SqlCommand();
    //Do my sqlcommand stuff
}

Have a look at the using statement for dealing with SqlConnections

user1
  • 15,594
  • 12
  • 96
  • 166
0

You should Open your sqlConnection first.

XardasLord
  • 1,706
  • 2
  • 18
  • 37
  • 1
    How do you know he/she doesn't? – Soner Gönül Oct 08 '14 at 07:41
  • @SonerGönül We read the code he provided. See any open there? I do not. – TomTom Oct 08 '14 at 07:44
  • @TomTom Exactly. We can't know that. That's why it is not right to give an answer based on an information that we _don't_ know. `Open()` method doesn't initialize any information in `SqlConnection` that's why there is no way to solve `NullReferenceException` either. – Soner Gönül Oct 08 '14 at 07:48
  • @SonerGönül I am sorry to say, but this is a stupid behavior. He clearly says "this is my code, i have a problem". Assuming he is sapbatging the question is not goin to be productive. – TomTom Oct 08 '14 at 07:53