从connection.cs文件调用连接字符串

时间:2013-05-05 16:35:23

标签: c# sqlconnection 3-tier

代码有问题吗?它没有工作并抛出异常对象ref。没有设置为对象的实例.. 代码行中的datageneric.cs文件中存在例外情况字符串DbConnectionString = Connection.ConnectionString;

connection.cs

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.Configuration;
    public static class Connection
    {
    private static string constr = "server=.;database=foood;";
        public static string ConnectionString
        {
    get
    {
        return constr;
    }
    set
    {
        constr = value;
    }
}
public static string ProviderName { get; set; }
static Connection()
{
    ConnectionString =WebConfigurationManager.ConnectionStrings["constring"].ConnectionString;
    ProviderName = WebConfigurationManager.ConnectionStrings["constring"].ProviderName;
}
    }

DataGeneric.cs

        public static DbCommand CreateCommand()
{
    DbCommand cmd=null;
    try
    {
        string DbConnectionString = Connection.ConnectionString;
        string DbProviderName = Connection.ProviderName;
        DbProviderFactory factory = DbProviderFactories.GetFactory(DbProviderName);
        DbConnection conn = factory.CreateConnection();
        conn.ConnectionString = DbConnectionString;
        cmd = conn.CreateCommand();
        cmd.CommandType = CommandType.Text;
    }
    catch (Exception ex) { }
    return cmd;
}

GetData.cs

        public static DataTable gimmedata()
{
    string Query = "select * from [slider]";
    DbCommand cmd = DataGeneric.CreateCommand();
    cmd.CommandText = Query;
    DataTable dt = DataGeneric.ExecuteSelectCommand(cmd);
    return dt;
}

Default.aspx.cs

protected void Page_Load(object sender, EventArgs e)
{
    DataTable dt = GetData.gimmedata();
    GridView1.DataSource = dt;
    GridView1.DataBind();

}

1 个答案:

答案 0 :(得分:1)

您的连接类是public static。因此,要使用其变量,请在object中创建DataGeneric.cs,然后通过该对象访问该类。

Connection con = new Connection();

string DbConnectionString = con.ConnectionString;

希望有效。