0

I have an usercontrol with a sql connection string. The connectionstring is okay because I have tested it and I was able to get data from the database. Every time when I try to drag the usercontrol onto my Windows Form I get a NullReferenceException : Object reference not set to an instance of an object. How can I solve this?

Usercontrol class

    public partial class incidentCategoryMaintenance : UserControl
{
    SqlConnection sqlConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["REINVENT.Quality.Properties.Settings.REINVENT_QualityConnectionString"].ConnectionString); // causes the exception
    SqlCommand cmd = new SqlCommand();

    public incidentCategoryMaintenance()
    {
        InitializeComponent();
    }

    private void incidentCategoryMaintenance_Load(object sender, EventArgs e)
    {          

        String query = "SELECT Max(IncIncidentCategory) FROM IncIncidentCategory;";
        cmd.Connection = sqlConnection;
        cmd.CommandText = query;

        sqlConnection.Open();
        String maxIncidentId = cmd.ExecuteScalar().ToString();
        sqlConnection.Close();

        if (maxIncidentId == "")
        {
            incidentCategoryTextBox.Text = "0";
        }
        else
            incidentCategoryTextBox.Text = (Convert.ToInt32(maxIncidentId) + 1).ToString();
   }

    private void saveCategoryButton_Click(object sender, EventArgs e)
    {
      //  String query =
    }


}

App.config

   <?xml version="1.0" encoding="utf-8" ?>
    <configuration>
<configSections>
</configSections>
<connectionStrings>
    // here's my connection string
</connectionStrings>
<startup> 
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>

Sybren
  • 1,071
  • 3
  • 17
  • 51
  • I guess, what you have to check for [design time](http://stackoverflow.com/q/2427381/1997232) to prevent some code from executing in winforms designer. – Sinatr Oct 07 '14 at 12:14
  • 1
    You getting error while trying to access `ConfigurationManager.ConnectionStrings` in design time which is null at this place. – Renatas M. Oct 07 '14 at 12:14
  • Reniuz you are right. The usercontrol load method was already accessing the connectionsstring at design time I moved the code to another method and it works – Sybren Oct 07 '14 at 12:28

0 Answers0