父窗体,子窗体连接数据库使用公共变量的问题, 大哥大姐,小弟分不多了,全给了,谢谢赐教
我的办法是新建一个Form, 然后把Form的IsMdiContainer 属性改为 True
在.net Windows 程序的主窗体里面通过如下的方式打开数据库. 
首先定义连接数据库的变量
  private string  connStr;   
public System.Data.OleDb.OleDbConnection conn;//定义为公共变量, 因为别的子Form 需要用到此conn连接数据库在父窗体的Form_Load 事件中连接数据库
private void Form1_Load(object sender, System.EventArgs e) // Form_load 时候打开
{
connStr = @"Provider=SQLOLEDB.1;Password=IEB;Persist Security Info=True;User ID=IEB;Initial Catalog=CUST;Data Source=10.64.2.80";
conn = new System.Data.OleDb.OleDbConnection(connStr);
conn.Open();
}如果在父窗体中添加一个按钮和dataGRid控件
private void button1_Click(object sender, System.EventArgs e) //执行sql
{
string sql;
sql="select dd,qty from test";
System.Data.OleDb.OleDbDataAdapter ada = new System.Data.OleDb.OleDbDataAdapter(sql,conn);
System.Data.DataSet ds  = new DataSet();
ada.Fill(ds);
if(ds.Tables[0].Rows.Count > 0)
{
MessageBox.Show("数据存在");
this.dataGrid1.DataSource = ds.Tables[0]; // DataGrid 控件附数据源
}
}
例如上述的代码,则数据可以读出来.然后在父窗体上再加上菜单控件,在菜单下打开Form2,
private void menuItem3_Click(object sender, System.EventArgs e)
{
Form2 fm2=new Form2();
fm2.MdiParent=this;
fm2.Show();
}我想在Form2上也添加一个按钮和一个DataGrid控件, 实现把数据读出来然后显示在DataGrid 里面, 现在遇到的问题如下, Form2上的按钮下的代码和父窗体中按钮的代码相同private void button1_Click(object sender, System.EventArgs e) //执行sql
{
string sql;
sql="select dd,qty from test";
System.Data.OleDb.OleDbDataAdapter ada = new System.Data.OleDb.OleDbDataAdapter(sql,conn);
System.Data.DataSet ds  = new DataSet();
ada.Fill(ds);
if(ds.Tables[0].Rows.Count > 0)
{
MessageBox.Show("数据存在");
this.dataGrid1.DataSource = ds.Tables[0]; // DataGrid 控件附数据源
}
}
只是在执行的时候
System.Data.OleDb.OleDbDataAdapter ada = new System.Data.OleDb.OleDbDataAdapter(sql,conn); 有问题,
因为conn 是在父窗体中定义的, 我如何把父窗体中的conn 传到Form2 子窗体中,也就是实现如下的功能, 在父窗体Form_Load 的时候,打开数据库,
以后子窗体中的数据操作都使用父窗体中的conn.
大哥大姐,小弟分不多了,全给了,谢谢赐教.
我在Form2 中定义了conn变量
public System.Data.OleDb.OleDbDataAdapter conn; //定义的conn ,用来从主窗体中接conn
然后在父窗体打开子窗体的事件中执行如下的代码
private void menuItem3_Click(object sender, System.EventArgs e)
{
Form2 fm2=new Form2();
fm2.MdiParent=this;
fm2.conn=this.conn;
fm2.Show();
}其中语句fm2.conn=this.conn;是想把父窗体中的conn传到子窗体,但是这句语法错误, 请问如何解决, 谢谢,好急啊

解决方案 »

  1.   

    直接在form2中操作form1中的conn就可以嘛
      

  2.   

    在Form2 定义private System.Data.OleDb.OleDbConnection conn;
    public System.Data.OleDb.OleDbConnection getconn
    {
       get
        {
           return conn
         }
       set
       {
    if (value != conn)
    {
    conn= value;
    }
       }然后在父窗体打开子窗体的事件中执行如下的代码
    private void menuItem3_Click(object sender, System.EventArgs e)
    {
    Form2 fm2=new Form2();
    fm2.MdiParent=this;
    fm2.getconn=this.conn;
    fm2.Show();
    }
    }
      

  3.   

    你可以把数据库连接写成一个静态变量,然后在Form2中直接引用form1.conn
    另外,看了你的代码,你最好是专门把数据库方面操作建一个类,在用到的地方直接引用或实例化
      

  4.   

    或者,你把conn变量设为public static 型变量,也可以解决这样的问题!
    也就是把CONN设为全局的通用变量!
      

  5.   

    public static string connStr;