C/S中的C#初学者遇到一个小问题
主窗品Form1,也是容器,代码如下:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data.OleDb;
namespace xuesan
{
public partial class xuesan : Form
{
private static OleDbConnection conn = null;
public xuesan()
{
InitializeComponent();
}
public static OleDbConnection getConnection()
{
if(conn==null)
{
conn = new OleDbConnection( "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=123.mdb "); //HrSalary
conn.Open();
}
return conn;
}
private void button1_Click(object sender, EventArgs e)
{
Form2 p = new Form2();
p.ShowDialog();
}
public bool has(string formName)
{
bool result = false;
for (int i = 0; i < this.MdiChildren.Length; i++)
{
if (this.MdiChildren[i].Name == formName)
{
result = true;
break;
}
else
{
result = false;
}
}
return result;
}
public Form showModal(string formName)
{
for (int i = 0; i < this.MdiChildren.Length; i++)
{
if (this.MdiChildren[i].Name == formName)
{
this.MdiChildren[i].Activate();
return this.MdiChildren[i]; ;
}
}
return null;
}
private void button2_Click(object sender, EventArgs e)
{
this.Close();
Application.Exit();
}
private void xuesan_FormClosed(object sender, FormClosedEventArgs e)
{
if (conn != null)
conn.Close();
}
private void xuesan_Load(object sender, EventArgs e)
{
}
}
}
==================================================
Form2窗体
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data.OleDb;
namespace xuesan
{
public partial class Form2 : Form
{
private static OleDbConnection conn = null;
public Form2()
{
InitializeComponent();
}
private void Form2_Load(object sender, EventArgs e)
{
string sql = "select user_name from users ";
if (conn == null) conn = Form1.getConnection();
OleDbCommand cmd = conn.CreateCommand();
cmd.CommandText = sql;
OleDbDataReader reader = cmd.ExecuteReader();
reader.Close();
cmd.Dispose();
}
}
}
============================
错误提示,在FORM2中调用数据库时,说上下文不存在FORM1,也就是
if (conn == null) conn = Form1.getConnection();
应该如何改?
[解决办法]
你已经把它命名为xuesan了,还哪来的Form1
public partial class xuesan : Form
这样试下
if (conn == null) conn = xuesan.getConnection();