为什么ConnectionString没有初始化错误

时间:2015-03-27 20:00:55

标签: c# asp.net connection-string

内容页面:

protected void Page_Load(object sender, EventArgs e)
{
    string gs = ConfigurationManager.ConnectionStrings["ging"].ConnectionString;
    if (Master.showCheck(s))
    {
        //do something...
    }
}

母版:

string gs = "";
protected void Page_Load(object sender, EventArgs e)
{
    gs = ConfigurationManager.ConnectionStrings["ging"].ConnectionString;
}
public bool showCheck(string strID)
{
    string strCheckIfParentExist = @"";

    using (SqlConnection scConn = new SqlConnection(gs))
    {
        scConn.Open(); //throws an error: 'The ConnectionString property has not been initialized'
    }
}

为什么会收到以下错误:The ConnectionString property has not been initialized

2 个答案:

答案 0 :(得分:1)

更改

protected void Page_Load(object sender, EventArgs e)
{
    string gs = ConfigurationManager.ConnectionStrings["ging"].ConnectionString;
}
public bool showCheck(string strID)
{
    string strCheckIfParentExist = @"";

    using (SqlConnection scConn = new SqlConnection(gs))
    {
        scConn.Open(); //throws an error: 'The ConnectionString property has not been initialized'
    }
}

private string gs = "";
protected void Page_Load(object sender, EventArgs e)
{
    gs = ConfigurationManager.ConnectionStrings["ging"].ConnectionString;
}
public bool showCheck(string strID)
{
    string strCheckIfParentExist = @"";

    using (SqlConnection scConn = new SqlConnection(gs))
    {
        scConn.Open(); //throws an error: 'The ConnectionString property has not been initialized'
    }
}

基本上,你的变量是以与你调用它的方式不同的方式声明的,所以你只需要将它的范围扩大到类。

答案 1 :(得分:1)

如果你有" gs"作为类成员,将内容页面更改为

protected void Page_Load(object sender, EventArgs e)
{
    gs = ConfigurationManager.ConnectionStrings["ging"].ConnectionString;
    if (Master.showCheck(s))
    {
        //do something...
    }
}

字符串def你有类成员的影子。