在表单上移动用户控件会为连接字符串提供空引用异常

时间:2014-10-07 12:06:03

标签: c# winforms user-controls

我有一个带有sql连接字符串的usercontrol。连接字符串是可以的,因为我已经测试了它,我能够从数据库中获取数据。每当我尝试将usercontrol拖到我的Windows窗体上时,我都会得到一个NullReferenceException:对象引用未设置为对象的实例。我该如何解决这个问题?

Usercontrol类

    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>

0 个答案:

没有答案