namespace WindowsFormsApplication2
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
if (textBox1.Text == "")
{
MessageBox.Show("请输入数据库名称");
}
else
{
try
{
string str = "server=.;database=" + textBox1.Text.Trim() + "uid = sa;pwd = 123456";
SqlConnection conn = new SqlConnection(str);
conn.Open();
if (conn.State == ConnectionState.Open)
{
MessageBox.Show("连接成功");
}
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
textBox1.Text = "";
}
}
}
private void button2_Click(object sender, EventArgs e)
{
try
{
string str = "";
SqlConnection conn = new SqlConnection(str);
conn.Close();
if(conn.State == ConnectionState.Closed)
{
str = "数据库已经成功关闭\n";
}
conn.Open();
if(conn.State == ConnectionState.Open)
{
str = "数据库已经成功打开\n";
}
richTextBox1.Text = str;
}
catch(Exception ex)
{
richTextBox1.Text = ex.Message;
}
}
private void button3_Click(object sender, EventArgs e)
{
try
{
conn.Dispose();
conn.Open();
}
catch (Exception ex)
{
richTextBox1.Text = ex.Message;
}
}
}
}
在button3的代码中 软件提示 conn.dispose();代码错误的 上下文不存在conn。请问如何修改代码