以前写类时
protected SqlConnection cnServerZjz = new SqlConnection(ConfigurationSettings.AppSettings["数据库路径"]);
直接从web.config中读出数据库连接字符串,现在我想在类库中,也用类似方法来实现,我不知道该怎么写了,请大家请点。

解决方案 »

  1.   

    using System.Configuration;
    然后就可以照样读出来了。
      

  2.   

    楼上的为正解
    类库也是.cs文件
    和codebehind文件一样的
      

  3.   

    就这么简单吗?可是新建的类库中没有web.config,是说我在自己建一个吗?然后从中读取数据库连接字符串吗?
      

  4.   

    private static string SqlConnStr=ConfigurationSettings.AppSettings["strconn"];
      

  5.   

    你作的类库是被引用的吧!到时使用的web.config文件就是引用该类库的项目的web.config,而与类库无关!
      

  6.   

    配置是从调用方程序集的配置文件中读取的. 与当前的程序集无关.
    如果是web应用程序, 就从web.config中读取.
    如果是exe应该程序, 就从app.exe.config中读取.当然类库程序集也可以有自己的配置文件,不过这种配置方式不好处理.
      

  7.   

    我的建议是在类的构造函数中处理
    例如:
    public class DataBaseClass
    {   
    private string ConnStr;
    private OleDbConnection myConn;
    private OleDbDataAdapter Adpter;
    private OleDbCommand myComm;
    public  DataSet Dset; 
    public DataBaseClass(string AConnStr)
    {
    //
    // TODO: 在此处添加构造函数逻辑
    //
    ConnStr = AConnStr;
    }
    private int OpenConn()
    {
    if(myConn==null)
    {
    myConn = new OleDbConnection(ConnStr);
    }
    try
    {
    myConn.Open();
    return 1;
    }
    catch
    {
       return -1;//连接失败
    }
    }上面是我写的一个类的一部分(注释:其中负数为返回的错误编号  返回为1则执行成功)
      

  8.   

    protected SqlConnection cnServerZjz = new SqlConnection(ConfigurationSettings.AppSettings["数据库路径"]);
    public bool fillData(string strSql,System.Web.UI.WebControls.DataGrid FillGrid)
    {
    bool flag = true;
    cnServerZjz.Open();
    SqlDataAdapter daFillGrid = new SqlDataAdapter(strSql,cnServerZjz);
    try
    {
    DataSet ds = new DataSet();
    daFillGrid.Fill(ds,"table");
    FillGrid.DataSource = ds.Tables["table"];
    FillGrid.DataBind();

    }
    catch
    {
    flag = false;
    }
    finally
    {
    cnServerZjz.Close();
    }
    return flag;

    }
    这段程序单独在类文件中是正确的,一但放在了类库程序集中就不对了,我不明白为什么会在
    System.Web.UI.WebControls.DataGrid FillGrid这行出错,说是UI错少引用.
    为什么会这样呢?
      

  9.   

    如果类库也在WEB 下,可以着样写
      

  10.   

    你放在类库中,而FillGrid是一个控件,有界面显示的,怎么能行?你可以只返回一个DATASET