Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/cmake/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 将usercontrol移动到表单上会导致连接字符串出现空引用异常_C#_Winforms_User Controls - Fatal编程技术网

C# 将usercontrol移动到表单上会导致连接字符串出现空引用异常

C# 将usercontrol移动到表单上会导致连接字符串出现空引用异常,c#,winforms,user-controls,C#,Winforms,User Controls,我有一个带有sql连接字符串的usercontrol。connectionstring还可以,因为我已经对它进行了测试,并且能够从数据库中获取数据。每次尝试将usercontrol拖到Windows窗体上时,我都会得到一个NullReferenceException:对象引用未设置为对象的实例。我怎样才能解决这个问题 用户控制类 public partial class incidentCategoryMaintenance : UserControl { SqlConnecti

我有一个带有sql连接字符串的usercontrol。connectionstring还可以,因为我已经对它进行了测试,并且能够从数据库中获取数据。每次尝试将usercontrol拖到Windows窗体上时,我都会得到一个NullReferenceException:对象引用未设置为对象的实例。我怎样才能解决这个问题

用户控制类

    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>

我想,为了防止某些代码在winforms designer中执行,您必须检查哪些内容。您在设计时尝试访问ConfigurationManager.ConnectionString时出错,此时为空。Reniuz您是对的。usercontrol加载方法在设计时已经在访问ConnectionString了。我将代码移到了另一个方法,它就可以工作了