C#新手问题寻求解答

[ExecuteReader 要求已打开且可用的 Connection。连接的当前状态为已关闭。请问大佬知道这个是什么原因吗?
源代码如下:
string name = textBox1.Text.Trim();
string password1 = textBox2.Text.Trim();
string password2 = textBox3.Text.Trim();
string Name = textBox4.Text.Trim();
string number = textBox5.Text.Trim();
if (name == “”)
{
MessageBox.Show(“用户名不能为空!”, “登录失败”, MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
if (password1 != password2)
{
MessageBox.Show(“两次输入的密码不一致!”, “登录失败”, MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
SqlConnection con = new SqlConnection();
con.ConnectionString = “Data source=(local);Initial Catalog=Management;Integrated Security=True”;

                SqlCommand cmd = new SqlCommand();
                cmd.CommandText = "select username from manager";
                cmd.Connection = con;
                SqlDataReader reader = cmd.ExecuteReader();
                while(reader.Read())
                {
                    string username = reader["username"].ToString();
                    if (name == username)
                    {
                        MessageBox.Show("用户名已存在!", "注册失败", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        
                    }
                      
                    else
                    {
                        string sql = "insert into manager(username,pwd,name,ID)values(" + name + "," + password1 + "," + Name + "," + number + ")";
                        try
                        {
                            
                            SqlCommand comm = new SqlCommand(sql, con);
                            int count = comm.ExecuteNonQuery();
                            if (count >= 0)
                            {
                                MessageBox.Show("注册成功,请前往登录", "注册成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
                            }
                            else
                                MessageBox.Show("注册失败", "注册失败", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show(ex.Message, "数据库出错!", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        }
                        finally
                        {
                            con.Close();
                        }
                        Form1 a = new Form1();
                        a.Show();
                        this.Visible=false;

                    }
                        
                }

            }
        }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值