连接字符串未正确初始化

时间:2015-01-15 15:55:18

标签: c# sql connection-string sqlconnection

我一直收到连接字符串未正确初始化的错误。我检查了其他答案,但无法找到解决方案。我的连接字符串适用于我的应用程序的其他部分,但一个。通过ondatabound进行调试时,它会在Connection.open();

中给出错误
<connectionStrings>
<add name="SmartFormConnection" connectionString="Data Source=OAK-HRSA-DB01;Initial Catalog=ORHP_Dev;User ID=blah;Password=blah" providerName="System.Data.SqlClient"/>
</connectionStrings>

背后的代码

public class DataAccess
{
    private static DataAccess _me;

    public string ConnString { get; set; }

    private DataAccess()
    {
        ConnString = ConfigurationManager.ConnectionStrings["SmartFormConnection"].ConnectionString;
    }

    public static DataAccess SelfRef()
    {
        return _me ?? (_me = new DataAccess());
    }

    public SqlConnection GetConnection()
    {
        var  con = new SqlConnection {ConnectionString = ConnString};
        return con;
    }
}

第二课

Sql Connection _connection = DataAccess.SelfRef().GetConnection();


protected void SectionInstructionListBox_OnDataBound(Object sender, EventArgs e)
{

    var ctrl = (Control)sender;
    var panel = (Panel)ctrl.FindControl("NoDataReturnedPanel");
    var listbox = (ListBox)ctrl.FindControl("SectionInstructionListBox");

    var reportdropdownlist = ReportPeriodDropDownList.SelectedValue;
    var programdropdownlist = ProgramDropDownList.SelectedValue;
    var formsectionlistbox = FormSectionListBox.SelectedValue;


    var sectionInstructionTextBox = (TextBox)ctrl.FindControl("SectionInstructionTextBox");

    using (var connection = _connection)
    {
        try
        {
            if (FormSectionListBox.SelectedValue != "" && ReportPeriodDropDownList.SelectedValue != "" && ProgramDropDownList.SelectedValue != "")
            {
                if (connection != null && connection.State == ConnectionState.Closed)
                {
                    connection.Open();
                }
                String selectquery = "Select Instruction from Core.SectionInstruction where FormSectionID = " +
                                         formsectionlistbox + " AND DataCollectionPeriodID = " + reportdropdownlist +
                                         " AND ProgramID = " + programdropdownlist;

                var command = new SqlCommand(selectquery);

                command.Connection = connection;
                command.CommandType = CommandType.Text;
                sectionInstructionTextBox.Text = command.ExecuteScalar().ToString();
                sectionInstructionTextBox.DataBind();
            }
        }
        catch (Exception ex)
        {
            //Display error message
            ScriptManager.RegisterStartupScript(this, GetType(), "error", "alert('Error: " + ex.Message + "');",
                                                    true);
        }
    }

        panel.Visible = listbox.Items.Count == 0;
        listbox.Visible = listbox.Items.Count != 0;

}

0 个答案:

没有答案